Skip to content

Commit 9f51851

Browse files
authored
FROM subquery should work if order provided (#1151)
1 parent c5710d9 commit 9f51851

File tree

3 files changed

+29
-5
lines changed

3 files changed

+29
-5
lines changed

CHANGELOG.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,9 @@
1+
## Unreleased
2+
3+
#### Fixed
4+
5+
- [#1151](https://github.com/rails-sqlserver/activerecord-sqlserver-adapter/pull/1151) FROM subquery should work if order provided
6+
17
## v7.1.1
28

39
#### Fixed

lib/arel/visitors/sqlserver.rb

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -213,7 +213,7 @@ def visit_Arel_Nodes_SelectStatement_SQLServer_Lock(collector, options = {})
213213

214214
def visit_Orders_And_Let_Fetch_Happen(o, collector)
215215
make_Fetch_Possible_And_Deterministic o
216-
unless o.orders.empty?
216+
if o.orders.any?
217217
collector << " ORDER BY "
218218
len = o.orders.length - 1
219219
o.orders.each_with_index { |x, i|
@@ -261,15 +261,14 @@ def select_statement_lock?
261261

262262
def make_Fetch_Possible_And_Deterministic(o)
263263
return if o.limit.nil? && o.offset.nil?
264+
return if o.orders.any?
264265

265266
t = table_From_Statement o
266267
pk = primary_Key_From_Table t
267268
return unless pk
268269

269-
if o.orders.empty?
270-
# Prefer deterministic vs a simple `(SELECT NULL)` expr.
271-
o.orders = [pk.asc]
272-
end
270+
# Prefer deterministic vs a simple `(SELECT NULL)` expr.
271+
o.orders = [pk.asc]
273272
end
274273

275274
def distinct_One_As_One_Is_So_Not_Fetch(o)

test/cases/fetch_test_sqlserver.rb

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,25 @@ class FetchTestSqlserver < ActiveRecord::TestCase
4242
end
4343
end
4444

45+
describe "FROM subquery" do
46+
let(:from_sql) { "(SELECT [books].* FROM [books]) [books]" }
47+
48+
it "SQL generated correctly for FROM subquery if order provided" do
49+
query = Book.from(from_sql).order(:id).limit(5)
50+
51+
assert_equal query.to_sql, "SELECT [books].* FROM (SELECT [books].* FROM [books]) [books] ORDER BY [books].[id] ASC OFFSET 0 ROWS FETCH NEXT 5 ROWS ONLY"
52+
assert_equal query.to_a.count, 5
53+
end
54+
55+
it "exception thrown if FROM subquery is provided without an order" do
56+
query = Book.from(from_sql).limit(5)
57+
58+
assert_raise(ActiveRecord::StatementInvalid) do
59+
query.to_sql
60+
end
61+
end
62+
end
63+
4564
protected
4665

4766
def create_10_books

0 commit comments

Comments
 (0)