Module: PartitionGardener::AdvisoryLock

Defined in:
lib/partition_gardener/advisory_lock.rb

Constant Summary collapse

LOCK_NAMESPACE =
"partition_gardener"

Class Method Summary collapse

Class Method Details

.lock_expression(connection, table_name) ⇒ Object



42
43
44
45
46
# File 'lib/partition_gardener/advisory_lock.rb', line 42

def lock_expression(connection, table_name)
  namespace = connection.quote(LOCK_NAMESPACE)
  table = connection.quote(table_name)
  "hashtext(#{namespace}), hashtext(#{table})"
end

.with_session_lock(table_name) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/partition_gardener/advisory_lock.rb', line 16

def with_session_lock(table_name)
  connection = Connection.connection
  lock_sql = lock_expression(connection, table_name)
  acquired = false
  acquired = connection.execute("SELECT pg_try_advisory_lock(#{lock_sql})").first.values.first
  acquired = acquired == true || acquired == "t"
  raise LockNotAcquired, "session advisory lock not acquired for #{table_name}" unless acquired

  yield
ensure
  connection.execute("SELECT pg_advisory_unlock(#{lock_sql})") if connection && lock_sql && acquired
end

.with_table_lock(table_name, &block) ⇒ Object



7
8
9
10
11
12
13
14
# File 'lib/partition_gardener/advisory_lock.rb', line 7

def with_table_lock(table_name, &block)
  case PartitionGardener.configuration.advisory_lock_mode
  when :transaction
    with_transaction_lock(table_name, &block)
  else
    with_session_lock(table_name, &block)
  end
end

.with_transaction_lock(table_name) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/partition_gardener/advisory_lock.rb', line 29

def with_transaction_lock(table_name)
  connection = Connection.connection
  lock_sql = lock_expression(connection, table_name)

  connection.transaction do
    acquired = connection.execute("SELECT pg_try_advisory_xact_lock(#{lock_sql})").first.values.first
    acquired = acquired == true || acquired == "t"
    raise LockNotAcquired, "transaction advisory lock not acquired for #{table_name}" unless acquired

    yield
  end
end