github.com/kunlun-qilian/sqlx/v3@v3.0.0/builder/toggles.go (about)

     1  package builder
     2  
     3  import (
     4  	"context"
     5  
     6  	contextx "github.com/go-courier/x/context"
     7  )
     8  
     9  var (
    10  	ToggleMultiTable    = "MultiTable"
    11  	ToggleNeedAutoAlias = "NeedAlias"
    12  	ToggleUseValues     = "UseValues"
    13  )
    14  
    15  type Toggles map[string]bool
    16  
    17  func (toggles Toggles) Merge(next Toggles) Toggles {
    18  	final := Toggles{}
    19  
    20  	for k, v := range toggles {
    21  		if v {
    22  			final[k] = true
    23  		}
    24  	}
    25  
    26  	for k, v := range next {
    27  		if v {
    28  			final[k] = true
    29  		} else {
    30  			delete(final, k)
    31  		}
    32  	}
    33  
    34  	return final
    35  }
    36  
    37  func (toggles Toggles) Is(key string) bool {
    38  	if v, ok := toggles[key]; ok {
    39  		return v
    40  	}
    41  	return false
    42  }
    43  
    44  type contextKeyForToggles struct {
    45  }
    46  
    47  func ContextWithToggles(ctx context.Context, toggles Toggles) context.Context {
    48  	return contextx.WithValue(ctx, contextKeyForToggles{}, TogglesFromContext(ctx).Merge(toggles))
    49  }
    50  
    51  func TogglesFromContext(ctx context.Context) Toggles {
    52  	if ctx == nil {
    53  		return Toggles{}
    54  	}
    55  	if toggles, ok := ctx.Value(contextKeyForToggles{}).(Toggles); ok {
    56  		return toggles
    57  	}
    58  	return Toggles{}
    59  }