Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions internal/dbtest/db_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -291,6 +291,7 @@ func TestDB(t *testing.T) {
{testScanRawMessage},
{testPointers},
{testExists},
{testRecursiveCTEUnion},
{testScanTimeIntoString},
{testModelNonPointer},
{testBinaryData},
Expand Down Expand Up @@ -1347,6 +1348,55 @@ func testExists(t *testing.T, db *bun.DB) {
require.False(t, exists)
}

func testRecursiveCTEUnion(t *testing.T, db *bun.DB) {
if !db.Dialect().Features().Has(feature.CTE) {
t.Skip("CTE is not supported")
return
}

if db.Dialect().Name() == dialect.MSSQL {
t.Skip("MSSQL uses a different recursive CTE syntax")
return
}

type Model struct {
bun.BaseModel `bun:"test_models,alias:m"`
ID int64 `bun:",pk,autoincrement"`
Name string `bun:",notnull"`
ParentID *int64
}

mustResetModel(t, ctx, db, (*Model)(nil))

root := &Model{Name: "root"}
_, err := db.NewInsert().Model(root).Exec(ctx)
require.NoError(t, err)
child := &Model{Name: "child", ParentID: &root.ID}
_, err = db.NewInsert().Model(child).Exec(ctx)
require.NoError(t, err)
grand := &Model{Name: "grand", ParentID: &child.ID}
_, err = db.NewInsert().Model(grand).Exec(ctx)
require.NoError(t, err)

query := db.NewSelect().
WithRecursive("category_tree", db.NewSelect().
Model((*Model)(nil)).
Where("name LIKE ?", "%roo%").
UnionAll(
db.NewSelect().
Model((*Model)(nil)).
Join("JOIN ? AS ?", bun.Ident("category_tree"), bun.Ident("ct")).
JoinOn("?TableAlias.? = ?", bun.Ident("parent_id"), bun.Ident("ct.id")),
),
).
TableExpr("?", bun.Ident("category_tree")).
OrderExpr("id")

var cats []Model
require.NoError(t, query.Scan(ctx, &cats))
require.Equal(t, []string{"root", "child", "grand"}, []string{cats[0].Name, cats[1].Name, cats[2].Name})
}

func testScanTimeIntoString(t *testing.T, db *bun.DB) {
ctx := context.Background()

Expand Down
9 changes: 8 additions & 1 deletion query_base.go
Original file line number Diff line number Diff line change
Expand Up @@ -339,7 +339,14 @@ func (q *baseQuery) appendCTE(
b = append(b, " AS ("...)
}

b, err = cte.query.AppendQuery(gen, b)
if sq, ok := cte.query.(*SelectQuery); ok && gen.Dialect().Name() == dialect.SQLite {
saved := sq.skipUnionParens
sq.skipUnionParens = true
b, err = cte.query.AppendQuery(gen, b)
sq.skipUnionParens = saved
} else {
b, err = cte.query.AppendQuery(gen, b)
}
if err != nil {
return nil, err
}
Expand Down
24 changes: 17 additions & 7 deletions query_select.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,9 @@ type SelectQuery struct {
having []schema.QueryWithArgs
selFor schema.QueryWithArgs

union []union
comment string
union []union
skipUnionParens bool
comment string
}

var _ Query = (*SelectQuery)(nil)
Expand Down Expand Up @@ -537,7 +538,10 @@ func (q *SelectQuery) appendQuery(
b = append(b, "WITH _count_wrapper AS ("...)
}

if len(q.union) > 0 {
hasUnion := len(q.union) > 0
wrapUnion := !q.skipUnionParens

if hasUnion && wrapUnion {
b = append(b, '(')
}

Expand Down Expand Up @@ -665,17 +669,23 @@ func (q *SelectQuery) appendQuery(
}
}

if len(q.union) > 0 {
b = append(b, ')')
if hasUnion {
if wrapUnion {
b = append(b, ')')
}

for _, u := range q.union {
b = append(b, u.expr...)
b = append(b, '(')
if wrapUnion {
b = append(b, '(')
}
b, err = u.query.AppendQuery(gen, b)
if err != nil {
return nil, err
}
b = append(b, ')')
if wrapUnion {
b = append(b, ')')
}
}
}

Expand Down
Loading