Skip to content

Commit

Permalink
entc/integration: add examples for sub-queries + minor fixed for sele…
Browse files Browse the repository at this point in the history
…ctor builder (#2509)

* dialect/sql: move FROM to inside switch

* dialect/sql: adds simple example of subquery usage

* dialect/sql: adds a more complex example with join

* Apply suggestions from code review

Co-authored-by: Ariel Mashraki <7413593+a8m@users.noreply.github.com>

* dialect/sql: fix missing type and change modify to where

Co-authored-by: Ariel Mashraki <7413593+a8m@users.noreply.github.com>
  • Loading branch information
crossworth and a8m committed May 5, 2022
1 parent 0c75ffc commit 4d1c0af
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 1 deletion.
4 changes: 3 additions & 1 deletion dialect/sql/builder.go
Expand Up @@ -2657,19 +2657,21 @@ func (s *Selector) Query() (string, []interface{}) {
} else {
b.WriteString("*")
}
b.WriteString(" FROM ")
switch t := s.from.(type) {
case *SelectTable:
b.WriteString(" FROM ")
t.SetDialect(s.dialect)
b.WriteString(t.ref())
case *Selector:
b.WriteString(" FROM ")
t.SetDialect(s.dialect)
b.Nested(func(b *Builder) {
b.Join(t)
})
b.WriteString(" AS ")
b.Ident(t.as)
case *WithBuilder:
b.WriteString(" FROM ")
t.SetDialect(s.dialect)
b.Ident(t.Name())
}
Expand Down
8 changes: 8 additions & 0 deletions dialect/sql/builder_test.go
Expand Up @@ -1288,6 +1288,14 @@ func TestBuilder(t *testing.T) {
wantQuery: "WITH `groups` AS (SELECT * FROM `groups` WHERE `name` = ?) SELECT `age` FROM `groups`",
wantArgs: []interface{}{"bar"},
},
{
input: SelectExpr(Raw("1")),
wantQuery: "SELECT 1",
},
{
input: Select("*").From(SelectExpr(Raw("1")).As("s")),
wantQuery: "SELECT * FROM (SELECT 1) AS `s`",
},
{
input: func() Querier {
builder := Dialect(dialect.Postgres)
Expand Down
25 changes: 25 additions & 0 deletions entc/integration/integration_test.go
Expand Up @@ -680,6 +680,31 @@ func Select(t *testing.T, client *ent.Client) {
require.Len(gs, 2)
require.Equal(hub.QueryUsers().CountX(ctx), gs[0].UsersCount)
require.Equal(lab.QueryUsers().CountX(ctx), gs[1].UsersCount)

// Select Subquery.
t.Log("select subquery")
i, err := client.User.
Query().
Modify(func(s *sql.Selector) {
subQuery := sql.SelectExpr(sql.Raw("1")).As("s")
s.Select("*").From(subQuery)
}).
Int(ctx)
require.NoError(err)
require.Equal(1, i)

// Select with join.
u = client.User.Create().SetName("crossworth").SetAge(28).SaveX(ctx)
id := client.User.
Query().
Where(func(s *sql.Selector) {
subQuery := sql.Select(user.FieldID).
From(sql.Table(user.Table)).
Where(sql.EQ(s.C(user.FieldName), "crossworth"))
s.Join(subQuery).On(s.C(user.FieldID), subQuery.C(user.FieldID))
}).
OnlyIDX(ctx)
require.Equal(u.ID, id)
}

func ExecQuery(t *testing.T, client *ent.Client) {
Expand Down

0 comments on commit 4d1c0af

Please sign in to comment.