Check constraints
Check constraints are defined in the constraints object of table definition using the check
function.
ts
import { integer, table, check } from "@monolayer/pg/schema";
import { sql } from "kysely";
export const books = table({
columns: {
id: integer(),
price: integer(),
},
constraints: {
check: check(sql`${sql.ref("price")} > 0`),
},
});
A check constraint can refer also to multiple columns:
ts
import { integer, table, check } from "@monolayer/pg/schema";
import { sql } from "kysely";
export const books = table({
columns: {
id: integer(),
price: integer(),
discount: integer(),
},
constraints: {
check: check(
sql`${sql.ref("price")} > 0 AND ${sql.ref("discount")} >= 10`
),
},
});
DANGER
It's recommended to reference column names with the sql.ref
function. This function takes care of:
- Double quote the column name (PostgreSQL lower cases all names unless they are "double quoted" ).
- Transform to the column name to
snake_case
when thecamelCase
option is active.