All files / src/connection query-logger.ts

92.85% Statements 13/14
100% Branches 20/20
100% Functions 5/5
92.85% Lines 13/14

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                                                  797x                   811x                   21137x 21137x           614x 614x                           646x 646x 32x   614x 646x 3x     611x              
import { SqlLiteral } from '../ddl/sql-literal.ts';
import type { CompiledQuery } from '../sql/compile.ts';
import type { LoggingFunction } from './options.ts';
 
/** Logging settings: instance defaults or per-query overrides. */
export type QueryLogSettings = Readonly<{
  /** SQL logger, or `false` to disable. */
  logging?: LoggingFunction | false;
  /** Pass the query duration to the logger. */
  benchmark?: boolean;
  /** Transaction id shown in the log line. */
  transactionId?: string;
}>;
 
/** Writes executed SQL to the configured logger (Sequelize v6 `logging` / `benchmark` output). */
export class QueryLogger {
  readonly #defaults: QueryLogSettings;
 
  /**
   * Logger for the `logging` / `benchmark` constructor options (`console.log` when `logging` is unset).
   *
   * @param options - Instance-level options.
   * @returns Logger.
   */
  static fromOptions(options: QueryLogSettings): QueryLogger {
    return new QueryLogger({
      logging: options.logging === undefined ? console.log : options.logging,
      ...(options.benchmark === undefined ? {} : { benchmark: options.benchmark }),
    });
  }
 
  /**
   * @param defaults - Instance-level `logging` and `benchmark` settings.
   */
  constructor(defaults: QueryLogSettings) {
    this.#defaults = defaults;
  }
 
  /**
   * Whether a statement run with these settings is logged, so callers can skip timing it.
   *
   * @param options - Per-query settings overriding the defaults.
   * @returns True when a logger is configured.
   */
  enabled(options: QueryLogSettings): boolean {
    const logging = options.logging ?? this.#defaults.logging;
    return logging !== false && logging !== undefined;
  }
 
  // Like v6 for a finder, the logged text carries the values, so it can be run as it is; the statement
  // sent to PostgreSQL keeps its bound parameters, and `bind` stays in the second argument.
  static #inlined(query: CompiledQuery): string {
    try {
      return new SqlLiteral().inlineValues(query);
    } catch {
      return query.text;
    }
  }
 
  /**
   * Logs one executed statement.
   *
   * @param query - Executed query.
   * @param options - Per-query settings overriding the defaults.
   * @param elapsed - Duration in milliseconds.
   */
  log(query: CompiledQuery, options: QueryLogSettings, elapsed: number): void {
    const logging = options.logging ?? this.#defaults.logging;
    if (logging === false || logging === undefined) {
      return;
    }
    const sql = `Executing (${options.transactionId ?? 'default'}): ${QueryLogger.#inlined(query)}`;
    if (options.benchmark ?? this.#defaults.benchmark) {
      logging(sql.replace('Executing', 'Executed'), elapsed);
    } else {
      // v6 passes the query options here although its typings declare `timing?: number`.
      (logging as (sql: string, options: unknown) => void)(sql, {
        bind: query.values,
        parameterizedSql: query.text,
      });
    }
  }
}