Skip to content

Commit ff58ea7

Browse files
committed
select+with
1 parent 9e9a48f commit ff58ea7

File tree

2 files changed

+16
-0
lines changed

2 files changed

+16
-0
lines changed

select.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -587,3 +587,8 @@ func (b SelectBuilder) Alias(table string, prefix ...string) alias {
587587
prefix: prefix,
588588
}
589589
}
590+
591+
// With adds a CTE (Common Table Expression) to the query.
592+
func (b SelectBuilder) With(cteName string, cte SelectBuilder) SelectBuilder {
593+
return b.PrefixExpr(cte.Prefix(fmt.Sprintf("WITH %s AS (", cteName)).Suffix(")"))
594+
}

select_test.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -518,3 +518,14 @@ func TestTableAlias(t *testing.T) {
518518
assert.NoError(t, err)
519519
assert.Equal(t, "SELECT u.id AS pref_id, u.name AS pref_name FROM users u GROUP BY u.id AS pref_id, u.name AS pref_name ORDER BY u.id AS pref_id", sql)
520520
}
521+
522+
func TestSelectWith(t *testing.T) {
523+
q := Select().
524+
With("table1", Select("a").From("table2")).
525+
Columns("a").
526+
From("table3")
527+
528+
sql, _, err := q.ToSql()
529+
assert.NoError(t, err)
530+
assert.Equal(t, "WITH table1 AS ( SELECT a FROM table2 ) SELECT a FROM table3", sql)
531+
}

0 commit comments

Comments
 (0)