Skip to content
Merged
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
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
## v5.1.6

#### Added

* Use lock hint when joining table in query.


## v5.1.5

#### Fixed
Expand Down
16 changes: 14 additions & 2 deletions lib/arel/visitors/sqlserver.rb
Original file line number Diff line number Diff line change
Expand Up @@ -95,17 +95,29 @@ def visit_Arel_Nodes_JoinSource o, collector
collector = visit_Arel_Nodes_SelectStatement_SQLServer_Lock collector
end
if o.right.any?
collector << " " if o.left
collector << SPACE if o.left
collector = inject_join o.right, collector, ' '
end
collector
end

def visit_Arel_Nodes_InnerJoin o, collector
collector << "INNER JOIN "
collector = visit o.left, collector
collector = visit_Arel_Nodes_SelectStatement_SQLServer_Lock collector, space: true
if o.right
collector << SPACE
visit(o.right, collector)
else
collector
end
end

def visit_Arel_Nodes_OuterJoin o, collector
collector << "LEFT OUTER JOIN "
collector = visit o.left, collector
collector = visit_Arel_Nodes_SelectStatement_SQLServer_Lock collector, space: true
collector << " "
collector << SPACE
visit o.right, collector
end

Expand Down
28 changes: 28 additions & 0 deletions test/cases/pessimistic_locking_test_sqlserver.rb
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,34 @@ class PessimisticLockingTestSQLServer < ActiveRecord::TestCase
end
end

describe 'joining tables' do

it 'joined tables use updlock by default' do
assert_sql %r|SELECT \[people\]\.\* FROM \[people\] WITH\(UPDLOCK\) INNER JOIN \[readers\] WITH\(UPDLOCK\)\s+ON \[readers\]\.\[person_id\] = \[people\]\.\[id\]| do
Person.lock(true).joins(:readers).load
end
end

it 'joined tables can use custom lock directive' do
assert_sql %r|SELECT \[people\]\.\* FROM \[people\] WITH\(NOLOCK\) INNER JOIN \[readers\] WITH\(NOLOCK\)\s+ON \[readers\]\.\[person_id\] = \[people\]\.\[id\]| do
Person.lock('WITH(NOLOCK)').joins(:readers).load
end
end

it 'left joined tables use updlock by default' do
assert_sql %r|SELECT \[people\]\.\* FROM \[people\] WITH\(UPDLOCK\) LEFT OUTER JOIN \[readers\] WITH\(UPDLOCK\)\s+ON \[readers\]\.\[person_id\] = \[people\]\.\[id\]| do
Person.lock(true).left_joins(:readers).load
end
end

it 'left joined tables can use custom lock directive' do
assert_sql %r|SELECT \[people\]\.\* FROM \[people\] WITH\(NOLOCK\) LEFT OUTER JOIN \[readers\] WITH\(NOLOCK\)\s+ON \[readers\]\.\[person_id\] = \[people\]\.\[id\]| do
Person.lock('WITH(NOLOCK)').left_joins(:readers).load
end
end

end

end

describe 'For paginated finds' do
Expand Down