Skip to content

Commit

Permalink
Create a more efficient regex
Browse files Browse the repository at this point in the history
require 'benchmark'

# Original regular expressions
original = Regexp.union(
  %r{\A(?:/\*.*?\*/)?\s*ROLLBACK}i,
  %r{\A(?:/\*.*?\*/)?\s*COMMIT}i,
  %r{\A(?:/\*.*?\*/)?\s*RELEASE\s+SAVEPOINT}i,
)

# Combined regular expression
combined = %r{\A(?:/\*.*?\*/)?\s*(ROLLBACK|COMMIT|RELEASE\s+SAVEPOINT)}i

# Test string
sql = "/* comment */ COMMIT"

n = 1_000_000
Benchmark.bm do |x|
  x.report("original:") { n.times { original.match?(sql) } }
  x.report("combined:") { n.times { combined.match?(sql) } }
end
  • Loading branch information
shanempope authored Oct 26, 2023
1 parent 7f19857 commit 37c01ec
Showing 1 changed file with 1 addition and 5 deletions.
6 changes: 1 addition & 5 deletions lib/semian/activerecord_trilogy_adapter.rb
Original file line number Diff line number Diff line change
Expand Up @@ -91,11 +91,7 @@ def resource_exceptions
end

# TODO: share this with Mysql2
QUERY_ALLOWLIST = Regexp.union(
%r{\A(?:/\*.*?\*/)?\s*ROLLBACK}i,
%r{\A(?:/\*.*?\*/)?\s*COMMIT}i,
%r{\A(?:/\*.*?\*/)?\s*RELEASE\s+SAVEPOINT}i,
)
QUERY_ALLOWLIST = %r{\A(?:/\*.*?\*/)?\s*(ROLLBACK|COMMIT|RELEASE\s+SAVEPOINT)}i

def query_allowlisted?(sql, *)
QUERY_ALLOWLIST.match?(sql)
Expand Down

0 comments on commit 37c01ec

Please sign in to comment.