Columns.ts overview

Pointing the stores at tables this package did not define: an AuthSchema maps each field a store needs to a column of the application’s table, checked at compile time by ColumnKey. See defineSchema for what such a table must satisfy.

Example

// An application's own `users` table: uuid keys, its own column names,
// columns the stores know nothing about.
const appUsers = pgTable("users", {
  userId: uuid("id").primaryKey(),
  displayName: text("display_name"),
  avatarUrl: text("avatar_url"),
  meta: jsonb("meta").$type<Auth.Types.JsonObject>().notNull().default({}),
  role: text("role").notNull().default("user"),
  created: timestamp("created_at", { withTimezone: true }).notNull(),
  updated: timestamp("updated_at", { withTimezone: true }).notNull(),
});

const schema = defineSchema({
  sessions: { table: appSessions, columns: { ... } },
  users: {
    table: appUsers,
    columns: {
      id: "userId",
      name: "displayName",
      image: "avatarUrl",
      attributes: "meta",
      createdAt: "created",
      updatedAt: "updated",
    },
  },
  identifiers: { table: appIdentifiers, columns: { ... } },
});

const stores = layer(schema).pipe(Layer.provide(databaseLayer(db)));

Exports Grouped by Category


utils

ApiKeyColumnNames (interface)

Which of TTable’s columns hold each field of an API key.

Signature

export interface ApiKeyColumnNames<TTable extends Table> {
  readonly id: ColumnKey<TTable, string>
  /** The owner: the column an application points its foreign key at `users.id` from. */
  readonly userId: ColumnKey<TTable, string>
  readonly name: ColumnKey<TTable, string | null>
  readonly prefix: ColumnKey<TTable, string | null>
  readonly start: ColumnKey<TTable, string>
  /** SHA-256 hex digest of the full key, never the key; give it a unique index. */
  readonly keyHash: ColumnKey<TTable, string>
  readonly enabled: ColumnKey<TTable, boolean>
  readonly expiresAt: ColumnKey<TTable, Date | null>
  readonly lastUsedAt: ColumnKey<TTable, Date | null>
  readonly permissions: ColumnKey<TTable, ApiKeyPermissions | null>
  readonly metadata: ColumnKey<TTable, Auth.Types.JsonObject | null>
  readonly remaining: ColumnKey<TTable, number | null>
  readonly refillAmount: ColumnKey<TTable, number | null>
  readonly refillInterval: ColumnKey<TTable, number | null>
  readonly refillMax: ColumnKey<TTable, number | null>
  readonly lastRefillAt: ColumnKey<TTable, Date | null>
  readonly rateLimitMaxRequests: ColumnKey<TTable, number | null>
  readonly rateLimitWindowMs: ColumnKey<TTable, number | null>
  readonly createdAt: ColumnKey<TTable, Date>
  readonly updatedAt: ColumnKey<TTable, Date>
}

Source

ApiKeyColumns (type alias)

The API key columns, resolved to drizzle column objects.

Signature

type ApiKeyColumns = {
  readonly id: StoreColumn<string>
  readonly userId: StoreColumn<string>
  readonly name: NullableColumn<string>
  readonly prefix: NullableColumn<string>
  readonly start: StoreColumn<string>
  readonly keyHash: StoreColumn<string>
  readonly enabled: StoreColumn<boolean>
  readonly expiresAt: NullableColumn<Date>
  readonly lastUsedAt: NullableColumn<Date>
  readonly permissions: NullableColumn<ApiKeyPermissions>
  readonly metadata: NullableColumn<Auth.Types.JsonObject>
  readonly remaining: NullableColumn<number>
  readonly refillAmount: NullableColumn<number>
  readonly refillInterval: NullableColumn<number>
  readonly refillMax: NullableColumn<number>
  readonly lastRefillAt: NullableColumn<Date>
  readonly rateLimitMaxRequests: NullableColumn<number>
  readonly rateLimitWindowMs: NullableColumn<number>
  readonly createdAt: StoreColumn<Date>
  readonly updatedAt: StoreColumn<Date>
}

Source

ApiKeySchema (type alias)

What ApiKeyStore addresses: one table and its mapping.

Signature

type ApiKeySchema = TableSchema<ApiKeyColumns> & { readonly _tag: "ApiKeySchema" }

Source

ApiKeyTableInput (type alias)

What ApiKeyStore accepts: a dialect’s tables, or a mapped API keys table.

Signature

type ApiKeyTableInput = Tables | ApiKeySchema

Source

AuthSchema (interface)

The three tables and their column mappings — what every store factory in this package ultimately runs against.

Build one with defineSchema for an application’s own tables, or with fromTables for the tables this package defines.

Signature

export interface AuthSchema {
  readonly _tag: "AuthSchema"
  readonly sessions: SessionSchema
  readonly users: UserSchema
  readonly identifiers: IdentifierSchema
}

Source

AuthSchemaSpec (interface)

The argument defineSchema takes.

Signature

export interface AuthSchemaSpec<TSessions extends Table, TUsers extends Table, TIdentifiers extends Table> {
  readonly sessions: TableSpec<TSessions, SessionColumnNames<TSessions>>
  readonly users: TableSpec<TUsers, UserColumnNames<TUsers>> & {
    /**
     * Attributes kept as real columns, keyed by attribute name: `{ role: "role" }`.
     * Each column must read back as a string, number, boolean or `null`.
     */
    readonly promoted?: Readonly<Record<string, ColumnKey<TUsers, PromotedValue>>>
  }
  readonly identifiers: TableSpec<TIdentifiers, IdentifierColumnNames<TIdentifiers>>
}

Source

ColumnKey (type alias)

The keys of TTable naming a column a SELECT reads back as TValue.

This is the whole type-level mechanism: InferSelectModel is drizzle’s own record of what each column yields — nullability, $type overrides and all — so filtering its keys by assignability to TValue is exactly “which of this table’s columns can stand in for the one the store needs”. A table with no such column resolves to never, and the mapping will not type-check.

Signature

type ColumnKey<TTable extends Table, TValue> = {
  [K in keyof InferSelectModel<TTable>]-?: InferSelectModel<TTable>[K] extends TValue ? K : never
}[keyof InferSelectModel<TTable>] &
  keyof InferInsertModel<TTable> &
  keyof TTable &
  string

Source

IdentifierColumnNames (interface)

Which of TTable’s columns hold each field of an identifier.

Signature

export interface IdentifierColumnNames<TTable extends Table> {
  readonly id: ColumnKey<TTable, string>
  readonly userId: ColumnKey<TTable, string>
  /**
   * `$type<Auth.Identifier.IdentifierType>()` is welcome but not required: a plain `text`
   * column maps fine. See {@link IdentifierColumns.type} for what the store
   * assumes about its contents.
   */
  readonly type: ColumnKey<TTable, string>
  readonly value: ColumnKey<TTable, string>
  readonly verified: ColumnKey<TTable, boolean>
  readonly verifiedAt: ColumnKey<TTable, Date | null>
  readonly createdAt: ColumnKey<TTable, Date>
}

Source

IdentifierColumns (type alias)

The identifier columns, resolved to drizzle column objects.

Signature

type IdentifierColumns = {
  readonly id: StoreColumn<string>
  readonly userId: StoreColumn<string>
  /**
   * Read back as an `Auth.Identifier.IdentifierType`. The mapping only requires a `string`
   * column, because an application's `type` column is usually plain `text`; this
   * package never writes a value outside the three, and a row that holds one
   * (put there by something else) is passed through as it was found rather than
   * rejected — the same behaviour the fixed-shape tables have always had.
   */
  readonly type: StoreColumn<Auth.Identifier.IdentifierType>
  readonly value: StoreColumn<string>
  readonly verified: StoreColumn<boolean>
  readonly verifiedAt: NullableColumn<Date>
  readonly createdAt: StoreColumn<Date>
}

Source

IdentifierSchema (type alias)

Everything the identifier store addresses.

Signature

type IdentifierSchema = TableSchema<IdentifierColumns>

Source

PromotedValue (type alias)

A value a promoted attribute column may read back as.

Signature

type PromotedValue = string | number | boolean | null

Source

RateLimitColumnNames (interface)

Which of TTable’s columns hold each field of a rate-limit counter.

Signature

export interface RateLimitColumnNames<TTable extends Table> {
  /** The rate-limit key; the primary key (the upsert conflicts on it). */
  readonly key: ColumnKey<TTable, string>
  readonly count: ColumnKey<TTable, number>
  readonly resetAt: ColumnKey<TTable, Date>
  readonly blockedUntil: ColumnKey<TTable, Date | null>
}

Source

RateLimitColumns (type alias)

The rate-limit columns, resolved to drizzle column objects.

Signature

type RateLimitColumns = {
  readonly key: StoreColumn<string>
  readonly count: StoreColumn<number>
  readonly resetAt: StoreColumn<Date>
  readonly blockedUntil: NullableColumn<Date>
}

Source

RateLimitSchema (type alias)

What RateLimitStore addresses: one table and its mapping.

Signature

type RateLimitSchema = TableSchema<RateLimitColumns> & { readonly _tag: "RateLimitSchema" }

Source

RateLimitTableInput (type alias)

What RateLimitStore accepts: a dialect’s tables, or a mapped rate-limit table.

Signature

