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
Executing raw SQL with comments can be very slow #45011
Comments
I think removing the extra |
@matthewbauer you're right - it seems to have improved a little bit, but not as much as removing # frozen_string_literal: true
require "bundler/inline"
gemfile(true) do
source "https://rubygems.org"
git_source(:github) { |repo| "https://github.com/#{repo}.git" }
gem "benchmark-ips"
end
prev = %r{(?:--.*\n)*|/\*(?:[^*]|\*[^/])*\*/}m # before https://github.com/rails/rails/pull/45012
current = %r{(?:--.*\n)|/\*(?:[^*]|\*[^/])*\*/}m
no_m = %r{(?:--.*\n)|/\*(?:[^*]|\*[^/])*\*/}
input = "-- select 1\n" * 30
Benchmark.ips do |x|
x.report("prev") { prev.match?(input) }
x.report("current") { current.match?(input) }
x.report("no m") { no_m.match?(input) }
x.compare!
end
Do you want to make a PR? It would be good to see if this breaks any tests, or if there's any extra tests worth adding. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I noticed the problem after upgrading to Rails 6.1 which starts considering comments starting with
--
. We have some ugly tests executing raw SQL fixture files that have some comments in them and those tests started running so slowly they practically hang. The issue is the Regexp here: https://github.com/rails/rails/blob/main/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb#L39 Unfortunately I'm not so good with regular expressions to explain why this is slow but intuitively it's something to do with multiline matching and a lot of*
-s causing an exponential number of backtracks when scanning the string. I tested with the corresponding regex in Java so it's not Ruby's regex implementation to blame. A faster solution should be to strip the comments in advance and then run the rest of the regex on the remaining SQL. The problem should boil down to the following script:Steps to reproduce
Expected behavior
The comments in the raw SQL are ignored and the query runs fast
Actual behavior
The query runs exponentially slow, based on the amount of comments in it
System configuration
Rails version: 7-0-stable
Ruby version: 3.1.0
The text was updated successfully, but these errors were encountered: