All files / src/transaction advisory-locks.ts

100% Statements 7/7
77.77% Branches 7/9
100% Functions 4/4
100% Lines 7/7

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60                              448x 448x                     7x                           36x 36x       36x       43x                  
import type { ConnectionManager, ExecuteOptions } from '../connection/connection-manager.ts';
 
/** Advisory lock key: a 64-bit integer, or a string hashed by PostgreSQL. */
export type AdvisoryLockKey = number | bigint | string;
 
/** Transaction-level advisory locks taken on the connection of one transaction. */
export class AdvisoryLocks {
  readonly #connections: ConnectionManager;
  readonly #executeOptions: () => ExecuteOptions;
 
  /**
   * @param connections - Connection manager running the lock statements.
   * @param executeOptions - Execute options bound to the owning transaction.
   */
  constructor(connections: ConnectionManager, executeOptions: () => ExecuteOptions) {
    this.#connections = connections;
    this.#executeOptions = executeOptions;
  }
 
  /**
   * Waits for and takes the lock.
   *
   * @param key - Lock key.
   * @param shared - Take a shared lock.
   * @returns Resolves when the lock is held.
   */
  async lock(key: AdvisoryLockKey, shared: boolean): Promise<void> {
    await this.#connections.execute(
      AdvisoryLocks.#query(shared ? 'pg_advisory_xact_lock_shared' : 'pg_advisory_xact_lock', key),
      this.#executeOptions(),
    );
  }
 
  /**
   * Tries to take the lock without waiting.
   *
   * @param key - Lock key.
   * @param shared - Take a shared lock.
   * @returns True when the lock was acquired.
   */
  async tryLock(key: AdvisoryLockKey, shared: boolean): Promise<boolean> {
    const fn = shared ? 'pg_try_advisory_xact_lock_shared' : 'pg_try_advisory_xact_lock';
    const result = await this.#connections.execute(
      AdvisoryLocks.#query(fn, key, 'locked'),
      this.#executeOptions(),
    );
    return result.rows[0]?.['locked'] === true;
  }
 
  static #query(fn: string, key: AdvisoryLockKey, alias = 'lock') {
    return {
      text:
        typeof key === 'string'
          ? `SELECT ${fn}(hashtextextended($1, 0)) AS "${alias}"`
          : `SELECT ${fn}($1::bigint) AS "${alias}"`,
      values: [typeof key === 'string' ? key : String(key)],
    };
  }
}