type RateLimitTableInput = Tables | RateLimitSchema

Source

SchemaInput (type alias)

What a store factory accepts: this package’s tables, or a full mapping.

Signature

type SchemaInput = Tables | AuthSchema

Source

SchemaMappingError (class)

A defineSchema mapping the stores cannot use: a promoted attribute mapped onto a column the stores already write as a fixed field (id, name, image, attributes, createdAt, updatedAt, passwordHash).

Signature

declare class SchemaMappingError

Source

SessionColumnNames (interface)

Which of TTable’s columns hold each field of a session.

Signature

export interface SessionColumnNames<TTable extends Table> {
  /** SHA-256 hex digest of the bearer token — never the raw token itself. */
  readonly id: ColumnKey<TTable, string>
  readonly userId: ColumnKey<TTable, string>
  readonly expiresAt: ColumnKey<TTable, Date>
  readonly createdAt: ColumnKey<TTable, Date>
  readonly lastActivityAt: ColumnKey<TTable, Date>
  readonly attributes: ColumnKey<TTable, Auth.Types.JsonObject | null>
}

Source

SessionColumns (type alias)

The session columns, resolved to drizzle column objects.

Signature

type SessionColumns = {
  readonly id: StoreColumn<string>
  readonly userId: StoreColumn<string>
  readonly expiresAt: StoreColumn<Date>
  readonly createdAt: StoreColumn<Date>
  readonly lastActivityAt: StoreColumn<Date>
  readonly attributes: NullableColumn<Auth.Types.JsonObject>
}

Source

SessionSchema (type alias)

Everything the session store addresses.

Signature

type SessionSchema = TableSchema<SessionColumns>

Source

TableSchema (interface)

One table, and where each field the store needs lives in it.

Signature

export interface TableSchema<TColumns> {
  readonly table: Table
  readonly columns: TColumns
  /** The mapping that produced {@link columns}, kept for building writes. */
  readonly names: Readonly<Record<keyof TColumns & string, string>>
}

Source

TableSpec (interface)

One table plus its mapping, before resolution.

Signature

export interface TableSpec<TTable extends Table, TColumns> {
  readonly table: TTable
  readonly columns: TColumns
}

Source

TokenColumnNames (interface)

Which of TTable’s columns hold each field of a pending one-time token.

Signature

export interface TokenColumnNames<TTable extends Table> {
  /** SHA-256 hex digest of the token, never the token; the primary key. */
  readonly token: ColumnKey<TTable, string>
  /**
   * `"email-verification"` or `"password-reset"`: one table serves both
   * stores. A plain `text` column maps fine.
   */
  readonly purpose: ColumnKey<TTable, string>
  /** The owner: the column an application points its foreign key at `users.id` from. */
  readonly userId: ColumnKey<TTable, string>
  readonly email: ColumnKey<TTable, string>
  readonly createdAt: ColumnKey<TTable, Date>
  readonly expiresAt: ColumnKey<TTable, Date>
}

Source

TokenColumns (type alias)

The token columns, resolved to drizzle column objects.

Signature

type TokenColumns = {
  readonly token: StoreColumn<string>
  /** Read back as a `TokenPurpose`; the stores write no other value. */
  readonly purpose: StoreColumn<TokenPurpose>
  readonly userId: StoreColumn<string>
  readonly email: StoreColumn<string>
  readonly createdAt: StoreColumn<Date>
  readonly expiresAt: StoreColumn<Date>
}

Source

TokenSchema (type alias)

What the token stores address: one table and its mapping.

Signature

type TokenSchema = TableSchema<TokenColumns> & { readonly _tag: "TokenSchema" }

Source

TokenTableInput (type alias)

What the token stores accept: a dialect’s tables, or a mapped tokens table.

Signature

type TokenTableInput = Tables | TokenSchema

Source

UserColumnNames (interface)

Which of TTable’s columns hold each field of a user.

Signature

export interface UserColumnNames<TTable extends Table> {
  readonly id: ColumnKey<TTable, string>
  readonly name: ColumnKey<TTable, string | null>
  readonly image: ColumnKey<TTable, string | null>
  /**
   * The `jsonb` attribute bag. Optional: a table that keeps every attribute it
   * has as a promoted column needs none.
   */
  readonly attributes?: ColumnKey<TTable, Auth.Types.JsonObject | null>
  readonly createdAt: ColumnKey<TTable, Date>
  readonly updatedAt: ColumnKey<TTable, Date>
  /**
   * The password hash, a nullable text column. Optional: only
   * `EmailPasswordStore` reads or writes it (`UserStore` never selects it), and
   * that store's layer requires it.
   */
  readonly passwordHash?: ColumnKey<TTable, string | null>
}

