From d566c862b8cd7d95c132c1cc438e3f27dda31b70 Mon Sep 17 00:00:00 2001 From: Mike L Date: Tue, 16 Jul 2024 10:25:12 +0200 Subject: [PATCH 1/3] fix: allow Limit() without Order() with MSSQL --- query_select.go | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/query_select.go b/query_select.go index 932cd48be..288a02f23 100644 --- a/query_select.go +++ b/query_select.go @@ -538,6 +538,11 @@ func (q *SelectQuery) appendQuery( if count && !cteCount { b = append(b, "count(*)"...) } else { + // Allows Limit() without Order() with MSSQL as per https://stackoverflow.com/a/36156953 + if q.limit > 0 && fmter.Dialect().Features().Has(feature.OffsetFetch) && len(q.order) == 0 { + b = append(b, "0 AS _temp_sort, "...) + q.order = []schema.QueryWithArgs{schema.UnsafeIdent("_temp_sort")} + } b, err = q.appendColumns(fmter, b) if err != nil { return nil, err From ed7e56793efc75603d1fefd14ad10e282342dc68 Mon Sep 17 00:00:00 2001 From: Vladimir Mihailenco Date: Sat, 26 Oct 2024 09:40:22 +0300 Subject: [PATCH 2/3] code review --- query_select.go | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/query_select.go b/query_select.go index 288a02f23..a0c94866c 100644 --- a/query_select.go +++ b/query_select.go @@ -538,11 +538,12 @@ func (q *SelectQuery) appendQuery( if count && !cteCount { b = append(b, "count(*)"...) } else { - // Allows Limit() without Order() with MSSQL as per https://stackoverflow.com/a/36156953 - if q.limit > 0 && fmter.Dialect().Features().Has(feature.OffsetFetch) && len(q.order) == 0 { + // MSSQL: allows Limit() without Order() as per https://stackoverflow.com/a/36156953 + if q.limit > 0 && len(q.order) == 0 && fmter.Dialect().Name() == dialect.MSSQL { b = append(b, "0 AS _temp_sort, "...) q.order = []schema.QueryWithArgs{schema.UnsafeIdent("_temp_sort")} } + b, err = q.appendColumns(fmter, b) if err != nil { return nil, err @@ -798,6 +799,12 @@ func (q *SelectQuery) appendOrder(fmter schema.Formatter, b []byte) (_ []byte, e return b, nil } + + // MSSQL: allows Limit() without Order() as per https://stackoverflow.com/a/36156953 + if q.limit > 0 && fmter.Dialect().Name() == dialect.MSSQL { + return append(b, " ORDER BY _temp_sort"...), nil + } + return b, nil } From bc5128b9b6f3ba6c8409833d40e878ff3e6c5144 Mon Sep 17 00:00:00 2001 From: Vladimir Mihailenco Date: Sat, 26 Oct 2024 09:41:17 +0300 Subject: [PATCH 3/3] fix dup order --- query_select.go | 1 - 1 file changed, 1 deletion(-) diff --git a/query_select.go b/query_select.go index a0c94866c..80a9e949e 100644 --- a/query_select.go +++ b/query_select.go @@ -541,7 +541,6 @@ func (q *SelectQuery) appendQuery( // MSSQL: allows Limit() without Order() as per https://stackoverflow.com/a/36156953 if q.limit > 0 && len(q.order) == 0 && fmter.Dialect().Name() == dialect.MSSQL { b = append(b, "0 AS _temp_sort, "...) - q.order = []schema.QueryWithArgs{schema.UnsafeIdent("_temp_sort")} } b, err = q.appendColumns(fmter, b)