All files / src/ddl routine-guards.ts

100% Statements 36/36
95.45% Branches 21/22
100% Functions 10/10
100% Lines 35/35

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 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155    133x     133x   133x   133x                                 133x   133x                   133x   133x   324x                                   1464x 588x   876x                       428x 156x   272x                     76x 76x 74x   2x                     101x 83x 83x 74x   9x                         470x 174x 9x   165x 165x 74x   91x                         1032x 50x       982x   983x        
import { SqlCompiler } from '../sql/compile.ts';
 
const WORD = /^[A-Za-z_]\w*$/;
 
const TYPE_NAME =
  /^(?:SETOF\s+)?[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)?(?:\s+[A-Za-z_]\w*){0,4}(?:\(\s*\d+(?:\s*,\s*\d+)?\s*\))?(?:\s+[A-Za-z_]\w*){0,4}(?:\[\d*\])*$/;
 
const DIRECTIONS: ReadonlySet<string> = new Set(['IN', 'OUT', 'INOUT', 'VARIADIC']);
 
const FUNCTION_OPTIONS: ReadonlySet<string> = new Set([
  'IMMUTABLE',
  'STABLE',
  'VOLATILE',
  'STRICT',
  'CALLED ON NULL INPUT',
  'RETURNS NULL ON NULL INPUT',
  'LEAKPROOF',
  'NOT LEAKPROOF',
  'PARALLEL SAFE',
  'PARALLEL UNSAFE',
  'PARALLEL RESTRICTED',
  'SECURITY DEFINER',
  'SECURITY INVOKER',
  'WINDOW',
]);
 
const FUNCTION_NUMBER_OPTION = /^(?:COST|ROWS) \d+$/;
 
const TRIGGER_OPTIONS: ReadonlySet<string> = new Set([
  'FOR EACH ROW',
  'FOR EACH STATEMENT',
  'DEFERRABLE',
  'NOT DEFERRABLE',
  'INITIALLY DEFERRED',
  'INITIALLY IMMEDIATE',
]);
 
const TRIGGER_REFERENCING =
  /^REFERENCING (?:OLD|NEW) TABLE AS [A-Za-z_]\w*(?: (?:OLD|NEW) TABLE AS [A-Za-z_]\w*)?$/;
 
const TRIGGER_WHEN = /^WHEN\s*\(/i;
 
const normalize = (value: string): string => value.trim().replaceAll(/\s+/g, ' ').toUpperCase();
 
/**
 * Allowlists and patterns for the keywords and type names of functions and triggers that cannot be
 * quoted (ADR-020, ADR-025).
 *
 * @internal
 */
export class RoutineGuards {
  /**
   * A plain identifier word (parameter, variable, language), rendered unquoted so it folds like v6.
   *
   * @param value - Word.
   * @param kind - Kind named in the error.
   * @returns The word.
   * @throws Error for anything but `[A-Za-z_]\w*`.
   */
  word(value: string, kind: string): string {
    if (!WORD.test(value)) {
      throw new Error(`Invalid ${kind}: ${value}`);
    }
    return value;
  }
 
  /**
   * A type name: words, an optional schema, a length / precision and array brackets.
   *
   * @param value - Type as written in SQL.
   * @param kind - Kind named in the error.
   * @returns The type.
   * @throws Error for anything that is not a type name.
   */
  typeName(value: string, kind: string): string {
    if (typeof value !== 'string' || !TYPE_NAME.test(value.trim())) {
      throw new Error(`Invalid ${kind}: ${String(value)}`);
    }
    return value.trim();
  }
 
  /**
   * Parameter direction keyword.
   *
   * @param value - Direction.
   * @returns Upper-case direction.
   * @throws Error outside `IN`, `OUT`, `INOUT`, `VARIADIC`.
   */
  direction(value: string): string {
    const direction = normalize(value);
    if (!DIRECTIONS.has(direction)) {
      throw new Error(`Invalid parameter direction: ${value}`);
    }
    return direction;
  }
 
  /**
   * Function characteristic keywords (`IMMUTABLE`, `SECURITY DEFINER`, `COST n`, ...).
   *
   * @param options - Keywords as given.
   * @returns Normalized keywords.
   * @throws Error for a keyword outside the allowlist.
   */
  functionOptions(options: readonly string[]): readonly string[] {
    return options.map((option) => {
      const keyword = normalize(option);
      if (!FUNCTION_OPTIONS.has(keyword) && !FUNCTION_NUMBER_OPTION.test(keyword)) {
        throw new Error(`Invalid function option: ${option}`);
      }
      return keyword;
    });
  }
 
  /**
   * Trigger clauses: row / statement level, deferrability, `REFERENCING` transition tables and
   * `WHEN (condition)`. The condition is trusted SQL.
   *
   * @param options - Clauses as given.
   * @returns Normalized clauses (`WHEN` kept as written).
   * @throws Error for a clause outside the allowlist.
   */
  triggerOptions(options: readonly string[]): readonly string[] {
    return options.map((option) => {
      if (TRIGGER_WHEN.test(option.trim())) {
        return option.trim();
      }
      const keyword = normalize(option);
      if (!TRIGGER_OPTIONS.has(keyword) && !TRIGGER_REFERENCING.test(keyword)) {
        throw new Error(`Invalid trigger option: ${option}`);
      }
      return keyword;
    });
  }
 
  /**
   * Function name: a word or `schema.word` string (unquoted, folds like v6) or `{ name, schema }`
   * (quoted exactly).
   *
   * @param name - Function name.
   * @returns SQL name.
   * @throws Error for a string that is not one or two identifier words.
   */
  functionName(name: string | Readonly<{ name: string; schema?: string }>): string {
    if (typeof name !== 'string') {
      return name.schema === undefined
        ? SqlCompiler.quoteIdent(name.name)
        : `${SqlCompiler.quoteIdent(name.schema)}.${SqlCompiler.quoteIdent(name.name)}`;
    }
    return name
      .split('.')
      .map((part) => this.word(part, 'function name'))
      .join('.');
  }
}