Skip to content

Commit 0924ebe

Browse files
committed
add column select
1 parent ec51b45 commit 0924ebe

File tree

2 files changed

+40
-1
lines changed

2 files changed

+40
-1
lines changed

sqlx/select.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,12 @@ func (self *SelectStatement) ColumnAs(column string, alias string) *SelectStatem
3737
return self
3838
}
3939

40+
func (self *SelectStatement) ColumnSelect(stmt *SelectStatement, alias string) *SelectStatement {
41+
stmt.setDepth(self.depth + 1)
42+
self.columns = append(self.columns, As(stmt, alias))
43+
return self
44+
}
45+
4046
func (self *SelectStatement) From(from string) *SelectStatement {
4147
self.from = Raw(from)
4248
return self

sqlx/select_test.go

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,38 @@ import (
77
)
88

99
func TestSelect(t *testing.T) {
10+
t.Run("column", func(t *testing.T) {
11+
t.Run("string", func(t *testing.T) {
12+
sql := sqlx.Select("a", "b", "c").Sql()
13+
14+
if sql != "SELECT a, b, c;" {
15+
t.Fatalf(sql)
16+
}
17+
})
18+
19+
t.Run("select", func(t *testing.T) {
20+
sql := sqlx.Select().ColumnSelect(
21+
sqlx.Select("a", "b", "c").From("test"),
22+
"results",
23+
).Sql()
24+
25+
if sql != "SELECT (SELECT a, b, c FROM test) as \"results\";" {
26+
t.Fatalf(sql)
27+
}
28+
})
29+
30+
t.Run("string and select", func(t *testing.T) {
31+
sql := sqlx.Select("1", "2").ColumnSelect(
32+
sqlx.Select("a", "b", "c").From("test"),
33+
"results",
34+
).Sql()
35+
36+
if sql != "SELECT 1, 2, (SELECT a, b, c FROM test) as \"results\";" {
37+
t.Fatalf(sql)
38+
}
39+
})
40+
})
41+
1042
t.Run("from", func(t *testing.T) {
1143
t.Run("string", func(t *testing.T) {
1244
sql := sqlx.Select("a", "b", "c").From("test").Sql()
@@ -64,6 +96,7 @@ func TestSelect(t *testing.T) {
6496
"a", "b", "c",
6597
).From("test").Where(
6698
sqlx.And(
99+
sqlx.Raw("c = c"),
67100
sqlx.And(
68101
sqlx.Raw("a = b"),
69102
sqlx.Raw("b = c"),
@@ -75,7 +108,7 @@ func TestSelect(t *testing.T) {
75108
),
76109
).Sql()
77110

78-
if sql != "SELECT a, b, c FROM test WHERE (a = b AND b = c) AND (a = b OR b = c);" {
111+
if sql != "SELECT a, b, c FROM test WHERE c = c AND (a = b AND b = c) AND (a = b OR b = c);" {
79112
t.Fatalf(sql)
80113
}
81114
})

0 commit comments

Comments
 (0)