Skip to content

Seeding

A seed file describes the rows you want. Supatype checks it against your schema, orders the writes by foreign key and applies them in one transaction.

Pre-1.0: APIs and config may change between releases.

Seed files

Put seed files in seeds/. They run in alphabetical order, so name them 01-authors.ts, 02-posts.ts. Files ending .ts, .mts or .tsx are found. When seeds/ holds none, seed.ts at the project root runs instead.

Each file exports a default function. The function does not connect or await anything. It records the writes, and the engine applies them.

seeds/01-blog.ts
import type { SeedContext } from "@supatype/cli/seed"
// Sign-in users are not seeded. Create one first, then paste the id list-users prints:
// supatype admin create-user --email alex@example.com --role editor
// supatype admin list-users
const ALEX = "<id from supatype admin list-users>"
export default async function seed({ db, expr, log }: SeedContext) {
log("seeding authors, tags and posts")
db.author.upsert({
where: { id: ALEX },
data: { id: ALEX, name: "Alex Rivera" },
})
db.tag.upsert({ where: { name: "news" }, data: { name: "news" } })
db.post.upsert({
where: { slug: "hello-world" },
data: {
title: "Hello world",
slug: "hello-world",
body: "Our first post.",
kind: "news",
views: expr.default(),
published_at: expr.ago({ days: 1 }),
author: { connect: { id: ALEX } },
comments: { create: [{ user_id: ALEX, body: "First!" }] },
},
})
}

This uses the schema from the Schema page.

The builder

db has one property per table, typed from your schema. A wrong column or a missing required field fails to compile.

The types come from supatype/generated/seed.ts, which is gitignored. supatype generate, dev and push write it, and a project made by supatype init also rebuilds it on install.

The context also has expr (values the database computes), log (print a line) and environment (the --environment name, if given).

db.$if(condition, body) runs body only when the database says so. The builder never connects, so the engine checks the condition when the seed runs. Use a plain if for anything your own code can decide.

seeds/02-tags.ts
import type { SeedContext } from "@supatype/cli/seed"
export default async function seed({ db }: SeedContext) {
db.$if({ notExists: { model: "Tag" } }, () => {
db.tag.create({ name: "general" })
})
}

The condition is { exists } or { notExists }, naming a model and an optional where, or { environment: "staging" }.

Without where, the condition asks whether the table has any row. A where names the rows to look for, in one of two forms:

seeds/03-once.ts
import { like, type SeedContext } from "@supatype/cli/seed"
export default async function seed({ db }: SeedContext) {
// Columns and values, like an upsert's `where`: every column equals its value.
db.$if({ notExists: { model: "Tag", where: { name: "general" } } }, () => {
db.tag.create({ name: "general" })
})
// A rule, for anything else: eq, neq, gt, gte, lt, lte, like, oneOf, isNull, notNull, and, or, not.
db.$if({ notExists: { model: "Tag", where: like("name", "team-%") } }, () => {
db.tag.create({ name: "team-default" })
})
}

In the plain form a value is a string, number, bigint, boolean, Date or null (which matches an empty column). Each is written the way an upsert’s where writes it, so a decimal column matches exactly. A value an earlier call returned, such as alex.id, cannot be compared there: the condition is checked against values known before the seed runs.

A file can also export a config. runOnce: true applies the file at most once, for a one-time backfill. It covers the whole run: if one file sets it, every file in that run gets it, with a warning.

seeds/01-blog.ts
export const config = { runOnce: true }

Create and upsert

CallDoes
db.tag.create(data)Inserts one row. Running the seed again inserts it again
db.tag.createMany(rows)Inserts many rows in one statement
db.tag.upsert({ where, data })Inserts the row, or updates the row where names

Use upsert for fixtures. Seeds get run again, and upsert makes that safe. where takes only columns that name one row: the primary key or a Unique<> column. A model with neither cannot be upserted, so give it a unique key.

Fields you leave out of data keep their current value when an upsert updates.

Relations

Set a foreign key by naming the related row by any unique key:

seeds/02-posts.ts
db.post.upsert({
where: { slug: "second-post" },
data: {
title: "Second post",
slug: "second-post",
body: "More news.",
kind: "news",
author: { connect: { id: ALEX } },
},
})

create and upsert return a reference you can use in later writes, such as post.id. It is a placeholder, filled in with the real value when the seed is applied. createMany returns nothing, so use create for a row you need to reference.

seeds/02-posts.ts
const tag = db.tag.create({ name: "release" })
log(`created a tag, referenced as ${JSON.stringify(tag.id)}`)

Nested children

Write a row’s children inside it with create or createMany. Their foreign keys are filled in for you.

Under an upsert, a child is written only if the parent has no child with the same values. So:

  • Running the seed again adds nothing.
  • A child whose values you changed is added beside the old one. The old one stays.
  • A child that matches is not updated. To change one, upsert it on its own model by a unique key.
  • Values the database computes, fields left out and expr.default() are not compared.

Rich text and defaults

A RichText field takes a plain string. It becomes a one-paragraph document. Rich text inside a block is not converted, so write the full document there.

A Blocks entry is { type, data }, with the block’s fields under data, as Studio stores it. See sections below.

