All files / src/model select-lock.ts

100% Statements 12/12
95.83% Branches 23/24
100% Functions 3/3
100% Lines 12/12

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        132x     132x 11x       132x 7862x 7846x   16x 1x     15x   7862x               7862x                         7862x      
import type { LockNode } from '../sql/ast.ts';
import { LOCK } from '../transaction/transaction.ts';
import type { SelectOptions } from './select-options.ts';
 
const LOCK_STRENGTHS: ReadonlySet<string> = new Set(Object.values(LOCK));
 
// Sequelize v6 emits FOR UPDATE for any lock level it does not know.
const lockStrength = (level: unknown): LockNode['strength'] =>
  typeof level === 'string' && LOCK_STRENGTHS.has(level)
    ? (level as LockNode['strength'])
    : LOCK.UPDATE;
 
const lockOf = (options: SelectOptions): LockNode | undefined => {
  if (options.lock === undefined || options.lock === false) {
    return undefined;
  }
  if (options.skipLocked === true && options.noWait === true) {
    throw new Error('skipLocked and noWait cannot be used together');
  }
  const wait =
    options.skipLocked === true ? 'SKIP LOCKED' : options.noWait === true ? 'NOWAIT' : undefined;
  const base: LockNode =
    options.lock === true
      ? { strength: 'UPDATE' }
      : typeof options.lock === 'string'
        ? { strength: lockStrength(options.lock) }
        : {
            strength: lockStrength(options.lock.level),
            ...(options.lock.of === undefined ? {} : { of: [options.lock.of.name] }),
          };
  return wait === undefined ? base : { ...base, wait };
};
 
/** Resolves the `lock`, `skipLocked` and `noWait` options into a row-lock clause. */
export class SelectLock {
  /**
   * Row-lock clause of the options.
   *
   * @param options - Select options.
   * @returns Lock node, or `undefined` without a lock.
   * @throws Error when `skipLocked` and `noWait` are both set.
   */
  of(options: SelectOptions): LockNode | undefined {
    return lockOf(options);
  }
}