All files / src/core/bindings D1Binding.ts

35.71% Statements 5/14
0% Branches 0/4
12.5% Functions 1/8
38.46% Lines 5/13

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 11928x 28x                                           28x               28x   28x                                                                                                                                                                          
import { Binding } from '@/core/bindings/Binding'
import { lazySettings } from '@/utils/lazySettings'
import { D1Settings } from '@/types/d1/D1Settings'
import type { CloudflareEnv } from '@/types/CloudflareEnv'
 
/**
 * Accessor for the D1 database binding (`d1_databases` in `wrangler.json`).
 *
 * Every query helper takes the statement and its bind values separately, so
 * user input is always parameterised rather than interpolated into SQL.
 *
 * @example
 * ```ts
 * const db = new D1Binding() // binding name from the configuration layer
 * const user = await db.first<User>(ctx.env, 'SELECT * FROM users WHERE id = ?', id)
 * ```
 *
 * @class
 *
 * @author Bayu Dwiyan Satria
 * @version 1.0.0
 * @since 1.0.0
 */
export class D1Binding<E extends CloudflareEnv = CloudflareEnv> extends Binding<D1Database, E> {
  /**
   * Constructs a D1Binding instance.
   *
   * @param settings Resolved settings. Defaults to `resolve('d1')`, so callers
   *   normally construct this with no arguments at all.
   */
  constructor(settings?: D1Settings) {
    const settle = lazySettings<D1Settings>('d1', settings)
 
    super(() => settle().binding)
  }
 
  /**
   * Prepares a statement, binding the supplied values when any are given.
   *
   * @param env The Worker environment.
   * @param query SQL statement, using `?` placeholders for bind values.
   * @param values Values bound to the placeholders, in order.
   * @returns The prepared statement, ready to run.
   * @throws {@link MissingBindingError} When the D1 binding is absent.
   */
  public prepare(env: E, query: string, ...values: unknown[]): D1PreparedStatement {
    const statement = this.resolve(env).prepare(query)
 
    return values.length > 0 ? statement.bind(...values) : statement
  }
 
  /**
   * Runs a query and returns every row.
   *
   * @param env The Worker environment.
   * @param query SQL statement, using `?` placeholders for bind values.
   * @param values Values bound to the placeholders, in order.
   * @returns The matched rows, empty when the query matched nothing.
   */
  public async all<T = Record<string, unknown>>(env: E, query: string, ...values: unknown[]): Promise<T[]> {
    const result = await this.prepare(env, query, ...values).all<T>()
 
    return result.results || []
  }
 
  /**
   * Runs a query and returns the first row.
   *
   * @param env The Worker environment.
   * @param query SQL statement, using `?` placeholders for bind values.
   * @param values Values bound to the placeholders, in order.
   * @returns The first matched row, or `null` when the query matched nothing.
   */
  public async first<T = Record<string, unknown>>(env: E, query: string, ...values: unknown[]): Promise<T | null> {
    return await this.prepare(env, query, ...values).first<T>()
  }
 
  /**
   * Runs a write statement and returns its execution metadata.
   *
   * @param env The Worker environment.
   * @param query SQL statement, using `?` placeholders for bind values.
   * @param values Values bound to the placeholders, in order.
   * @returns The D1 result, including `meta.changes` and `meta.last_row_id`.
   */
  public async run<T = Record<string, unknown>>(env: E, query: string, ...values: unknown[]): Promise<D1Result<T>> {
    return await this.prepare(env, query, ...values).run<T>()
  }
 
  /**
   * Runs several prepared statements in a single batch.
   *
   * Statements execute in order and are wrapped in an implicit transaction, so
   * a failure rolls the whole batch back.
   *
   * @param env The Worker environment.
   * @param statements Statements built via {@link D1Binding.prepare}.
   * @returns One result per statement, in the order supplied.
   */
  public async batch<T = unknown>(env: E, statements: D1PreparedStatement[]): Promise<D1Result<T>[]> {
    return await this.resolve(env).batch<T>(statements)
  }
 
  /**
   * Executes raw SQL, typically a migration or a multi-statement script.
   *
   * @remarks
   * This path does not support bind values — never build a statement here from
   * user input. Use {@link D1Binding.run} for anything parameterised.
   *
   * @param env The Worker environment.
   * @param query One or more SQL statements separated by newlines.
   * @returns The execution summary, including the number of statements run.
   */
  public async exec(env: E, query: string): Promise<D1ExecResult> {
    return await this.resolve(env).exec(query)
  }
}