github.com/machinefi/w3bstream@v1.6.5-rc9.0.20240426031326-b8c7c4876e72/pkg/depends/kit/sqlx/builder/builder_assignment.go (about) 1 package builder 2 3 import ( 4 "context" 5 "math" 6 ) 7 8 type Assignment struct { 9 AssignmentMarker 10 11 columns SqlExpr 12 values []interface{} 13 colc int 14 } 15 16 func ColumnsAndValues(columns SqlExpr, values ...interface{}) *Assignment { 17 colc := 1 18 if canLen, ok := columns.(interface{ Len() int }); ok { 19 colc = canLen.Len() 20 } 21 return &Assignment{colc: colc, values: values, columns: columns} 22 } 23 24 func (a *Assignment) IsNil() bool { 25 return a == nil || IsNilExpr(a.columns) || len(a.values) == 0 26 } 27 28 func (a *Assignment) Ex(ctx context.Context) *Ex { 29 e := Expr("") 30 e.Grow(len(a.values)) 31 32 if TogglesFromContext(ctx).Is(ToggleUseValues) { 33 e.WriteGroup(func(e *Ex) { 34 e.WriteExpr(ExprBy(func(ctx context.Context) *Ex { 35 return a.columns.Ex(ContextWithToggleMultiTable(ctx, false)) 36 })) 37 }) 38 if len(a.values) == 1 { 39 if expr, ok := a.values[0].(SelectStatement); ok { 40 e.WriteQueryByte(' ') 41 e.WriteExpr(expr) 42 return e.Ex(ctx) 43 } 44 } 45 e.WriteQuery(" VALUES ") 46 47 groupCount := int(math.Round(float64(len(a.values)) / float64(a.colc))) 48 for i := 0; i < groupCount; i++ { 49 if i > 0 { 50 e.WriteQueryByte(',') 51 } 52 e.WriteGroup(func(e *Ex) { 53 for j := 0; j < a.colc; j++ { 54 e.WriteHolder(j) 55 } 56 }) 57 } 58 e.AppendArgs(a.values...) 59 return e.Ex(ctx) 60 } 61 62 e.WriteExpr(ExprBy(func(ctx context.Context) *Ex { 63 return a.columns.Ex(ContextWithToggleMultiTable(ctx, false)) 64 })) 65 e.WriteQuery(" = ?") 66 e.AppendArgs(a.values[0]) 67 return e.Ex(ctx) 68 } 69 70 type Assignments []*Assignment 71 72 func WriteAssignments(e *Ex, assignments ...*Assignment) { 73 count := 0 74 for i := range assignments { 75 a := assignments[i] 76 if IsNilExpr(a) { 77 continue 78 } 79 if count > 0 { 80 e.WriteQuery(", ") 81 } 82 e.WriteExpr(a) 83 count++ 84 } 85 } 86 87 type AssignmentMarker interface { 88 asCondition() 89 } 90 91 type SqlAssignment interface { 92 SqlExpr 93 AssignmentMarker 94 }