Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix - from(nil) did not generate the expected SQL #23

Merged
merged 3 commits into from
Sep 4, 2023
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
2 changes: 1 addition & 1 deletion lib/atomically/query_service.rb
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ def update_all_and_get_ids(*args)
@klass.transaction do
@relation.connection.execute('SET @ids := NULL')
@relation.where("(SELECT @ids := CONCAT_WS(',', #{id_column}, @ids))").update_all(*args) # 撈出有真的被更新的 id,用逗號串在一起
ids = @klass.from(nil).pluck(Arel.sql('@ids')).first
ids = @klass.from(Arel.sql('DUAL')).pluck(Arel.sql('@ids')).first
end
return ids.try{|s| s.split(',').map(&:to_i).uniq.sort } || [] # 將 id 從字串取出來 @id 的格式範例: '1,4,12'
end
Expand Down
18 changes: 18 additions & 0 deletions test/test_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -51,3 +51,21 @@ def assert_queries(expected_count, event_key = 'sql.active_record')
ensure
ActiveSupport::Notifications.unsubscribe(subscriber)
end

def assert_sqls(expected_sqls, event_key = 'sql.active_record')
sqls = []
subscriber = ActiveSupport::Notifications.subscribe(event_key) do |_, _, _, _, payload|
next if payload[:sql].start_with?('PRAGMA table_info')
next if payload[:sql] =~ /\A(?:BEGIN TRANSACTION|COMMIT TRANSACTION|BEGIN|COMMIT)\z/i

sqls << payload[:sql]
end
yield

missing_sqls = expected_sqls - sqls
if missing_sqls.any?
assert_equal "expect #{expected_sqls} queried, but query following sqls:\n#{sqls.join("\n").tr('"', "'")}\n", "\nmissing sqls:\n#{missing_sqls.join("\n").tr('"', "'")}\n"
end
ensure
ActiveSupport::Notifications.unsubscribe(subscriber)
end
11 changes: 11 additions & 0 deletions test/update_all_and_get_ids_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -65,4 +65,15 @@ def test_on_relation_and_with_race_condition
assert_equal ['bomb', '', 'flame thrower'], Item.order('id').pluck(:name)
end
end

def test_select_from_dual
skip if not Atomically::AdapterCheckService.new(UserItem).mysql?

in_sandbox do
assert_sqls(['SELECT @ids FROM DUAL']) do
assert_equal [1, 2], Item.joins(:users).atomically.update_all_and_get_ids('items.name = ""')
assert_equal ['', '', 'flame thrower'], Item.order('id').pluck(:name)
end
end
end
end
Loading