Feature proposal: Add a `shard_keys` method to ActiveRecord models

This is mostly a replica of a previous discussion from 2020 but hopefully it’s okay to re-open the topic.

It would be useful to have a shard_keys (could be called shards or shard_names) method that returns an array of shards that model can connect to. This would also allow for methods like on_all_shards (to perform an action on each shard) and sharded? (which would return true if the model is configured to connect to shards, otherwise returns false).

I have a working branch that implements all of the above but, given the previous discussion and general guidance to start a topic first, I’m bringing it up here.

The implementation (on connection_handling) looks like so:

def connects_to(database: {}, shards: {})
  ...
  @shard_keys = shards.keys
  ...
end

def sharded?
  shard_keys.any?
end

def shard_keys
  connection_class_for_self.instance_variable_get(:@shard_keys) || []
end

shard_keys gets the ivar from connection_class_for_self so that all descendants of abstract connection classes know which shards they can connect to. connection_class_for_self also returns self, for connection classes themselves, and thus would return their own @shard_keys ivar.

1 Like

If you have a patch, please do open a PR. It is easier to get feedback with the code in place.

Here you go! Add `.shard_keys`, `.sharded?`, & `.on_all_shards` methods to AR Models by HeyNonster · Pull Request #51009 · rails/rails · GitHub

One actioncable integration (3.3)rake test:integration task failed but it looks unrelated?