kysely
    Preparing search index...

    Class WheneableMergeQueryBuilder<DB, TT, ST, O>

    Type Parameters

    • DB
    • TT extends keyof DB
    • ST extends keyof DB
    • O

    Implements

    Index

    Constructors

    Methods

    • Simply calls the provided function passing this as the only argument. $call returns what the provided function returns.

      If you want to conditionally call a method on this, see the $if method.

      The next example uses a helper function log to log a query:

      import type { Compilable } from 'kysely'

      function log<T extends Compilable>(qb: T): T {
      console.log(qb.compile())
      return qb
      }

      await db.updateTable('person')
      .set({ first_name: 'John' })
      .$call(log)
      .execute()

      Type Parameters

      • T

      Parameters

      • func: (qb: this) => T

      Returns T

    • Call func(this) if condition is true.

      This method is especially handy with optional selects. Any returning or returningAll method calls add columns as optional fields to the output type when called inside the func callback. This is because we can't know if those selections were actually made before running the code.

      You can also call any other methods inside the callback.

      import type { PersonUpdate } from 'type-editor' // imaginary module

      async function updatePerson(id: number, updates: PersonUpdate, returnLastName: boolean) {
      return await db
      .updateTable('person')
      .set(updates)
      .where('id', '=', id)
      .returning(['id', 'first_name'])
      .$if(returnLastName, (qb) => qb.returning('last_name'))
      .executeTakeFirstOrThrow()
      }

      Any selections added inside the if callback will be added as optional fields to the output type since we can't know if the selections were actually made before running the code. In the example above the return type of the updatePerson function is:

      Promise<{
      id: number
      first_name: string
      last_name?: string
      }>

      Type Parameters

      • O2

      Parameters

      Returns O2 extends MergeResult
          ? WheneableMergeQueryBuilder<DB, TT, ST, MergeResult>
          : O2 extends O & E
              ? WheneableMergeQueryBuilder<DB, TT, ST, O & Partial<E>>
              : WheneableMergeQueryBuilder<DB, TT, ST, Partial<O2>>

    • Allows you to return data from modified rows.

      On supported databases like MS SQL Server (MSSQL), this method can be chained to insert, update, delete and merge queries to return data.

      Also see the outputAll method.

      Return one column:

      const { id } = await db
      .insertInto('person')
      .output('inserted.id')
      .values({
      first_name: 'Jennifer',
      last_name: 'Aniston',
      gender: 'female',
      })
      .executeTakeFirstOrThrow()

      The generated SQL (MSSQL):

      insert into "person" ("first_name", "last_name", "gender")
      output "inserted"."id"
      values (@1, @2, @3)

      Return multiple columns:

      const { old_first_name, old_last_name, new_first_name, new_last_name } = await db
      .updateTable('person')
      .set({ first_name: 'John', last_name: 'Doe' })
      .output([
      'deleted.first_name as old_first_name',
      'deleted.last_name as old_last_name',
      'inserted.first_name as new_first_name',
      'inserted.last_name as new_last_name',
      ])
      .where('created_at', '<', new Date())
      .executeTakeFirstOrThrow()

      The generated SQL (MSSQL):

      update "person"
      set "first_name" = @1, "last_name" = @2
      output "deleted"."first_name" as "old_first_name",
      "deleted"."last_name" as "old_last_name",
      "inserted"."first_name" as "new_first_name",
      "inserted"."last_name" as "new_last_name"
      where "created_at" < @3

      Return arbitrary expressions:

      importsql } from 'kysely'

      const { full_name } = await db
      .deleteFrom('person')
      .output((eb) => sql<string>`concat(${eb.ref('deleted.first_name')}, ' ', ${eb.ref('deleted.last_name')})`.as('full_name'))
      .where('created_at', '<', new Date())
      .executeTakeFirstOrThrow()

      The generated SQL (MSSQL):

      delete from "person"
      output concat("deleted"."first_name", ' ', "deleted"."last_name") as "full_name"
      where "created_at" < @1

      Return the action performed on the row:

      await db
      .mergeInto('person')
      .using('pet', 'pet.owner_id', 'person.id')
      .whenMatched()
      .thenDelete()
      .whenNotMatched()
      .thenInsertValues({
      first_name: 'John',
      last_name: 'Doe',
      gender: 'male'
      })
      .output([
      'inserted.id as inserted_id',
      'deleted.id as deleted_id',
      ])
      .execute()

      The generated SQL (MSSQL):

      merge into "person"
      using "pet" on "pet"."owner_id" = "person"."id"
      when matched then delete
      when not matched then
      insert ("first_name", "last_name", "gender")
      values (@1, @2, @3)
      output "inserted"."id" as "inserted_id", "deleted"."id" as "deleted_id"

      Type Parameters

      • OE extends
            | AliasedExpression<any, any>
            | `deleted.${string}`
            | `inserted.${string}`
            | `deleted.${string} as ${string}`
            | `inserted.${string} as ${string}`
            | AliasedExpressionFactory<
                OutputDatabase<DB, TT, OutputPrefix>,
                OutputPrefix,
            >

      Parameters

      • selections: readonly OE[]

      Returns WheneableMergeQueryBuilder<
          DB,
          TT,
          ST,
          ReturningRow<DB, TT, O, SelectExpressionFromOutputExpression<OE>>,
      >

    • Type Parameters

      Parameters

      • callback: CB

      Returns WheneableMergeQueryBuilder<
          DB,
          TT,
          ST,
          ReturningRow<DB, TT, O, SelectExpressionFromOutputCallback<CB>>,
      >

    • Type Parameters

      • OE extends
            | AliasedExpression<any, any>
            | `deleted.${string}`
            | `inserted.${string}`
            | `deleted.${string} as ${string}`
            | `inserted.${string} as ${string}`
            | AliasedExpressionFactory<
                OutputDatabase<DB, TT, OutputPrefix>,
                OutputPrefix,
            >

      Parameters

      • selection: OE

      Returns WheneableMergeQueryBuilder<
          DB,
          TT,
          ST,
          ReturningRow<DB, TT, O, SelectExpressionFromOutputExpression<OE>>,
      >

    • Adds the when not matched clause to the query with an and condition.

      This method is similar to SelectQueryBuilder.where, so see the documentation for that method for more examples.

      For a simple when not matched clause (without an and condition) see whenNotMatched.

      Unlike whenMatchedAnd, you cannot reference columns from the table merged into.

      const result = await db.mergeInto('person')
      .using('pet', 'person.id', 'pet.owner_id')
      .whenNotMatchedAnd('pet.name', '=', 'Lucky')
      .thenInsertValues({
      first_name: 'John',
      last_name: 'Doe',
      })
      .execute()

      The generated SQL (PostgreSQL):

      merge into "person"
      using "pet" on "person"."id" = "pet"."owner_id"
      when not matched and "pet"."name" = $1 then
      insert ("first_name", "last_name") values ($2, $3)

      Type Parameters

      • RE extends
            | string
            | Expression<any>
            | DynamicReferenceBuilder<any>
            | SelectQueryBuilderExpression<Record<string, any>>
            | OperandExpressionFactory<DB, ST, any>
      • VE extends any

      Parameters

      Returns NotMatchedThenableMergeQueryBuilder<DB, TT, ST, O>

    • Adds the when not matched clause to the query with an and condition.

      This method is similar to SelectQueryBuilder.where, so see the documentation for that method for more examples.

      For a simple when not matched clause (without an and condition) see whenNotMatched.

      Unlike whenMatchedAnd, you cannot reference columns from the table merged into.

      const result = await db.mergeInto('person')
      .using('pet', 'person.id', 'pet.owner_id')
      .whenNotMatchedAnd('pet.name', '=', 'Lucky')
      .thenInsertValues({
      first_name: 'John',
      last_name: 'Doe',
      })
      .execute()

      The generated SQL (PostgreSQL):

      merge into "person"
      using "pet" on "person"."id" = "pet"."owner_id"
      when not matched and "pet"."name" = $1 then
      insert ("first_name", "last_name") values ($2, $3)

      Type Parameters

      Parameters

      • expression: E

      Returns NotMatchedThenableMergeQueryBuilder<DB, TT, ST, O>