All files / src/model table-sample-builder.ts

90% Statements 9/10
92.3% Branches 12/13
100% Functions 1/1
90% Lines 9/10

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        132x 132x                       84x 84x 75x   9x 2x   7x     7x              
import type { TableSample } from '../sql/ast.ts';
import { SqlAst } from '../sql/ast.ts';
import type { TableSampleOptions } from './source-options.ts';
 
const ast = new SqlAst();
const METHODS: ReadonlySet<string> = new Set(['BERNOULLI', 'SYSTEM']);
 
/** Validates `sample` options and converts them to a `TABLESAMPLE` clause. */
export class TableSampleBuilder {
  /**
   * Builds the sampling clause.
   *
   * @param sample - Sample options.
   * @returns `TABLESAMPLE` node with bound percent and seed.
   * @throws Error for an unknown method, a percent outside 0–100, or a non-finite seed.
   */
  build(sample: TableSampleOptions): TableSample {
    const method = String(sample.method).toUpperCase();
    if (!METHODS.has(method)) {
      throw new Error(`Invalid TABLESAMPLE method: ${String(sample.method)}`);
    }
    if (!Number.isFinite(sample.percent) || sample.percent < 0 || sample.percent > 100) {
      throw new Error('TABLESAMPLE percent must be a number from 0 to 100');
    }
    Iif (sample.seed !== undefined && !Number.isFinite(sample.seed)) {
      throw new Error('TABLESAMPLE seed must be a finite number');
    }
    return {
      method: method as TableSample['method'],
      percent: ast.param(sample.percent),
      ...(sample.seed === undefined ? {} : { seed: ast.param(sample.seed) }),
    };
  }
}