Postgres Connection String

DrizzleORM Schema

Type Parameters

  • TSchema extends Record<string, unknown> = Record<string, never>

Hierarchy

  • PgDatabase<PostgresJsQueryResultHKT, TSchema>
    • Pool

Constructors

  • Type Parameters

    • TSchema extends Record<string, unknown> = Record<string, never>

    Parameters

    • connstr: string
    • config: {
          options?: PostgresJsSessionOptions;
          schema: TSchema;
          ssl?: { rejectUnauthorized?: boolean };
      }

    Returns Pool<TSchema>

Properties

_: {
    fullSchema: TSchema;
    schema: undefined | ExtractTablesWithRelations<TSchema>;
    session: PgSession<
        PostgresJsQueryResultHKT,
        TSchema,
        ExtractTablesWithRelations<TSchema>,
    >;
    tableNamesMap: Record<string, string>;
}
authToken?: NeonAuthToken
connstr: string
query: TSchema extends Record<string, never>
    ? DrizzleTypeError<
        "Seems like the schema generic is missing - did you forget to add it to your DB type?",
    >
    : {
        [K in string
        | number
        | symbol]: RelationalQueryBuilder<
            ExtractTablesWithRelations<TSchema>,
            ExtractTablesWithRelations<TSchema>[K],
        >
    }
schema: TSchema
"[entityKind]": string

Methods

  • Parameters

    • source: SQLWrapper | SQL | PgTable | PgViewBase
    • Optionalfilters: SQL

    Returns PgCountBuilder<PgSession<any, any, any>>

  • Creates a subquery that defines a temporary named result set as a CTE.

    It is useful for breaking down complex queries into simpler parts and for reusing the result set in subsequent parts of the query.

    See docs: https://orm.drizzle.team/docs/select#with-clause

    Type Parameters

    • TAlias extends string

    Parameters

    • alias: TAlias

      The alias for the subquery.

      Failure to provide an alias will result in a DrizzleTypeError, preventing the subquery from being referenced in other queries.

    Returns {
        as<TSelection extends ColumnsSelection>(
            qb:
                | TypedQueryBuilder<TSelection>
                | (qb: QueryBuilder) => TypedQueryBuilder<TSelection>,
        ): WithSubqueryWithSelection<TSelection, TAlias>;
    }

    // Create a subquery with alias 'sq' and use it in the select query
    const sq = db.$with('sq').as(db.select().from(users).where(eq(users.id, 42)));

    const result = await db.with(sq).select().from(sq);

    To select arbitrary SQL values as fields in a CTE and reference them in other CTEs or in the main query, you need to add aliases to them:

    // Select an arbitrary SQL value as a field in a CTE and reference it in the main query
    const sq = db.$with('sq').as(db.select({
    name: sql<string>`upper(${users.name})`.as('name'),
    })
    .from(users));

    const result = await db.with(sq).select({ name: sq.name }).from(sq);
  • Creates a delete query.

    Calling this method without .where() clause will delete all rows in a table. The .where() clause specifies which rows should be deleted.

    See docs: https://orm.drizzle.team/docs/delete

    Type Parameters

    • TTable extends PgTable

    Parameters

    • table: TTable

      The table to delete from.

    Returns PgDeleteBase<TTable, PostgresJsQueryResultHKT>

    // Delete all rows in the 'cars' table
    await db.delete(cars);

    // Delete rows with filters and conditions
    await db.delete(cars).where(eq(cars.color, 'green'));

    // Delete with returning clause
    const deletedCar: Car[] = await db.delete(cars)
    .where(eq(cars.id, 1))
    .returning();
  • Type Parameters

    • TRow extends Record<string, unknown> = Record<string, unknown>

    Parameters

    • query: string | SQLWrapper

    Returns PgRaw<RowList<Assume<TRow, Row>[]>>

  • Creates an insert query.

    Calling this method will create new rows in a table. Use .values() method to specify which values to insert.

    See docs: https://orm.drizzle.team/docs/insert

    Type Parameters

    • TTable extends PgTable

    Parameters

    • table: TTable

      The table to insert into.

    Returns PgInsertBuilder<TTable, PostgresJsQueryResultHKT>

    // Insert one row
    await db.insert(cars).values({ brand: 'BMW' });

    // Insert multiple rows
    await db.insert(cars).values([{ brand: 'BMW' }, { brand: 'Porsche' }]);

    // Insert with returning clause
    const insertedCar: Car[] = await db.insert(cars)
    .values({ brand: 'BMW' })
    .returning();
  • Type Parameters

    • TView extends PgMaterializedView

    Parameters

    Returns PgRefreshMaterializedView<PostgresJsQueryResultHKT>

  • Creates a select query.

    Calling this method with no arguments will select all columns from the table. Pass a selection object to specify the columns you want to select.

    Use .from() method to specify which table to select from.

    See docs: https://orm.drizzle.team/docs/select

    Returns PgSelectBuilder<undefined>

    // Select all columns and all rows from the 'cars' table
    const allCars: Car[] = await db.select().from(cars);

    // Select specific columns and all rows from the 'cars' table
    const carsIdsAndBrands: { id: number; brand: string }[] = await db.select({
    id: cars.id,
    brand: cars.brand
    })
    .from(cars);

    Like in SQL, you can use arbitrary expressions as selection fields, not just table columns:

    // Select specific columns along with expression and all rows from the 'cars' table
    const carsIdsAndLowerNames: { id: number; lowerBrand: string }[] = await db.select({
    id: cars.id,
    lowerBrand: sql<string>`lower(${cars.brand})`,
    })
    .from(cars);
  • Creates a select query.

    Calling this method with no arguments will select all columns from the table. Pass a selection object to specify the columns you want to select.

    Use .from() method to specify which table to select from.

    See docs: https://orm.drizzle.team/docs/select

    Type Parameters

    • TSelection extends SelectedFields

    Parameters

    Returns PgSelectBuilder<TSelection>

    // Select all columns and all rows from the 'cars' table
    const allCars: Car[] = await db.select().from(cars);

    // Select specific columns and all rows from the 'cars' table
    const carsIdsAndBrands: { id: number; brand: string }[] = await db.select({
    id: cars.id,
    brand: cars.brand
    })
    .from(cars);

    Like in SQL, you can use arbitrary expressions as selection fields, not just table columns:

    // Select specific columns along with expression and all rows from the 'cars' table
    const carsIdsAndLowerNames: { id: number; lowerBrand: string }[] = await db.select({
    id: cars.id,
    lowerBrand: sql<string>`lower(${cars.brand})`,
    })
    .from(cars);
  • Adds distinct expression to the select query.

    Calling this method will return only unique values. When multiple columns are selected, it returns rows with unique combinations of values in these columns.

    Use .from() method to specify which table to select from.

    See docs: https://orm.drizzle.team/docs/select#distinct

    Returns PgSelectBuilder<undefined>

    // Select all unique rows from the 'cars' table
    await db.selectDistinct()
    .from(cars)
    .orderBy(cars.id, cars.brand, cars.color);

    // Select all unique brands from the 'cars' table
    await db.selectDistinct({ brand: cars.brand })
    .from(cars)
    .orderBy(cars.brand);
  • Adds distinct expression to the select query.

    Calling this method will return only unique values. When multiple columns are selected, it returns rows with unique combinations of values in these columns.

    Use .from() method to specify which table to select from.

    See docs: https://orm.drizzle.team/docs/select#distinct

    Type Parameters

    • TSelection extends SelectedFields

    Parameters

    Returns PgSelectBuilder<TSelection>

    // Select all unique rows from the 'cars' table
    await db.selectDistinct()
    .from(cars)
    .orderBy(cars.id, cars.brand, cars.color);

    // Select all unique brands from the 'cars' table
    await db.selectDistinct({ brand: cars.brand })
    .from(cars)
    .orderBy(cars.brand);
  • Adds distinct on expression to the select query.

    Calling this method will specify how the unique rows are determined.

    Use .from() method to specify which table to select from.

    See docs: https://orm.drizzle.team/docs/select#distinct

    Parameters

    • on: (SQLWrapper | PgColumn)[]

      The expression defining uniqueness.

    Returns PgSelectBuilder<undefined>

    // Select the first row for each unique brand from the 'cars' table
    await db.selectDistinctOn([cars.brand])
    .from(cars)
    .orderBy(cars.brand);

    // Selects the first occurrence of each unique car brand along with its color from the 'cars' table
    await db.selectDistinctOn([cars.brand], { brand: cars.brand, color: cars.color })
    .from(cars)
    .orderBy(cars.brand, cars.color);
  • Adds distinct on expression to the select query.

    Calling this method will specify how the unique rows are determined.

    Use .from() method to specify which table to select from.

    See docs: https://orm.drizzle.team/docs/select#distinct

    Type Parameters

    • TSelection extends SelectedFields

    Parameters

    • on: (SQLWrapper | PgColumn)[]

      The expression defining uniqueness.

    • fields: TSelection

      The selection object.

    Returns PgSelectBuilder<TSelection>

    // Select the first row for each unique brand from the 'cars' table
    await db.selectDistinctOn([cars.brand])
    .from(cars)
    .orderBy(cars.brand);

    // Selects the first occurrence of each unique car brand along with its color from the 'cars' table
    await db.selectDistinctOn([cars.brand], { brand: cars.brand, color: cars.color })
    .from(cars)
    .orderBy(cars.brand, cars.color);
  • Type Parameters

    • T

    Parameters

    • transaction: (
          tx: PgTransaction<
              PostgresJsQueryResultHKT,
              TSchema,
              ExtractTablesWithRelations<TSchema>,
          >,
      ) => Promise<T>
    • Optionalconfig: PgTransactionConfig

    Returns Promise<T>

  • Creates an update query.

    Calling this method without .where() clause will update all rows in a table. The .where() clause specifies which rows should be updated.

    Use .set() method to specify which values to update.

    See docs: https://orm.drizzle.team/docs/update

    Type Parameters

    • TTable extends PgTable

    Parameters

    • table: TTable

      The table to update.

    Returns PgUpdateBuilder<TTable, PostgresJsQueryResultHKT>

    // Update all rows in the 'cars' table
    await db.update(cars).set({ color: 'red' });

    // Update rows with filters and conditions
    await db.update(cars).set({ color: 'red' }).where(eq(cars.brand, 'BMW'));

    // Update with returning clause
    const updatedCar: Car[] = await db.update(cars)
    .set({ color: 'red' })
    .where(eq(cars.id, 1))
    .returning();
  • Incorporates a previously defined CTE (using $with) into the main query.

    This method allows the main query to reference a temporary named result set.

    See docs: https://orm.drizzle.team/docs/select#with-clause

    Parameters

    • ...queries: WithSubquery[]

      The CTEs to incorporate into the main query.

    Returns {
        delete: <TTable extends PgTable>(
            table: TTable,
        ) => PgDeleteBase<TTable, PostgresJsQueryResultHKT>;
        insert: <TTable extends PgTable>(
            table: TTable,
        ) => PgInsertBuilder<TTable, PostgresJsQueryResultHKT>;
        select: {
            (): PgSelectBuilder<undefined>;
            <TSelection extends SelectedFields>(
                fields: TSelection,
            ): PgSelectBuilder<TSelection>;
        };
        selectDistinct: {
            (): PgSelectBuilder<undefined>;
            <TSelection extends SelectedFields>(
                fields: TSelection,
            ): PgSelectBuilder<TSelection>;
        };
        selectDistinctOn: {
            (on: (SQLWrapper | PgColumn)[]): PgSelectBuilder<undefined>;
            <TSelection extends SelectedFields>(
                on: (SQLWrapper | PgColumn)[],
                fields: TSelection,
            ): PgSelectBuilder<TSelection>;
        };
        update: <TTable extends PgTable>(
            table: TTable,
        ) => PgUpdateBuilder<TTable, PostgresJsQueryResultHKT>;
    }

    // Define a subquery 'sq' as a CTE using $with
    const sq = db.$with('sq').as(db.select().from(users).where(eq(users.id, 42)));

    // Incorporate the CTE 'sq' into the main query and select from it
    const result = await db.with(sq).select().from(sq);
  • Connect to a database and return a slonik connection

    Type Parameters

    • TSchema extends Record<string, unknown> = Record<string, never>

    Parameters

    • connstr: string

      Postgres Connection String

    • schema: TSchema
    • Optionalopts: {
          migrationsFolder?: string;
          options?: PostgresJsSessionOptions;
          retry?: number;
          ssl?: { rejectUnauthorized?: boolean };
      } = {}

      Options Object

      • OptionalmigrationsFolder?: string
      • Optionaloptions?: PostgresJsSessionOptions
      • Optionalretry?: number

        Number of times to retry an initial connection

      • Optionalssl?: { rejectUnauthorized?: boolean }

    Returns Promise<Pool<TSchema>>