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

Choosing Primary instead of Replica when using 'with' (because of newlines) #376

Open
jackcb123 opened this issue Aug 17, 2023 · 0 comments

Comments

@jackcb123
Copy link

Issue: Many of my complex sql statements were being performed by the primary instead of the replica. It turns out that the sql_replica_matchers regex is insufficient for queries that begin with CTE 'with' statements.

In lib/active_record/connection_adapters/makara_abstract_adapter.rb

SQL_REPLICA_MATCHERS = [/\A\s*(select|with.+\)\s*select)\s/i].map(&:freeze).freeze

should be changed to

SQL_REPLICA_MATCHERS = [/\A\s*(select|with[\s\S]*\)\s*select)\s/i].map(&:freeze).freeze

[\s\S] is the difference and accounts for new lines.

This is because '.' regex doesn't account for new lines (which will obviously be there in complex sql statements).

My workaround is this. Hope this helps! :)

class ActiveRecord::ConnectionAdapters::MakaraAbstractAdapter < ::Makara::Proxy
  CUSTOM_SQL_REPLICA_MATCHERS = [/\A\s*(select|with[\s\S]*\)\s*select)\s/i].map(&:freeze).freeze

  def sql_slave_matchers
    CUSTOM_SQL_REPLICA_MATCHERS
  end

  def sql_replica_matchers
    CUSTOM_SQL_REPLICA_MATCHERS
  end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant