Skip to content

Commit a2acfba

Browse files
[release-22.0] fix sqlSelectLimit propagating to subqueries (#18716) (#18872)
Signed-off-by: ghostframe <[email protected]> Co-authored-by: vitess-bot[bot] <108069721+vitess-bot[bot]@users.noreply.github.com>
1 parent cbce157 commit a2acfba

File tree

2 files changed

+9
-2
lines changed

2 files changed

+9
-2
lines changed

go/test/endtoend/vtgate/misc_test.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -528,6 +528,13 @@ func TestSQLSelectLimit(t *testing.T) {
528528
utils.AssertMatches(t, conn, "select uid, msg from t7_xxhash order by uid", `[[VARCHAR("1") VARCHAR("a")] [VARCHAR("2") VARCHAR("b")]]`)
529529
utils.AssertMatches(t, conn, "(select uid, msg from t7_xxhash order by uid)", `[[VARCHAR("1") VARCHAR("a")] [VARCHAR("2") VARCHAR("b")]]`)
530530
utils.AssertMatches(t, conn, "select uid, msg from t7_xxhash order by uid limit 4", `[[VARCHAR("1") VARCHAR("a")] [VARCHAR("2") VARCHAR("b")] [VARCHAR("3") NULL] [VARCHAR("4") VARCHAR("a")]]`)
531+
532+
// Don't LIMIT subqueries
533+
utils.AssertMatches(t, conn, "select count(*) from (select uid, msg from t7_xxhash order by uid) as subquery", `[[INT64(6)]]`)
534+
utils.AssertMatches(t, conn, "select count(*) from (select 1 union all select 2 union all select 3) as subquery", `[[INT64(3)]]`)
535+
536+
utils.AssertMatches(t, conn, "select 1 union all select 2 union all select 3", `[[INT64(1)] [INT64(2)]]`)
537+
531538
/*
532539
planner does not support query with order by in union query. without order by the results are not deterministic for testing purpose
533540
utils.AssertMatches(t, conn, "select uid, msg from t7_xxhash union all select uid, msg from t7_xxhash order by uid", ``)

go/vt/sqlparser/normalizer.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -184,7 +184,7 @@ func (nz *normalizer) walkDown(node, _ SQLNode) bool {
184184
nz.inDerived++
185185
case *Select:
186186
nz.inSelect++
187-
if nz.selectLimit > 0 && node.Limit == nil {
187+
if nz.selectLimit > 0 && node.Limit == nil && nz.inSelect == 1 {
188188
node.Limit = &Limit{Rowcount: NewIntLiteral(strconv.Itoa(nz.selectLimit))}
189189
}
190190
case *AliasedExpr:
@@ -575,7 +575,7 @@ func shouldRewriteDatabaseFunc(in Statement) bool {
575575

576576
// rewriteUnion sets the SELECT limit for UNION statements if not already set.
577577
func (nz *normalizer) rewriteUnion(node *Union) {
578-
if nz.selectLimit > 0 && node.Limit == nil {
578+
if nz.selectLimit > 0 && node.Limit == nil && nz.inSelect == 0 {
579579
node.Limit = &Limit{Rowcount: NewIntLiteral(strconv.Itoa(nz.selectLimit))}
580580
}
581581
}

0 commit comments

Comments
 (0)