github.com/machinefi/w3bstream@v1.6.5-rc9.0.20240426031326-b8c7c4876e72/pkg/depends/kit/sqlx/builder/builder_toggle.go (about) 1 package builder 2 3 import ( 4 "context" 5 6 "github.com/machinefi/w3bstream/pkg/depends/x/contextx" 7 ) 8 9 type Toggles map[string]bool 10 11 const ( 12 ToggleNeedAutoAlias = "NeedAlias" 13 ToggleMultiTable = "MultiTable" 14 ToggleUseValues = "UseValues" 15 ) 16 17 func (toggles Toggles) Merge(follows Toggles) Toggles { 18 final := Toggles{} 19 for k, v := range toggles { 20 if v { 21 final[k] = true 22 } 23 } 24 for k, v := range follows { 25 if v { 26 final[k] = true 27 } else { 28 delete(final, k) 29 } 30 } 31 return final 32 } 33 34 func (toggles Toggles) Is(k string) bool { 35 v, ok := toggles[k] 36 return ok && v 37 } 38 39 type ctxKeyToggles struct{} 40 41 func ContextWithToggles(ctx context.Context, toggles Toggles) context.Context { 42 return contextx.WithValue( 43 ctx, 44 ctxKeyToggles{}, 45 TogglesFromContext(ctx).Merge(toggles), 46 ) 47 } 48 49 func ContextWithToggleMultiTable(ctx context.Context, v bool) context.Context { 50 return ContextWithToggles(ctx, Toggles{ToggleMultiTable: v}) 51 } 52 53 func ContextWithToggleUseValues(ctx context.Context, v bool) context.Context { 54 return ContextWithToggles(ctx, Toggles{ToggleUseValues: v}) 55 } 56 57 func ContextWithToggleNeedAutoAlias(ctx context.Context, v bool) context.Context { 58 return ContextWithToggles(ctx, Toggles{ToggleNeedAutoAlias: v}) 59 } 60 61 func TogglesFromContext(ctx context.Context) Toggles { 62 if ctx == nil { 63 return Toggles{} 64 } 65 if toggles, ok := ctx.Value(ctxKeyToggles{}).(Toggles); ok { 66 return toggles 67 } 68 return Toggles{} 69 }