gitee.com/eden-framework/sqlx@v0.0.3/builder/assignment.go (about) 1 package builder 2 3 import ( 4 "context" 5 "math" 6 ) 7 8 type SqlAssignment interface { 9 SqlExpr 10 SqlAssignmentMarker 11 } 12 13 type SqlAssignmentMarker interface { 14 asCondition() 15 } 16 17 func WriteAssignments(e *Ex, assignments ...*Assignment) { 18 count := 0 19 20 for i := range assignments { 21 a := assignments[i] 22 23 if IsNilExpr(a) { 24 continue 25 } 26 27 if count > 0 { 28 e.WriteString(", ") 29 } 30 31 e.WriteExpr(a) 32 count++ 33 } 34 } 35 36 func ColumnsAndValues(columnOrColumns SqlExpr, values ...interface{}) *Assignment { 37 lenOfColumn := 1 38 if canLen, ok := columnOrColumns.(interface{ Len() int }); ok { 39 lenOfColumn = canLen.Len() 40 } 41 return &Assignment{columnOrColumns: columnOrColumns, lenOfColumn: lenOfColumn, values: values} 42 } 43 44 type Assignments []*Assignment 45 46 type Assignment struct { 47 SqlAssignmentMarker 48 49 columnOrColumns SqlExpr 50 lenOfColumn int 51 52 values []interface{} 53 } 54 55 func (a *Assignment) IsNil() bool { 56 return a == nil || IsNilExpr(a.columnOrColumns) || len(a.values) == 0 57 } 58 59 func (a *Assignment) Ex(ctx context.Context) *Ex { 60 e := Expr("") 61 62 useValues := TogglesFromContext(ctx).Is(ToggleUseValues) 63 64 if useValues { 65 e.WriteGroup(func(e *Ex) { 66 e.WriteExpr(ExprBy(func(ctx context.Context) *Ex { 67 return a.columnOrColumns.Ex(ContextWithToggles(ctx, Toggles{ 68 ToggleMultiTable: false, 69 })) 70 })) 71 }) 72 73 if len(a.values) == 1 { 74 if s, ok := a.values[0].(SelectStatement); ok { 75 e.WriteByte(' ') 76 e.WriteExpr(s) 77 return e.Ex(ctx) 78 } 79 } 80 81 e.WriteString(" VALUES ") 82 83 groupCount := int(math.Round(float64(len(a.values)) / float64(a.lenOfColumn))) 84 85 for i := 0; i < groupCount; i++ { 86 if i > 0 { 87 e.WriteByte(',') 88 } 89 90 e.WriteGroup(func(e *Ex) { 91 for j := 0; j < a.lenOfColumn; j++ { 92 e.WriteHolder(j) 93 } 94 }) 95 } 96 97 e.AppendArgs(a.values...) 98 99 return e.Ex(ctx) 100 } 101 102 e.WriteExpr(ExprBy(func(ctx context.Context) *Ex { 103 return a.columnOrColumns.Ex(ContextWithToggles(ctx, Toggles{ 104 ToggleMultiTable: false, 105 })) 106 })) 107 108 e.WriteString(" = ?") 109 e.AppendArgs(a.values[0]) 110 111 return e.Ex(ctx) 112 }