github.com/octohelm/storage@v0.0.0-20240516030302-1ac2cc1ea347/pkg/sqlbuilder/stmt_select.go (about)

     1  package sqlbuilder
     2  
     3  import (
     4  	"context"
     5  )
     6  
     7  type SelectStatement interface {
     8  	SqlExpr
     9  	selectStatement()
    10  }
    11  
    12  func Select(sqlExpr SqlExpr, modifiers ...SqlExpr) *StmtSelect {
    13  	return &StmtSelect{
    14  		sqlExpr:   sqlExpr,
    15  		modifiers: modifiers,
    16  	}
    17  }
    18  
    19  type StmtSelect struct {
    20  	SelectStatement
    21  	sqlExpr   SqlExpr
    22  	table     Table
    23  	modifiers []SqlExpr
    24  	additions []Addition
    25  }
    26  
    27  func (s *StmtSelect) IsNil() bool {
    28  	return s == nil
    29  }
    30  
    31  func (s StmtSelect) From(table Table, additions ...Addition) *StmtSelect {
    32  	s.table = table
    33  	s.additions = additions
    34  	return &s
    35  }
    36  
    37  func (s *StmtSelect) Ex(ctx context.Context) *Ex {
    38  	multiTable := false
    39  
    40  	for i := range s.additions {
    41  		addition := s.additions[i]
    42  		if IsNilExpr(addition) {
    43  			continue
    44  		}
    45  
    46  		if addition.AdditionType() == AdditionJoin {
    47  			multiTable = true
    48  		}
    49  	}
    50  
    51  	if multiTable {
    52  		ctx = ContextWithToggles(ctx, Toggles{
    53  			ToggleMultiTable: multiTable,
    54  		})
    55  	}
    56  
    57  	e := Expr("SELECT")
    58  	e.Grow(len(s.additions) + 2)
    59  
    60  	if len(s.modifiers) > 0 {
    61  		for i := range s.modifiers {
    62  			e.WriteQueryByte(' ')
    63  			e.WriteExpr(s.modifiers[i])
    64  		}
    65  	}
    66  
    67  	sqlExpr := s.sqlExpr
    68  
    69  	if IsNilExpr(sqlExpr) {
    70  		sqlExpr = Expr("*")
    71  	}
    72  
    73  	e.WriteQueryByte(' ')
    74  	e.WriteExpr(sqlExpr)
    75  
    76  	if !IsNilExpr(s.table) {
    77  		e.WriteQuery(" FROM ")
    78  		e.WriteExpr(s.table)
    79  	}
    80  
    81  	WriteAdditions(e, s.additions...)
    82  
    83  	return e.Ex(ctx)
    84  }
    85  
    86  func ForUpdate() *OtherAddition {
    87  	return AsAddition(Expr("FOR UPDATE"))
    88  }