zendesk / active_record_shards

Support for sharded databases and replicas for ActiveRecord

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to create a connection model?

bluengreen opened this issue · comments

I'm trying to create a connection to another database server using an abstract connection model like so:

class MyConnection < ActiveRecord::Base
  self.establish_connection( configurations['my_connection'][Rails.env] )
  self.abstract_class = true
end

This doesn't seem to work. The models that use this connection model are not connected to the other database, they are still using the main default db. I want to use this gem for the slaves and possibly the sharding but need to be able to establish a connection to another db. How do I do that using this gem? How do I connect to another database as I normally would do?

Thanks in advance

Additionally if I have to, how do I at least force a model to always use a shard? on_shard(1) only works for the block syntax. How do I do that within a model? I want every request to go to the db defined for that shard/connection.

I'm trying to create a connection to another database server using an abstract connection model

@bluengreen, does it work ok if you do establish_connection on the concrete model? May need a patch to honor the superclasses settings.

Additionally if I have to, how do I at least force a model to always use a shard?

I'm not totally sure what you're asking. Sounds like your databases are vertically partitioned maybe? ARS wasn't exactly designed for vertically partitioned DBs, much more designed around N shards with the same schema. I don't think it's out of the realm of possibility but might need a patch.

@osheroff - no it doesn't work in the connection class or the concrete model. I tried to dig into the code more to find a work around, but didn't really see how the super class was being called.

I can get it to work, sometimes, if I call establish_connection on the model directly.

MyModel.establish_connection(Rails.configuration.database_configuration["other_database"]) 
MyModel.first

However that is random, and times out. Another issue I found, is even when that does work, unless self.primary_key is set then .find and .last will not work.

As for forcing a model to use a shard, I was thinking a work around could be to assign a model to a slave/shard and then forcing the model to always use that slave/shard.

class MyModel < ActiveRecord::Base 
    on_slave 
end 

Thanks for your help. Really would like to use this gem over others that are getting old, and not compatible with Rails 5. However, we have about 10 models that need to connect to other databases for lookup data and are not in the main schema. So its a necessity to be able to connect to other databases as we would normally under active record.