Skip to content

Commit 8abb18a

Browse files
committed
Distinct One As One Is So Not Fetch. Fixes #374.
1 parent 5a249a2 commit 8abb18a

File tree

1 file changed

+13
-0
lines changed

1 file changed

+13
-0
lines changed

lib/arel/visitors/sqlserver.rb

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@ def visit_Arel_Nodes_Limit o, collector
5858

5959
def visit_Arel_Nodes_SelectStatement o, collector
6060
@select_statement = o
61+
distinct_One_As_One_Is_So_Not_Fetch o
6162
if o.with
6263
collector = visit o.with, collector
6364
collector << SPACE
@@ -126,6 +127,7 @@ def visit_Make_Fetch_Happen o, collector
126127
# SQLServer Helpers
127128

128129
def node_value(node)
130+
return nil unless node
129131
case node.expr
130132
when NilClass then nil
131133
when Numeric then node.expr
@@ -148,6 +150,17 @@ def make_Fetch_Possible_And_Deterministic o
148150
end
149151
end
150152

153+
def distinct_One_As_One_Is_So_Not_Fetch o
154+
core = o.cores.first
155+
distinct = Nodes::Distinct === core.set_quantifier
156+
oneasone = core.projections.all? { |x| x == ActiveRecord::FinderMethods::ONE_AS_ONE }
157+
limitone = node_value(o.limit) == 1
158+
if distinct && oneasone && limitone && !o.offset
159+
core.projections = [Arel.sql("TOP(1) 1 AS [one]")]
160+
o.limit = nil
161+
end
162+
end
163+
151164
def table_From_Statement o
152165
core = o.cores.first
153166
if Arel::Table === core.from

0 commit comments

Comments
 (0)