Class: PgDog
- Inherits:
-
Object
- Object
- PgDog
- Defined in:
- lib/pgdog.rb
Class Method Summary collapse
-
.check_transaction ⇒ Object
Ensure a transaction isn’t started already.
-
.connection ⇒ Object
Get a connection from ActiveRecord.
-
.shard ⇒ Object
Get currently set shard, if any.
-
.sharding_key ⇒ Object
Get currently set sharding key, if any.
-
.shards ⇒ Object
Get the number of configured shards.
-
.with_shard(shard) ⇒ Object
Start a transaction and set the shard number manually using SET.
-
.with_sharding_key(key) ⇒ Object
Start a transaction and set the sharding key manually using SET.
Class Method Details
.check_transaction ⇒ Object
Ensure a transaction isn’t started already.
63 64 65 66 67 |
# File 'lib/pgdog.rb', line 63 def self.check_transaction if ActiveRecord::Base.connection.open_transactions != 0 raise PgDogError, "Transaction already started, can't set route" end end |
.connection ⇒ Object
Get a connection from ActiveRecord.
3 4 5 |
# File 'lib/pgdog.rb', line 3 def self.connection return ActiveRecord::Base.connection end |
.shard ⇒ Object
Get currently set shard, if any.
45 46 47 48 49 50 51 52 53 54 |
# File 'lib/pgdog.rb', line 45 def self.shard shard = self.connection.execute "SELECT current_setting('pgdog.shard', true)" shard = shard[0]["current_setting"] if shard.nil? return nil else return shard.to_i end end |
.sharding_key ⇒ Object
Get currently set sharding key, if any.
57 58 59 60 |
# File 'lib/pgdog.rb', line 57 def self.sharding_key key = self.connection.execute "SELECT current_setting('pgdog.sharding_key', true)" key[0]["current_setting"] end |
.shards ⇒ Object
Get the number of configured shards
Can only work outside of a transaction, because a started transaction is most likely already routed to a shard and the PgDog query parser won’t be used.
38 39 40 41 42 |
# File 'lib/pgdog.rb', line 38 def self.shards PgDog.check_transaction shards = self.connection.execute "SHOW \"pgdog.shards\"" return shards[0]["shards"].to_i end |
.with_shard(shard) ⇒ Object
Start a transaction and set the shard number manually using SET.
9 10 11 12 13 14 15 16 17 18 |
# File 'lib/pgdog.rb', line 9 def self.with_shard(shard) # Basic SQL injection protection shard = shard.to_i PgDog.check_transaction ActiveRecord::Base.transaction do self.connection.execute "SET \"pgdog.shard\" TO #{shard}" yield end end |
.with_sharding_key(key) ⇒ Object
Start a transaction and set the sharding key manually using SET.
22 23 24 25 26 27 28 29 30 31 |
# File 'lib/pgdog.rb', line 22 def self.with_sharding_key(key) # Basic SQL injection protection. key = key.to_s.sub "'", "''" PgDog.check_transaction ActiveRecord::Base.transaction do self.connection.execute "SET \"pgdog.sharding_key\" TO '#{key}'" yield end end |