Skip to content

Fix ArrayHandlerPatch to support multi-database configurations#128

Open
biancapower wants to merge 1 commit intoGeorgeKaraszi:mainfrom
biancapower:fix/multi-database-array-handler
Open

Fix ArrayHandlerPatch to support multi-database configurations#128
biancapower wants to merge 1 commit intoGeorgeKaraszi:mainfrom
biancapower:fix/multi-database-array-handler

Conversation

@biancapower
Copy link
Copy Markdown

Problem

ArrayHandlerPatch#call hardcodes ActiveRecord::Base.connection to check the schema cache for PostgreSQL array columns. In Rails 6.1+ multi-database setups where connects_to is declared on abstract subclasses (not ActiveRecord::Base itself), ActiveRecord::Base has no connection pool registered. This raises ActiveRecord::ConnectionNotDefined on any .where() with array values.

Minimal reproduction:

class ApplicationRecord < ActiveRecord::Base
  primary_abstract_class
  connects_to database: { writing: :primary, reading: :primary_replica }
end

# Any model with an array column:
Role.where(name: ["admin", "doctor"])
# => ActiveRecord::ConnectionNotDefined: No database connection defined.

Fix

Resolve the connection through the model that owns the Arel table, via attribute.relation. Arel::Table stores the owning model as @klass (set via the klass: keyword argument in its constructor). There is no public accessor,
so we use instance_variable_get(:@klass) with a fallback to ActiveRecord::Base for cases where klass is nil (e.g. hand-built Arel tables).

This is the minimal change — the rest of the method is untouched.

Notes

  • Verified on Rails 8.0.3 with PostgreSQL and a multi-database config (separate primary + queue databases)
  • The fallback to ActiveRecord::Base preserves existing behavior for single-database setups
  • @klass has been present on Arel::Table since Rails 5.2 and is used internally by Rails for attribute alias resolution

Resolve connection through the Arel table's owning model class instead
of hardcoding ActiveRecord::Base.connection, which raises
ConnectionNotDefined in multi-database setups where pools are registered
on abstract subclasses.
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

Successfully merging this pull request may close these issues.

1 participant