Repository navigation
Introduce Parameter Object: QueryIntent - #55897
Conversation
byroot
left a comment
There was a problem hiding this comment.
I had something like that in mind for a while, but I really think it should just be a "query object".
| def inspect | ||
| "#<#{self.class.name} name=#{name.inspect} allow_retry=#{allow_retry} materialize_transactions=#{materialize_transactions}>" | ||
| end |
There was a problem hiding this comment.
We have #instance_variables_to_inspect now: ruby/ruby#13555
|
|
||
| module ActiveRecord | ||
| module ConnectionAdapters | ||
| class QueryIntent # :nodoc: |
There was a problem hiding this comment.
I wanted a name that 1) sounded like an internal implementation detail, 2) conveyed a sense that it's a particular execution of a query and not a more long-term storable thing, 3) can be used as a parameter/variable name without introducing ambiguity about whether it contains an instance of this class vs a string vs an Arel object.
(I also anticipate this overall concept eventually needing more than one class -- e.g. a deeply-frozen encapsulation of just the things that actually need to be passed into the DB driver -- so it feels cleaner to decorate everything with slight nonsense-words to keep them mentally separated.)
There was a problem hiding this comment.
sounded like an internal implementation detail
I suspected as much, but I don't think we should make our code less expressive to scare users away from private APIs.
conveyed a sense that it's a particular execution of a query and not a more long-term storable thing
I don't think Query implies that but alright.
can be used as a parameter/variable name without introducing ambiguity about whether it contains an instance of this class vs a string vs an Arel object.
If anything, I'm more weirded out by all these intent variable, more than by the class name.
If you really don't want Query, what about QueryInfo?
There was a problem hiding this comment.
fwiw I think of a QueryIntent (or any Intent suffixed object) as implying a writeable-until-maybe-execution and read-only-post-execution lifecycle. Not sure if others interpret this semantic the same way, and I haven't read the changes to evaluate if I agree with the name, just offering a data point.
There was a problem hiding this comment.
sounded like an internal implementation detail
I'm actually wondering if this should be public API.
I was talking with @beauraF earlier today, and they're doing some pretty heavy SQL parsing to figure out what they can redirect to read replicas or not. I think having access to the Arel AST could potentially save them a lot of effort.
Similarly, having the info of whether the query is known to be a read or a write, can be very useful, etc.
The more I think about it, the more it make sense to expose a proper query object rather than just a SQL string and a few things on the side.
NB: I understand designing a public API may require more thoughts and effort than a purely internal refactor. I'm mostly just thinking out loud.
There was a problem hiding this comment.
Indeed, we rely on this concept of Database::CurrentQuery in our codebase, which is set using pg_query:
class Database::CurrentQuery < ActiveSupport::CurrentAttributes
attribute :normalized_sql
attribute :raw_sql
attribute :query_id
attribute :parsed_query
attribute :type
attribute :locking
attribute :before_table_write
attribute :past_parsed_queries
attribute :past_written_tables
attribute :auto_offloadable
attribute :sql_length
attribute :where_in_metadata
# ...
endWe primarily use it to automatically route read queries to replicas, through logic like this:
def auto_offloadable?(sql, name)
Database::CurrentQuery.set(sql)
# ...
# Don't offload if we are not reading the database
return false if Database::CurrentQuery.type != :read
# Don't offload if we have previously written to one of these tables
return false unless Database::CurrentQuery.before_table_write
# ...
true
endWe patch both the PostgreSQLAdapter and the ConnectionPool to make this behavior transparent.
We also use it for observability and resiliency use cases (eg: discussions around circuit breaker based on query_id).
As @byroot mentioned, exposing a public API for query introspection would be a strong enabler for us. It would likely allow us to simplify our internal implementation and potentially open the door to upstreaming some of this logic to improve the current automatic role switching mechanism 😄
| # Handle SQL preprocessing if needed | ||
| intent.processed_sql ||= preprocess_query(intent.raw_sql) if intent.raw_sql | ||
| intent.type_casted_binds = type_casted_binds(intent.binds) |
There was a problem hiding this comment.
This feels like it should be part of the constructor, or at least of compile_arel_in_intent?
I see there are other codepath only calling one of the two, or none of them but I don't understand why.
There was a problem hiding this comment.
Yeah, I wanted to retain the current behaviour everywhere for now (at the cost of more complicated handling of arguably the most important contents in the object), to put off which call sites' local semantics it's safe to change.
I think insert -> exec_insert -> sql_for_insert is the call path that most clearly [currently] leans on all these steps being separately addressable.
| def initialize(arel: nil, raw_sql: nil, processed_sql: nil, name: "SQL", binds: [], prepare: false, async: false, | ||
| allow_retry: false, materialize_transactions: true, batch: false) |
There was a problem hiding this comment.
Another thing I'd like to store in there is whether we know if it's a read or write query (or unknown).
e.g. you used #select_all, we know it's a read query and skip trying to match it against the shitty regexps.
7bfa689 to
19f1c40
Compare
|
@byroot I'm thinking of moving forward with the current name for now, with an intention (heh) of revisiting the question later, when we can see what [if anything] further I've ended up moving onto it, etc. To that end, I think we're best served by a name that stands out for easy search & [interactive] replace, vs something like "query" which would be hard to track down. |
|
@matthewd yes no worries, my concern isn't a blocking one, your refactor seem positive to me regardless. |
byroot
left a comment
There was a problem hiding this comment.
It's big so I haven't reviewed everything in close detail, but seems like a positive refactor to me, we can always refine later.
| autoload :Column | ||
| autoload :PoolConfig | ||
| autoload :PoolManager | ||
| autoload :QueryIntent |
There was a problem hiding this comment.
I think this should be in eager_autoload.
There was a problem hiding this comment.
Probably true, but IMO better considered together with a bunch of these peers -- I think AbstractAdapter has specific reasons it's currently eager loaded even though nothing else is, and I wouldn't want to imply this is a similar outlier.
| rescue ActiveRecord::StatementInvalid => ex | ||
| raise ex.set_query(sql, binds) | ||
| if intent | ||
| raise ex.set_query(intent.processed_sql, intent.binds) | ||
| else | ||
| raise ex.set_query(sql, binds) | ||
| end |
There was a problem hiding this comment.
Nitpick: I'd move that rescue in each branch of the if, so we have a single conditional instead of two.
There was a problem hiding this comment.
I would if the conditional wasn't on a local, but between the extra nesting of the begin and the possibility of two rescue blocks drifting.. 🤷🏻♂️
| def compile_arel_in_intent(intent) # :nodoc: | ||
| return unless intent.needs_arel_compilation? | ||
|
|
||
| sql, binds, preparable, allow_retry = to_sql_and_binds(intent.arel, intent.binds, intent.prepare, intent.allow_retry) | ||
| intent.set_compiled_result(raw_sql: sql, binds: binds, prepare: preparable, allow_retry: allow_retry) | ||
| end | ||
| private :compile_arel_in_intent |
There was a problem hiding this comment.
I believe this logic should move inside QueryAttempt, e.g. intent.compile(self). It would be better encapsulation.
There was a problem hiding this comment.
For now I prefer to keep the adapter being obsessed with intent's internals rather than teaching the intent about to_sql_and_binds. I think it would be interesting to consider moving all of to_sql_and_binds into QueryIntent, but am also conscious that would mean constructing an intent just to do to_sql, so I'm holding off on that at this stage.
This is an adapter-internal object that represents a caller's desire that a given query be run, encapsulating the SQL, binds, and various control parameters like allow_retry. Immutable here, but mutable attributes to follow.
Carry the type-casted binds and notification payload once they're available; update #async to reflect whether the query was actually run asynchronously.
It was documented despite being private, so we continue accepting the old separated parameter set with a deprecation warning. The method is no longer documented: since the consolidation onto perform_query, individual adapters should not need to know about it.
This moves intent-unpacking to the same boundary where we start talking to the raw connection.
The work stays in the adapter, but we now construct the intent with the original SQL, to be stored separately from the final preprocessed form.
Following the SQL preprocessing, further allow QueryIntent to be constructed with an Arel-shaped query.
These are purely less-powerful versions of their non-prefixed public API equivalents, and the adapter has far too many query-running methods to justify keeping obscure variants for compatibility. For update and delete, these are now entirely vestigial. For insert, some adapters need to be able to intervene, so I've moved the real work to _exec_insert.
19f1c40 to
3fc2ca0
Compare
| # Handle Arel compilation if needed | ||
| compile_arel_in_intent(intent) |
There was a problem hiding this comment.
I may be wrong, but is this an unintended API change? I think that #raw_execute did not previously accept Arel, but only raw sql? And it looks like you changed all the internal code to compile Arel into sql before calling #raw_execute.
There was a problem hiding this comment.
Intentional simplification.
Most public API already accepts at least Arel, and my plan is to drive towards full consistency. I haven't widened any documentation yet, because things are still in flux (and "surprise: it works" is a valid version of the undefined behaviour that's possible when supplying a parameter that's not documented as supported).
Also note at this stage this only applies where the QueryIntent is constructed with arel:, so does not affect e.g. exec_update which [via internal_execute] skips straight to raw_sql:. I'm semi-anticipating this changing (hence the above thinking/reasoning), but I'm actually not sure this PR alone does cause additional public APIs to accept Arel.
In particular, these two pull requests: - rails/rails#55897 - rails/rails#55900
Rails 8.2 changed the log method to accept a QueryIntent object as the first argument (rails/rails#55897). Update the dbms_output override to use the new signature and delegate to super, keeping only the log_dbms_output call in the ensure block. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Rails 8.2 changed execute to go through execute_intent -> perform_query instead of raw_execute (rails/rails#55897, rails/rails@b22a86d061c). Implement perform_query(raw_connection, intent) with the Oracle-specific query execution logic. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Rails 8.2 changed the log method to accept a QueryIntent object as the first argument (rails/rails#55897). Update the dbms_output override to use the new signature and delegate to super, keeping only the log_dbms_output call in the ensure block. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Rails 8.2 changed execute to go through execute_intent -> perform_query instead of raw_execute (rails/rails#55897, rails/rails@b22a86d061c). Implement perform_query(raw_connection, intent) with the Oracle-specific query execution logic. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Rails 8.2 changed the log method to accept a QueryIntent object as the first argument (rails/rails#55897). Update the dbms_output override to use the new signature and delegate to super, keeping only the log_dbms_output call in the ensure block. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Rails 8.2 deprecated exec_insert, exec_update, and exec_delete (rails/rails#55897). The new pattern is: - exec_insert wraps into a QueryIntent and delegates to _exec_insert - exec_update/exec_delete use intent.execute! -> perform_query Override _exec_insert(intent, ...) instead of exec_insert to handle Oracle-specific RETURNING INTO clause with cursor.bind_returning_param. Use log(intent) instead of log(sql, ...) to avoid the deprecated SQL string path. Remove exec_update override and exec_delete alias — the base class versions now go through perform_query which handles DML correctly. Remove raw_execute — replaced by perform_query in Rails 8.2. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Rails 8.2 refactored query execution to go through execute_intent -> perform_query instead of raw_execute, and deprecated exec_insert/exec_update/exec_delete in favor of QueryIntent-based methods (rails/rails#55897, rails/rails@b22a86d061c). - Add perform_query(raw_connection, intent) with Oracle-specific query execution logic using QueryIntent#processed_sql - Replace exec_insert with _exec_insert(intent, ...) to handle Oracle-specific RETURNING INTO clause with cursor.bind_returning_param - Remove raw_execute (replaced by perform_query) - Remove exec_update override and exec_delete alias (base class versions now go through perform_query) Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Rails 8.2 changed the log method to accept a QueryIntent object as the first argument (rails/rails#55897). Update the dbms_output override to use the new signature and delegate to super, keeping only the log_dbms_output call in the ensure block. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Rails 8.2 refactored query execution to go through execute_intent -> perform_query instead of raw_execute, and deprecated exec_insert/exec_update/exec_delete in favor of QueryIntent-based methods (rails/rails#55897, rails/rails@b22a86d061c). - Add perform_query(raw_connection, intent) with Oracle-specific query execution logic using QueryIntent#processed_sql - Replace exec_insert with _exec_insert(intent, ...) to handle Oracle-specific RETURNING INTO clause with cursor.bind_returning_param - Remove raw_execute (replaced by perform_query) - Remove exec_update override and exec_delete alias (base class versions now go through perform_query) Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Rails 8.2 changed the log method to accept a QueryIntent object as the first argument (rails/rails#55897). Update the dbms_output override to use the new signature and delegate to super, keeping only the log_dbms_output call in the ensure block. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Rails 8.2 changed the log method to accept a QueryIntent object as the first argument (rails/rails#55897). Update the dbms_output override to use the new signature and delegate to super, keeping only the log_dbms_output call in the ensure block. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Rails 8.2 refactored query execution to go through execute_intent -> perform_query instead of raw_execute, and deprecated exec_insert/exec_update/exec_delete in favor of QueryIntent-based methods (rails/rails#55897, rails/rails@b22a86d061c). - Add perform_query(raw_connection, intent) with Oracle-specific query execution logic using QueryIntent#processed_sql - Replace exec_insert with _exec_insert(intent, ...) to handle Oracle-specific RETURNING INTO clause with cursor.bind_returning_param - Remove raw_execute (replaced by perform_query) - Remove exec_update override and exec_delete alias (base class versions now go through perform_query) Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Rails 8.2 changed the log method to accept a QueryIntent object as the first argument (rails/rails#55897). Update the dbms_output override to use the new signature and delegate to super, keeping only the log_dbms_output call in the ensure block. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Rails 8.2 refactored query execution to go through execute_intent -> perform_query instead of raw_execute, and deprecated exec_insert/exec_update/exec_delete in favor of QueryIntent-based methods (rails/rails#55897, rails/rails@b22a86d061c). - Add perform_query(raw_connection, intent) with Oracle-specific query execution logic using QueryIntent#processed_sql - Replace exec_insert with _exec_insert(intent, ...) to handle Oracle-specific RETURNING INTO clause with cursor.bind_returning_param - Update DbmsOutput#log to accept QueryIntent as first argument - Remove raw_execute (replaced by perform_query) - Remove exec_update override and exec_delete alias (base class versions now go through perform_query) Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Rails 8.2 refactored query execution to go through execute_intent -> perform_query instead of raw_execute, and deprecated exec_insert/exec_update/exec_delete in favor of QueryIntent-based methods (rails/rails#55897, rails/rails@b22a86d061c). - Add perform_query(raw_connection, intent) with Oracle-specific query execution logic using QueryIntent#processed_sql - Replace exec_insert with _exec_insert(intent, ...) to handle Oracle-specific RETURNING INTO clause with cursor.bind_returning_param - Update DbmsOutput#log to accept QueryIntent as first argument - Remove raw_execute (replaced by perform_query) - Remove exec_update override and exec_delete alias (base class versions now go through perform_query) Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Rails 8.2 refactored query execution to go through execute_intent -> perform_query instead of raw_execute, and deprecated exec_insert/exec_update/exec_delete in favor of QueryIntent-based methods (rails/rails#55897, rails/rails@b22a86d061c). - Add perform_query(raw_connection, intent) with Oracle-specific query execution logic using QueryIntent#processed_sql - Replace exec_insert with _exec_insert(intent, ...) to handle Oracle-specific RETURNING INTO clause with cursor.bind_returning_param - Update DbmsOutput#log to accept QueryIntent as first argument - Remove raw_execute (replaced by perform_query) - Remove exec_update override and exec_delete alias (base class versions now go through perform_query) Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
exec_update is deprecated in Rails 8.2 and will be removed in Rails 8.3 (rails/rails#55897). Use exec_query instead which accepts binds and goes through the QueryIntent pipeline. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Rails 8.2 deprecated passing SQL strings to `log` in favor of QueryIntent objects (rails/rails#55897). Update log_custom_method in procedures.rb to wrap the SQL string in a QueryIntent before calling log. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Rails 8.2 refactored query execution to go through execute_intent -> perform_query instead of raw_execute, and deprecated exec_insert/exec_update/exec_delete in favor of QueryIntent-based methods (rails/rails#55897, rails/rails@b22a86d061c). - Add perform_query(raw_connection, intent) with Oracle-specific query execution logic using QueryIntent#processed_sql - Replace exec_insert with _exec_insert(intent, ...) to handle Oracle-specific RETURNING INTO clause with cursor.bind_returning_param - Update DbmsOutput#log to accept QueryIntent as first argument - Update log_custom_method in procedures.rb to wrap SQL in QueryIntent - Remove raw_execute (replaced by perform_query) - Remove exec_update override and exec_delete alias (base class versions now go through perform_query) - Replace deprecated exec_update with exec_query in specs Co-Authored-By: Claude Sonnet 4.6 <[email protected]>


This has been on my todo list for a while, as we've continued to gradually accumulate extra context that we end up needing to pass along with queries.
This is a draft -- for exploration, I've changed a number of low-level-but-public APIs. Even if we agree that's a reasonable end-goal, they would require deprecations along the way.Affected Public APIs:
exec_updateandexec_deleteare deprecated, pointing callers toupdateanddeleteinstead. Those methods (the only internal callers) now justaffected_rows(raw_execute(intent))directly.exec_insertis likewise deprecated in favour ofinsert. We [currently?] still need to keep it for overriding, so the internal intent-using one is now_exec_insert. That's ugly, but I'm hopeful we can later evolve it away, and failing that we'll be able to reclaimexec_insertpost-deprecation.logis now called exclusively with anintent, but still acceptssql, name, bindscalls too (with deprecation). In practice I don't anticipate many people calling it with existing parameters, but it is technically documented (as a:doc:private method). I anticipate most external users oflogare overriding/wrapping it, so will be broken by the signature change on our existing calls -- but I think that's unavoidable.