Skip to content

Commit f3ddf55

Browse files
guyyakirido50
authored andcommitted
Add ability to select using indirect values.
ADD: add the option to pass indirect values to select statement columns
1 parent 2f64be1 commit f3ddf55

File tree

1 file changed

+21
-2
lines changed

1 file changed

+21
-2
lines changed

select.go

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ type SelectStmt struct {
5252
queryer Queryer
5353
DistinctColumns []string
5454
Columns []string
55+
IndirectColumns []IndirectValue
5556
Joins []JoinClause
5657
Conditions []WhereCondition
5758
Ordering []SQLStmt
@@ -183,6 +184,13 @@ func (tx *Tx) Select(cols ...string) *SelectStmt {
183184
}
184185
}
185186

187+
// InDirectColumns adds sqlz.IndirectValue columns to the statement.
188+
// This can be useful when using database function inside the select statement
189+
func (stmt *SelectStmt) InDirectColumns(cols ...IndirectValue) *SelectStmt {
190+
stmt.IndirectColumns = append([]IndirectValue{}, cols...)
191+
return stmt
192+
}
193+
186194
// Distinct marks the statements as a SELECT DISTINCT
187195
// statement
188196
func (stmt *SelectStmt) Distinct(cols ...string) *SelectStmt {
@@ -387,10 +395,21 @@ func (stmt *SelectStmt) ToSQL(rebind bool) (asSQL string, bindings []interface{}
387395
}
388396
}
389397

390-
if len(stmt.Columns) == 0 {
398+
if len(stmt.Columns) == 0 && len(stmt.IndirectColumns) == 0 {
391399
clauses = append(clauses, "*")
392400
} else {
393-
clauses = append(clauses, strings.Join(stmt.Columns, ", "))
401+
columnsClauses := make([]string, 0)
402+
if len(stmt.Columns) > 0 {
403+
columnsClauses = append(columnsClauses, stmt.Columns...)
404+
}
405+
406+
if len(stmt.IndirectColumns) > 0 {
407+
for _, indirectColumn := range stmt.IndirectColumns {
408+
bindings = append(bindings, indirectColumn.Bindings...)
409+
columnsClauses = append(columnsClauses, indirectColumn.Reference)
410+
}
411+
}
412+
clauses = append(clauses, strings.Join(columnsClauses, ", "))
394413
}
395414

396415
if len(stmt.Table) > 0 {

0 commit comments

Comments
 (0)