Source

UserColumns (type alias)

The user columns, resolved to drizzle column objects.

Signature

type UserColumns = {
  readonly id: StoreColumn<string>
  readonly name: NullableColumn<string>
  readonly image: NullableColumn<string>
  readonly attributes?: NullableColumn<Auth.Types.JsonObject>
  readonly createdAt: StoreColumn<Date>
  readonly updatedAt: StoreColumn<Date>
  readonly passwordHash?: NullableColumn<string>
}

Source

UserSchema (type alias)

Everything the user store addresses.

Signature

type UserSchema = TableSchema<UserColumns> & {
  /** Attribute name → the real column that holds it, the only authority for that key. */
  readonly promoted: Readonly<Record<string, Column>>
}

Source

defineApiKeyTable

Point ApiKeyStore at an application’s own API keys table, so the application owns its migration and its user_id foreign key (with ON DELETE CASCADE, deleting a user revokes their keys in the database as well as through core’s account deletion).

Every field is mapped, since the store writes every one. The keyHash column needs a unique index; an extra required column the store knows nothing about needs a database default.

Example

const appApiKeys = pgTable("api_keys", {
  id: text("id").primaryKey(),
  owner: uuid("owner_id").notNull().references(() => appUsers.userId, { onDelete: "cascade" }),
  // ... the other columns, under the application's own names
});

const apiKeys = defineApiKeyTable({
  table: appApiKeys,
  columns: { id: "id", userId: "owner", keyHash: "digest", ... },
});

const store = ApiKeyStore.layer(apiKeys).pipe(Layer.provide(databaseLayer(db)));

Signature

declare const defineApiKeyTable: <TTable extends Table>(
  spec: TableSpec<TTable, ApiKeyColumnNames<TTable>>
) => ApiKeySchema

Source

defineRateLimitTable

Point RateLimitStore (and its purgeExpired) at an application’s own rate-limit table. key must be the primary key or carry a unique index: increment and set are upserts that conflict on it.

Signature

declare const defineRateLimitTable: <TTable extends Table>(
  spec: TableSpec<TTable, RateLimitColumnNames<TTable>>
) => RateLimitSchema

Source

defineSchema

Point the stores at tables this package did not define.

Each entry names a table and says which of its columns holds each field the corresponding store reads and writes. A column’s type must read back as the value the store needs (a uuid key reads as string; a bigint one is not supported). Beyond the mapping, a table still needs:

  • attribute bags that read back as an object (jsonb().$type<Auth.Types.JsonObject>(), not a bare jsonb());
  • a database default for every required column the stores do not know;
  • a unique index on the identifiers table’s (type, value), which makes Auth.Identifier.claimIdentifier correct.

An attribute under users.promoted is a real column, presented in user.attributes under its name; the column is the only authority for that key, and a NULL leaves it absent.

Throws SchemaMappingError when users.promoted maps an attribute onto a column already mapped to a fixed field.

Signature

declare const defineSchema: <TSessions extends Table, TUsers extends Table, TIdentifiers extends Table>(
  spec: AuthSchemaSpec<TSessions, TUsers, TIdentifiers>
) => AuthSchema

Source

defineTokenTable

Point TokenStore’s email-verification and password-reset stores at an application’s own tokens table, so the application owns its user_id foreign key: with ON DELETE CASCADE, deleting a user drops their pending tokens in the database too.

The table holds both purposes, told apart by the mapped purpose column, with token as its primary key; an index on (purpose, user_id) serves the per-user reads and deletes.

Signature

declare const defineTokenTable: <TTable extends Table>(spec: TableSpec<TTable, TokenColumnNames<TTable>>) => TokenSchema

Source

fromTables

The identity mapping over this package’s own tables: every field lives in the column of the same name.

This is what a store factory builds when it is handed a Tables set, which is why the fixed-shape path and the mapped path are one code path.

Signature

declare const fromTables: (tables: Tables) => AuthSchema

Source

resolveApiKeyTable

The identity mapping over a dialect’s API keys table. @internal

Signature

declare const resolveApiKeyTable: (input: ApiKeyTableInput) => ApiKeySchema

Source

resolveRateLimitTable

The identity mapping over a dialect’s rate-limit table. @internal

Signature

declare const resolveRateLimitTable: (input: RateLimitTableInput) => RateLimitSchema

Source

resolveSchema

Accept either shape a store factory is given. @internal

Signature

declare const resolveSchema: (input: SchemaInput) => AuthSchema

Source

resolveTokenTable

The identity mapping over a dialect’s tokens table. @internal

Signature

declare const resolveTokenTable: (input: TokenTableInput) => TokenSchema

Source


This site uses Just the Docs, a documentation theme for Jekyll.