github.com/octohelm/storage@v0.0.0-20240516030302-1ac2cc1ea347/pkg/sqlbuilder/alias.go (about) 1 package sqlbuilder 2 3 import ( 4 "context" 5 ) 6 7 func Alias(expr SqlExpr, name string) SqlExpr { 8 return &exAlias{ 9 name: name, 10 SqlExpr: expr, 11 } 12 } 13 14 type exAlias struct { 15 name string 16 SqlExpr 17 } 18 19 func (alias *exAlias) IsNil() bool { 20 return alias == nil || alias.name == "" || IsNilExpr(alias.SqlExpr) 21 } 22 23 func (alias *exAlias) Ex(ctx context.Context) *Ex { 24 return Expr("? AS ?", alias.SqlExpr, Expr(alias.name)).Ex(ContextWithToggles(ctx, Toggles{ 25 ToggleNeedAutoAlias: false, 26 })) 27 } 28 29 func MultiMayAutoAlias(columns ...SqlExpr) SqlExpr { 30 return &exMayAutoAlias{ 31 columns: columns, 32 } 33 } 34 35 type exMayAutoAlias struct { 36 columns []SqlExpr 37 } 38 39 func (alias *exMayAutoAlias) IsNil() bool { 40 return alias == nil || len(alias.columns) == 0 41 } 42 43 func (alias *exMayAutoAlias) Ex(ctx context.Context) *Ex { 44 e := Expr("") 45 e.Grow(1) 46 47 RangeNotNilExpr(alias.columns, func(expr SqlExpr, i int) { 48 if i > 0 { 49 e.WriteQuery(", ") 50 } 51 e.WriteExpr(expr) 52 }) 53 54 return e.Ex(ContextWithToggles(ctx, Toggles{ 55 ToggleNeedAutoAlias: true, 56 })) 57 }