Skip to content

monolayer-pg / schema / foreignKey

Function: foreignKey()

foreignKey(columns, targetColumns)

foreignKey<T, C>(columns, targetColumns): PgForeignKey<T, C>

Defines a foreign key constraint on a column or a group of columns.

Values in the column (or a group of columns) must match the values appearing in some row of another table, maintaining referential integrity between two related tables.

Type Parameters

Type Parameter
T extends string
C extends AnyPgTable

Parameters

ParameterTypeDescription
columnsT[]The column or a group of columns that will be constrained by the foreign key.
targetColumnsT[]The column or a group of columns in the target table that the foreign key references.

Returns

PgForeignKey<T, C>

Example

ts
import { integer, schema, table } from "@monolayer/pg/schema";

const users = table({
 columns: {
   id: integer().generatedAlwaysAsIdentity(),
 },
});

const documents = table({
  columns: {
    id: integer().generatedAlwaysAsIdentity(),
    userId: integer(),
  },
  constraints: {
    foreignKey: foreignKey(["userId"], users, ["id"]),
  },
});

const dbSchema = schema({
  tables: {
    users,
    documents,
  },
});

You can also create self-referential foreign keys, by ommiting the target table:

ts
import { integer, schema, table } from "@monolayer/pg/schema";

const tree = table({
  columns: {
    nodeId: integer().generatedAlwaysAsIdentity(),
    parentId: integer(),
  },
  constraints: {
    foreignKey: foreignKey(["parentId"], ["nodeId"]),
  },
});

const dbSchema = schema({
  tables: {
    users,
    documents,
  },
});

See

PostgreSQL docs: Foreign Keys

foreignKey(columns, targetTable, targetColumns)

foreignKey<T, C>(columns, targetTable, targetColumns): PgForeignKey<T, C>

Type Parameters

Type Parameter
T extends string
C extends AnyPgTable

Parameters

ParameterTypeDescription
columnsT[]The column or a group of columns that will be constrained by the foreign key.
targetTableCThe target table that the foreign key references.
targetColumnsC extends PgTable<U, any> ? keyof U[] : neverThe column or a group of columns in the target table that the foreign key references.

Returns

PgForeignKey<T, C>