Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added ReplaceColumns method #190

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
9 changes: 9 additions & 0 deletions select.go
Expand Up @@ -256,6 +256,15 @@ func (b SelectBuilder) Column(column interface{}, args ...interface{}) SelectBui
return builder.Append(b, "Columns", newPart(column, args...)).(SelectBuilder)
}

// ReplaceColumns replaces the query columns
func (b SelectBuilder) ReplaceColumns(columns ...string) SelectBuilder {
var parts []Sqlizer
for _, str := range columns {
parts = append(parts, newPart(str))
}
return builder.Set(b, "Columns", parts).(SelectBuilder)
}

// From sets the FROM clause of the query.
func (b SelectBuilder) From(from string) SelectBuilder {
return builder.Set(b, "From", newPart(from)).(SelectBuilder)
Expand Down
47 changes: 47 additions & 0 deletions select_test.go
Expand Up @@ -53,6 +53,53 @@ func TestSelectBuilderToSql(t *testing.T) {
assert.Equal(t, expectedArgs, args)
}

func TestReplaceColumnsBuilderToSql(t *testing.T) {
subQ := Select("aa", "bb").From("dd")
b := Select("a", "b").
Prefix("WITH prefix AS ?", 0).
Distinct().
Columns("c").
Column("IF(d IN ("+Placeholders(3)+"), 1, 0) as stat_column", 1, 2, 3).
Column(Expr("a > ?", 100)).
Column(Alias(Eq{"b": []int{101, 102, 103}}, "b_alias")).
Column(Alias(subQ, "subq")).
From("e").
JoinClause("CROSS JOIN j1").
Join("j2").
LeftJoin("j3").
RightJoin("j4").
Where("f = ?", 4).
Where(Eq{"g": 5}).
Where(map[string]interface{}{"h": 6}).
Where(Eq{"i": []int{7, 8, 9}}).
Where(Or{Expr("j = ?", 10), And{Eq{"k": 11}, Expr("true")}}).
GroupBy("l").
Having("m = n").
OrderByClause("? DESC", 1).
OrderBy("o ASC", "p DESC").
Limit(12).
Offset(13).
Suffix("FETCH FIRST ? ROWS ONLY", 14)

b = b.ReplaceColumns("z")

sql, args, err := b.ToSql()
assert.NoError(t, err)

expectedSql :=
"WITH prefix AS ? " +
"SELECT DISTINCT z " +
"FROM e " +
"CROSS JOIN j1 JOIN j2 LEFT JOIN j3 RIGHT JOIN j4 " +
"WHERE f = ? AND g = ? AND h = ? AND i IN (?,?,?) AND (j = ? OR (k = ? AND true)) " +
"GROUP BY l HAVING m = n ORDER BY ? DESC, o ASC, p DESC LIMIT 12 OFFSET 13 " +
"FETCH FIRST ? ROWS ONLY"
assert.Equal(t, expectedSql, sql)

expectedArgs := []interface{}{0, 4, 5, 6, 7, 8, 9, 10, 11, 1, 14}
assert.Equal(t, expectedArgs, args)
}

func TestSelectBuilderFromSelect(t *testing.T) {
subQ := Select("c").From("d").Where(Eq{"i": 0})
b := Select("a", "b").FromSelect(subQ, "subq")
Expand Down