A column stored as jsonb takes an object or an array as it is. A string is read as JSON text, so a value that is itself a JSON string needs its quotes: alert: JSON.stringify("outbid"), not alert: "outbid", which fails with invalid input syntax for type json. This includes a field whose type push stores as jsonb by fallback, such as a single string literal type.

expr gives values the database works out when the seed runs:

seeds/02-posts.ts
db.post.upsert({
where: { slug: "launch-day" },
data: {
title: "Launch day",
slug: "launch-day",
body: "We are live.",
sections: [{ type: "hero", data: { heading: "We are live" } }],
kind: "news",
views: expr.default(),
published_at: expr.now({ days: 7 }),
author: { connect: { id: ALEX } },
},
})

expr.now(), expr.ago({ days: 1 }), expr.startOf("day", { days: 30, hours: 9 }) and expr.startOfBefore("month", { months: 1 }) are times. startOf moves forward from the start of the period and startOfBefore moves back. They only fit date fields.

expr.default() sets the column’s own default. It is sent as { "$default": true }. Leaving a field out of an upsert keeps the old value. expr.default() resets it. It only fits columns that have a default.

Leave id out and the database makes one.

Sign-in users

A seed cannot create sign-in users. Users live in the auth schema, which the seed builder does not reach. Create them first, then put their ids in the seed:

Terminal window
$ supatype admin create-user --email alex@example.com --role editor
$ supatype admin list-users

create-user also gives the user a Studio role (admin if you do not pass --role). list-users prints each id.

For app users with no Studio access, sign them up through the client’s auth.signUp, or create them in Studio under Authentication > Users with Studio access set to “No access”.

A SupatypeAuthUserId field with onDelete has a foreign key to the user, so the user must exist before the seed runs.

Many-to-many rows

Many-to-many relations have no nested write yet. The rows live in the junction table, which the builder does not list, so a seed writes them with db.$sql, which runs in the same transaction. (App code can write the same rows through the client: see Linking many-to-many rows.)

seeds/03-tags.ts
db.$sql(
`insert into post_tag (post_id, tag_id)
select p.id, t.id from post p, tag t
where p.slug = $1 and t.name = $2
on conflict do nothing`,
["hello-world", "news"],
)

The statement runs at its position in the file, after every write above it, so it can read the rows those writes made.

Each param binds by its JSON type: a string as text, a whole number as bigint, any other number as double precision, a boolean as boolean, and an object or array as jsonb. A column of another type needs a cast on its placeholder, such as $1::uuid. That includes an id taken from an earlier write, such as post.id, which binds as text:

seeds/03-tags.ts
const post = db.post.upsert({
where: { slug: "release-notes" },
data: {
title: "Release notes",
slug: "release-notes",
body: "What changed.",
kind: "news",
author: { connect: { id: ALEX } },
},
})
db.$sql(
`insert into post_tag (post_id, tag_id)
select $1::uuid, t.id from tag t where t.name = $2
on conflict do nothing`,
[post.id, "news"],
)

A JavaScript bigint is sent as its digits, and a Date as an ISO timestamp. Both bind as text, so cast them: $1::bigint, $2::timestamptz. expr values, expr.default() included, are refused as params.

Running seeds

Terminal window
$ supatype seed # every file in seeds/
$ supatype seed seeds/02-posts.ts # one file
$ supatype seed --atomic # all files in one transaction
$ supatype seed --status # what ran, when, and what changed since
$ supatype seed --connection <dsn> # another database, from this machine
$ supatype seed --env staging # a linked project's environment
$ supatype seed --local # the local stack, even when linked
$ supatype seed --environment staging

--status lists each applied file with its status, when it ran, how long it took, and whether the file has changed since. --environment names the environment for an { environment } condition.

A Docker project’s local stack has to be running: with it stopped, supatype seed starts nothing and exits 2, saying to start it with supatype dev, or supatype self-host compose up -d on a server. --connection seeds the database it names either way.

Each file is one transaction. Without --atomic, a failure in the third file leaves the first two applied, and the report says so.

Errors name your schema, such as Tag.name is already taken, with the file and position. Exit code 1 means a seed failed. Exit code 2 means the run could not start.

A seed writes the model’s own table, so rows on a drafts model are seeded as published.

A linked project

A project linked with supatype link, to Supatype Cloud or to a self-hosted server, seeds through that server. The CLI collects your files as it does locally and sends the result to the server, which applies it as the environment’s own database role. The CLI never holds the database credential. --env <name> picks the environment, and the link’s default is used without it.

  • Seeding production asks you to type the project ref. In a script, or with no terminal, pass --confirm-production. A self-hosted server’s one environment is production.
  • --force is refused on a linked project. Use --confirm-production to skip the prompt, or --local to seed the stack on this machine instead.
  • --environment must match the environment being seeded, because that is what an { environment } condition reads. Drop it, or pass --env with the same name.
  • Every file must export default a function. A file without one would run its writes when it is read, so it is refused before anything is sent.
  • The server refuses with schema_not_pushed when the database lacks the schema the seed was built against. Run supatype push first.
  • --status needs only permission to view the project. Applying a seed needs permission to push the schema.
  • --connection and --local skip the link and seed the database or stack on this machine.