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

Support read queries with leading characters while preventing writes #35402

Merged
merged 1 commit into from
Feb 25, 2019

Conversation

alimi
Copy link
Contributor

@alimi alimi commented Feb 25, 2019

Summary

#34505 introduced the ability to block writes even if the database allows it. It added a READ_QUERY regex to help determine if a query was a read or a write. The regex is built using ActiveRecord::ConnectionAdapters::AbstractAdapter.build_read_query_regexp and it doesn't account for reads with leading parenthesis and/or spaces.

def self.build_read_query_regexp(*parts) # :nodoc:
parts = parts.map { |part| /\A\s*#{part}/i }
Regexp.union(*parts)

This would cause read queries like unions ((SELECT ...) UNION (SELECT ...)) to be treated as writes.

In this PR, I update the regex allow for leading parenthesis and/or spaces.

  * The READ_QUERY regex would consider reads to be writes if they started with
    spaces or parens. For example, a UNION query might have parens around each
    SELECT - (SELECT ...) UNION (SELECT ...).
  * It will now correctly treat these queries as reads.
@conn.execute("INSERT INTO ex (data) VALUES ('138853948594')")

@conn.while_preventing_writes do
assert_equal 1, @conn.execute(" SELECT data from ex WHERE data = '138853948594'").count
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I didn't add leading parenthesis to the sqlite3 test because sqlite3 didn't consider it valid syntax.

@tenderlove tenderlove merged commit ec30b84 into rails:master Feb 25, 2019
@alimi alimi deleted the update-ar-read-regex branch February 25, 2019 19:58
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants