### Initialize Snaplet Seed Project
Source: https://snaplet-seed.netlify.app/seed/getting-started/installation
Starts the interactive setup wizard for Snaplet Seed. This command guides the user through the initial project configuration and setup process.
```bash
npx @snaplet/seed init
```
--------------------------------
### Initialize Snaplet Seed Client
Source: https://snaplet-seed.netlify.app/seed/getting-started/quick-start
This TypeScript code initializes the Snaplet Seed client, which is used to create and manage seed data.
```typescript
import { createSeedClient } from '@snaplet/seed';
const seed = await createSeedClient();
```
--------------------------------
### Install Snaplet Seed Dependencies
Source: https://snaplet-seed.netlify.app/seed/getting-started/installation
Installs the necessary Snaplet Seed and Copycat development dependencies using npm. These packages are required for database seeding and data generation.
```bash
npm install -D @snaplet/seed @snaplet/copycat
```
--------------------------------
### Create and Execute a Basic Seed Script
Source: https://snaplet-seed.netlify.app/seed/getting-started/installation
Demonstrates how to create a `seed.ts` file to seed a database. It includes resetting the database, seeding 10 users into the `users` table, and exiting the process.
```typescript
import { createSeedClient } from "@snaplet/seed";
const seed = await createSeedClient();
// Truncate all tables in the database
await seed.$resetDatabase();
// Seed the database with 10 users
await seed.users((x) => x(10));
process.exit();
```
--------------------------------
### Sync Snaplet Seed Assets
Source: https://snaplet-seed.netlify.app/seed/getting-started/quick-start
This command synchronizes the @snaplet/seed assets with your database schema. It's a necessary step before writing seed scripts.
```bash
npx @snaplet/seed sync
```
--------------------------------
### Importing Copycat in Seed Example
Source: https://snaplet-seed.netlify.app/seed/release-notes-archive
Example of importing `@snaplet/copycat` in a `seed.mts` file, which is now automatically included by `npx snaplet setup`.
```typescript
import '@snaplet/copycat';
```
--------------------------------
### Configure Snaplet Seed for PostgreSQL
Source: https://snaplet-seed.netlify.app/seed/getting-started/quick-start
This TypeScript code configures the @snaplet/seed adapter for a PostgreSQL database. It sets up the connection string and initializes the SeedPostgres adapter.
```typescript
import { SeedPostgres } from "@snaplet/seed/adapter-postgres";
import { defineConfig } from "@snaplet/seed/config";
import postgres from "postgres";
export default defineConfig({
adapter: () => {
const client = postgres("postgres://postgres@localhost:5432/blog");
return new SeedPostgres(client);
},
});
```
--------------------------------
### Preview Snaplet Seed Script with Dry Run
Source: https://snaplet-seed.netlify.app/seed/getting-started/quick-start
Execute the Snaplet seed script using `npx tsx seed.ts` with the `dryRun: true` option to preview the generated SQL INSERT statements without actually modifying the database. This is useful for verifying the data before it's applied.
```bash
npx tsx seed.ts
```
--------------------------------
### Initialize Snaplet Seed
Source: https://snaplet-seed.netlify.app/seed/migrations
Command to start the Snaplet Seed journey using the new onboarding wizard.
```bash
npx @snaplet/seed init
```
--------------------------------
### Sync Snaplet Seed with Database Schema Changes
Source: https://snaplet-seed.netlify.app/seed/getting-started/quick-start
When your database schema evolves, synchronize the Snaplet seed assets by running `npx @snaplet/seed sync`. This command fetches the latest schema from the database and regenerates the necessary seed files.
```bash
npx @snaplet/seed sync
```
--------------------------------
### Install Postgres Adapter for Snaplet Seed
Source: https://snaplet-seed.netlify.app/seed/integrations/supabase
Install the 'postgres' npm package as a development dependency to enable Snaplet Seed to interface with your PostgreSQL database.
```bash
npm install -D postgres
```
--------------------------------
### Seed Data into Database with Snaplet
Source: https://snaplet-seed.netlify.app/seed/getting-started/quick-start
To seed the generated data into the database, remove the `dryRun` option from the command. This will execute the SQL statements and insert the data directly into your database.
```typescript
const seed = await createSeedClient();
```
--------------------------------
### Snaplet Seed Script Output (Dry Run)
Source: https://snaplet-seed.netlify.app/seed/getting-started/quick-start
The output from a dry run of the Snaplet seed script shows the SQL INSERT statements that would be executed. This includes statements for inserting data into 'public.user', 'public.post', and 'public.comment' tables.
```sql
INSERT INTO public.user (email,id,username) VALUES
('Craig.Bednar82365@acme.org', '24058b0d-21ec-54b8-a3fa-b0ad8034f10f', 'site-glance56860'),
('Humberto.Bruen34274@meternephew.org', '241ed1d9-c36c-50d4-b783-e12ce5187076', 'Alexis-Gleason29168'),
('Mattie.Braun26688@plodantechamber.com', '8c84c800-1b34-5843-b34b-73d3239f0c5b', 'blissful-fountain21234'),
('Dannie_Osinski74665@brownmidline.name', '0e041e68-00c0-53db-b0f8-e28be8a009e0', 'visualise-service97805');
INSERT INTO public.post (title,content,author_id,id) VALUES
('Hello World!', 'Ramo ramukin rae racea rakesoma, me vayota yume vi keyo munavima.', '24058b0d-21ec-54b8-a3fa-b0ad8034f10f', '1a294726-1661-5d42-aaf6-cdb66e6c6eaf');
INSERT INTO public.comment (content,id,post_id,author_id,written_at) VALUES
('Ma ceasova yuviketa shira chiyomu.', '13fdf8d2-2199-5dfd-81d0-c8dd3ce3b8a6', '1a294726-1661-5d42-aaf6-cdb66e6c6eaf', '241ed1d9-c36c-50d4-b783-e12ce5187076', DEFAULT),
('Mukinra kahyceako kiva kai me hameso rae.', '71a504eb-a859-5217-9e27-e15975ac69c6', '1a294726-1661-5d42-aaf6-cdb66e6c6eaf', '8c84c800-1b34-5843-b34b-73d3239f0c5b', DEFAULT),
('Ma nacea va memumi ta, mami viyua yoma shimusona viyo metake.', '8e826b31-f774-57f3-8ef2-183bddb35f3e', '1a294726-1661-5d42-aaf6-cdb66e6c6eaf', '0e041e68-00c0-53db-b0f8-e28be8a009e0', DEFAULT);
```
--------------------------------
### Generate Snaplet Seed Client
Source: https://snaplet-seed.netlify.app/seed/getting-started/installation
Synchronizes the Snaplet Seed client with the database schema. This command introspects the database and generates the client files needed for seeding operations.
```bash
npx @snaplet/seed sync
```
--------------------------------
### Configure Snaplet Seed with PostgreSQL Adapter
Source: https://snaplet-seed.netlify.app/seed/getting-started/installation
Sets up the `seed.config.ts` file to use the PostgreSQL adapter. This involves importing necessary modules, defining the adapter configuration with a database connection string, and exporting the configuration object.
```typescript
import { SeedPostgres } from "@snaplet/seed/adapter-postgres";
import { defineConfig } from "@snaplet/seed/config";
import postgres from "postgres";
export default defineConfig({
adapter: () => {
const client = postgres(process.env.DATABASE_URL);
return new SeedPostgres(client);
},
});
```
--------------------------------
### Initialize Seed Project with CLI
Source: https://snaplet-seed.netlify.app/seed/getting-started/overview
Provides the command to initialize a new project with Snaplet Seed. This command sets up the necessary configurations for the Seed CLI to start generating data clients.
```Bash
npx @snaplet/seed init
```
--------------------------------
### Execute Snaplet Seed Script
Source: https://snaplet-seed.netlify.app/seed/getting-started/installation
Runs a Snaplet Seed script, typically named `seed.ts`. This command executes the database seeding operations defined in the script.
```bash
npx tsx seed.ts
```
--------------------------------
### Initialize Snaplet Seed
Source: https://snaplet-seed.netlify.app/seed/integrations/supabase
Run the Snaplet Seed initialization command in your project's root directory. This command sets up the necessary configuration files for Snaplet Seed.
```bash
npx @snaplet/seed init
```
--------------------------------
### Initialize Snaplet Seed for Prisma
Source: https://snaplet-seed.netlify.app/seed/integrations/prisma
Installs Snaplet Seed in your Prisma project, creating necessary configuration and seed files within the specified directory.
```bash
npx @snaplet/seed init prisma/seed
```
--------------------------------
### Install @snaplet/seed
Source: https://snaplet-seed.netlify.app/seed/migrations
Installs the new @snaplet/seed package as a development dependency using npm.
```bash
npm install -D @snaplet/seed
```
--------------------------------
### Snaplet Generate Example
Source: https://snaplet-seed.netlify.app/seed/release-notes-archive
Demonstrates how to explicitly provide a name to a Snaplet user and how the generated value might change after an upgrade when the name is not explicitly provided.
```javascript
await snaplet.users({ name: 'Garnet Harley' })
// name not given explicitly
// => the generated value might have now changed
// (after the first `snaplet generate` after upgrading)
await snaplet.users({})
```
--------------------------------
### Configure Prisma Adapter for Snaplet Seed
Source: https://snaplet-seed.netlify.app/seed/migrations
Example configuration for `seed.config.ts` using the Prisma adapter, including importing the Prisma instance and handling database connection closure.
```typescript
import { SeedPrisma } from "@snaplet/seed/adapter-prisma";
import { defineConfig } from "@snaplet/seed/config";
// You can import the prisma instance from your own code like you would
// in your backend code
import { db } from "./src/utils/db";
export default defineConfig({
adapter: () => new SeedPrisma(db),
});
// at the end of seed.ts
process.exit(0);
```
--------------------------------
### Create a Seed Script for Prisma
Source: https://snaplet-seed.netlify.app/seed/integrations/prisma
Provides an example seed script (`seed.ts`) that uses the Seed client to reset the database and then seed it with a specified number of users.
```typescript
import { createSeedClient } from "@snaplet/seed";
const seed = await createSeedClient();
// Truncate all tables in the database
await seed.$resetDatabase();
// Seed the database with 10 users
await seed.user((x) => x(10));
process.exit();
```
--------------------------------
### Snaplet Seed Configuration (New API)
Source: https://snaplet-seed.netlify.app/seed/migrations
Example of a seed.config.ts file using the new @snaplet/seed API. It defines the data generation logic within the 'run' function, directly using the snaplet client.
```typescript
///
import { defineConfig } from 'snaplet';
export default defineConfig({
generate: {
alias: {
inflection: true,
},
async run(snaplet) {
await snaplet.users((x) => x(3, () => ({
posts: (x) => x(10),
}))),
},
},
});
```
--------------------------------
### Generate Supabase Seed Script
Source: https://snaplet-seed.netlify.app/seed/integrations/supabase
Pipe the output of the Snaplet Seed execution (with dry run enabled) to a `supabase/seed.sql` file. This script can then be applied to your local Supabase database.
```bash
npx tsx seed.ts > supabase/seed.sql
```
--------------------------------
### Use Store Parameters in Snaplet Generate and Connect
Source: https://snaplet-seed.netlify.app/seed/release-notes-archive
Provides `store` and `$store` parameters for Snaplet's generate and connect functions. `store` gives access to models created within the current plan, while `$store` provides access to all models created in the Snaplet instance so far, aiding in relational data setup.
```typescript
// generate function
await snaplet.customers([{
email: ({ store, $store }) => /* ... */
}])
// connect function
await snaplet.reservations([{
customer: ({ store, $store }) => /* ... */,
}]);
```
--------------------------------
### Configure Options for Snaplet Pipe and Merge (JavaScript)
Source: https://snaplet-seed.netlify.app/seed/release-notes-archive
Demonstrates how to provide options to Snaplet's 'pipe' and 'merge' operators. This example shows passing an options object to '$merge' to configure model-specific data, such as setting a title for all posts in the merged plans.
```javascript
snaplet.$merge([/* ... plans */], {
models: {
Post: {
data: {
// This title will be used for all plans
// being combined by this merge
title: 'A title for posts in the merged plans';
}
}
}
});
```
--------------------------------
### Sync Snaplet Seed Client with Database
Source: https://snaplet-seed.netlify.app/seed/integrations/supabase
Execute the Snaplet Seed sync command to regenerate the client and ensure it reflects the latest database structure after migrations or schema changes.
```bash
npx @snaplet/seed sync
```
--------------------------------
### Seed Posts Linked to Supabase Profiles
Source: https://snaplet-seed.netlify.app/seed/recipes/data-pools-connection
This example shows how to seed users into Supabase, enrich their data, and link new posts to these profiles using `@snaplet/seed` and Supabase client. It includes resetting the database, creating new users via Supabase auth, retrieving profile IDs, and then seeding posts connected to these profiles.
```javascript
import { createSeedClient } from "@snaplet/seed";
import { createClient } from '@supabase/supabase-js';
const supabase = createClient(
process.env.NEXT_PUBLIC_SUPABASE_URL,
process.env.NEXT_PUBLIC_SUPABASE_ROLE_KEY
);
const PASSWORD = "testuser";
const seed = await createSeedClient();
// Reset our database to start from a clean state
await seed.$resetDatabase();
// Creating a pool of users with common attributes
for (let i = 0; i < 5; i++) {
await supabase.auth.signUp({
email: `user${i}@example.com`,
password: PASSWORD,
options: { data: { user_name: `user${i}` } }
});
}
// Retrieving profiles for linking with new data
const { data: profiles } = await supabase.from("profiles").select("id");
// Linking new posts to these profiles
await seed.posts(x => x(10), { connect: { profiles } });
```
--------------------------------
### Snaplet Seed Script with Dry Run Option
Source: https://snaplet-seed.netlify.app/seed/migrations
Example of a seed.ts file using the SnapletClient with the dryRun option. This outputs SQL queries to stdout instead of directly modifying the database.
```typescript
import { SnapletClient } from '@snaplet/seed';
const snaplet = new SnapletClient({ dryRun: true });
// With the dryRun option, the data client will output all the SQL queries to stdout.
await snaplet.users((x) => x(3, () => ({
posts: (x) => x(10),
})));
```
--------------------------------
### Snaplet Seed Configuration (Old API)
Source: https://snaplet-seed.netlify.app/seed/migrations
Example of a seed.config.ts file using the older Snaplet API (pre-0.66.0). It defines the data generation plan using the 'plan' function and specific utilities like 'count' and 'data'.
```typescript
///
import { defineConfig } from 'snaplet';
export default defineConfig({
generate: {
plan({ snaplet }) {
return snaplet.User({
count: 3,
data: {
email: ({ seed }) =>
copycat.email(seed),
Post: {
count: 10,
}
}
}),
},
},
});
```
--------------------------------
### Connect Descendant Models in Snaplet Seed
Source: https://snaplet-seed.netlify.app/seed/release-notes-archive
This example shows how Snaplet Seed automatically connects descendant models in the same plan, simplifying the seeding process. It illustrates the previous manual connection method and the new, streamlined approach.
```typescript
await snaplet.boards([
{
name: 'Snaplet',
columns: [{
items: [{
name: 'TODO',
// no need to connect board manually!
}]
}]
}
])
```
--------------------------------
### Configure Groq API Key for Seed CLI
Source: https://snaplet-seed.netlify.app/seed/reference/environment-variables
Set the GROQ_API_KEY environment variable to allow the Seed CLI to generate examples using Groq models. This is crucial for text-based entry generation with Groq.
```shell
export GROQ_API_KEY='your-groq-api-key'
```
--------------------------------
### Configure OpenAI API Key for Seed CLI
Source: https://snaplet-seed.netlify.app/seed/reference/environment-variables
Set the OPENAI_API_KEY environment variable to enable the Seed CLI to generate examples using OpenAI models. This is essential for text-based entry generation.
```shell
export OPENAI_API_KEY='your-openai-api-key'
```
--------------------------------
### Define Database Schema for Snaplet Seed Example
Source: https://snaplet-seed.netlify.app/seed/release-notes-archive
This SQL code defines the `board`, `column`, and `item` tables used in the Snaplet Seed documentation to illustrate automatic descendant model connection. It includes primary keys and foreign key constraints.
```sql
create table board (
id uuid not null primary key,
name text not null
);
create table "column" (
id uuid not null primary key,
name text not null,
board_id uuid not null references board(id)
);
create table item (
id uuid not null primary key,
name text not null,
column_id uuid not null references "column"(id),
board_id uuid not null references board(id)
);
```
--------------------------------
### Specify AI Model Name for Seed CLI
Source: https://snaplet-seed.netlify.app/seed/reference/environment-variables
Use the AI_MODEL_NAME environment variable to specify which AI model the Seed CLI should use for generating examples. You can list multiple models, separated by commas.
```shell
export AI_MODEL_NAME='gpt-4-mini,llama-3.1-8b-instant'
```
--------------------------------
### Update Snaplet Pipe and Merge Operators (JavaScript)
Source: https://snaplet-seed.netlify.app/seed/release-notes-archive
Shows the updated signature for Snaplet's 'pipe' and 'merge' operators, which now accept an array of plans instead of using variadic arguments. This includes examples of both the previous and the new syntax for chaining and merging plans.
```javascript
// previously
snaplet.$pipe(snaplet.User({}), snaplet.Post({}));
snaplet.$merge(snaplet.User({}), snaplet.Post({}));
snaplet.User({}).pipe(snaplet.Post({}));
snaplet.User({}).merge(snaplet.Post({}));
// from 0.68.1 onwards
snaplet.$pipe([snaplet.User({}), snaplet.Post({})]);
snaplet.$merge([snaplet.User({}), snaplet.Post({}))
snaplet.User({}).pipe([snaplet.Post({})]);
snaplet.User({}).merge([snaplet.Post({})]);
```
--------------------------------
### Initialize Snaplet Seed Project
Source: https://snaplet-seed.netlify.app/seed/release-notes-archive
Initializes a new Snaplet Seed project. This command can be run in a custom directory to specify the project's location.
```bash
npx @snaplet/seed init
# it will initialize the project in the ./prisma/seed directory
npx @snaplet/seed init prisma/seed
```
--------------------------------
### Configure Snaplet Seed for Supabase
Source: https://snaplet-seed.netlify.app/seed/integrations/supabase
Configure the `seed.config.ts` file to connect to your Supabase local development database and specify which schemas and tables Snaplet Seed should manage. This example configures the connection to a local Supabase instance and selects tables from the 'public' and 'auth' schemas.
```typescript
import { SeedPostgres } from "@snaplet/seed/adapter-postgres";
import { defineConfig } from "@snaplet/seed/config";
import postgres from "postgres";
export default defineConfig({
adapter: () => {
const client = postgres("postgresql://postgres:postgres@127.0.0.1:54322/postgresql");
return new SeedPostgres(client);
},
select: [
// We don't alter any extensions tables that might be owned by extensions
"!*",
// We want to alter all the tables under public schema
"public*",
// We also want to alter some of the tables under the auth schema
"auth.users",
"auth.identities",
"auth.sessions",
]
});
```
--------------------------------
### Create Seed Client Instance
Source: https://snaplet-seed.netlify.app/seed/core-concepts
Demonstrates how to create a new instance of the Seed Client. This is the primary entry point for interacting with the Seed Client API.
```javascript
import { createSeedClient } from "@snaplet/seed";
const seed = await createSeedClient();
```
--------------------------------
### Example of Triggering a Unique Constraint Error
Source: https://snaplet-seed.netlify.app/seed/recipes/unique-constraints
A basic example showing how attempting to create multiple users with the same static email address will trigger a unique constraint error.
```typescript
import { createSeedClient } from "@snaplet/seed";
const seed = await createSeedClient();
await seed.$resetDatabase();
const user = await seed.User((x) => x(2, () => ({ email: 'a-static-user-email@gmail.com' })));
```
--------------------------------
### Generate Seed Client Assets
Source: https://snaplet-seed.netlify.app/seed/reference/cli
Generates the necessary assets for the Seed Client. This command prepares the client for use with your database.
```bash
npx @snaplet/seed generate
```
--------------------------------
### Explicitly Provided User Name
Source: https://snaplet-seed.netlify.app/seed/release-notes-archive
Example of providing a name explicitly when generating user data with `@snaplet/seed`. This value will not change after an upgrade.
```typescript
snaplet.users({ name: 'Garnet Harley' })
```
--------------------------------
### Generate Assets with Copycat Next
Source: https://snaplet-seed.netlify.app/seed/release-notes-archive
Command to regenerate assets using the next version of `@snaplet/copycat`. This allows previewing upcoming breaking changes in copycat.
```bash
npx snaplet generate --copycat-next
```
--------------------------------
### Generate Data Client with Snaplet CLI
Source: https://snaplet-seed.netlify.app/seed/migrations
Runs the Snaplet CLI command to generate the data client based on the database schema. This creates source code in node_modules/.snaplet.
```bash
npx snaplet generate
```
--------------------------------
### Refined $resetDatabase Usage in Snaplet Seed
Source: https://snaplet-seed.netlify.app/seed/migrations
Example of using the `$resetDatabase` method with Snaplet Seed to reset the database, optionally excluding specific tables.
```typescript
import { createSeedClient } from "@snaplet/seed";
const seed = await createSeedClient();
await seed.$resetDatabase(); // Resets, respecting exclusions from config
// Example usage in tests
test('your_test', () => {...});
test('another_test', async () => {
await seed.$resetDatabase([
'!public.users', // Keeps user data intact
]);
});
```
--------------------------------
### Using the x Helper Function for Child Fields
Source: https://snaplet-seed.netlify.app/seed/migrations
Demonstrates the updated `x` helper function, which now supports static data and provides context (index, seed) for generating child fields.
```javascript
await seed.posts(x => x(3, (ctx) => ({
title: `Post #${ctx.index}`,
content: `This post's seed is ${ctx.seed}`
})));
await seed.posts(x => x(3, {
title: 'Static post',
content: (ctx) => copycat.paragraph(ctx.seed)
}));
```
--------------------------------
### Selective Table Syncing with Glob Patterns in Snaplet Seed
Source: https://snaplet-seed.netlify.app/seed/migrations
Example configuration for `seed.config.ts` using the `select` option with glob patterns to include or exclude tables during syncing.
```typescript
export default defineConfig({
select: [
'!some_schema_name*', // Exclude all tables under a schema
'!public._*', // Exclude all tables prefixed by _ in the schema public
'public._specific_table', // include a specific table even with the prefix
]
});
```
--------------------------------
### Initialize Seed CLI
Source: https://snaplet-seed.netlify.app/seed/reference/cli
Initializes Seed locally for your project. Can be used in the current directory or a specific directory path. If a specific directory is used, the --config option must be specified in other commands.
```bash
npx @snaplet/seed init
```
```bash
npx @snaplet/seed init prisma/seed
```
--------------------------------
### Implicitly Generated User Name
Source: https://snaplet-seed.netlify.app/seed/release-notes-archive
Example of not providing a name when generating user data with `@snaplet/seed`. The generated value might change after the first `snaplet generate` run following an upgrade.
```typescript
snaplet.users({})
```
--------------------------------
### Stateful Snaplet Client Usage
Source: https://snaplet-seed.netlify.app/seed/release-notes-archive
Illustrates the use of a stateful SnapletClient to execute multiple plans generating different data, and how to reset the client's state.
```javascript
await snaplet.users((x) => x(2));
await snaplet.users((x) => x(2));
// Clear the state of the client
await snaplet.$reset()
```
--------------------------------
### Automate Seed Sync with Post-Migration Script
Source: https://snaplet-seed.netlify.app/seed/integrations/prisma
Adds a `postmigrate` script to `package.json` to automatically run `npx @snaplet/seed sync` after `prisma migrate dev`.
```json
{
"scripts": {
"migrate": "prisma migrate dev",
"postmigrate": "npx @snaplet/seed sync"
}
}
```
--------------------------------
### Snaplet: Stateful Client - Resetting State
Source: https://snaplet-seed.netlify.app/seed/migrations
Illustrates how to reset the state of the data client using the `$reset` function. This is useful for clearing the global store and starting fresh, particularly in testing scenarios.
```typescript
await snaplet.users([{}]);
snaplet.$reset();
```
--------------------------------
### Seed Posts with Existing Users and Files using Prisma
Source: https://snaplet-seed.netlify.app/seed/recipes/data-pools-connection
This snippet demonstrates how to seed new posts and link them to existing users and files in a database using `@snaplet/seed` and Prisma. It first retrieves existing user and file IDs and then uses the `connect` option to establish relationships during seeding, while also resetting specific tables.
```typescript
import { PrismaClient } from "@prisma/client";
import { createSeedClient } from "@snaplet/seed";
const prisma = new PrismaClient();
const users = await prisma.user.findMany({ select: { id: true } });
const files = await prisma.file.findMany({ select: { id: true } });
const seed = await createSeedClient();
// Resetting specific tables while preserving users and files
await seed.$resetDatabase(["!*_prisma_migrations", "!*user", "!*file"]);
// Seeding new posts and linking them to existing users and files
await seed.posts(x => x(10, { Attachments: [{}, {}, {}] }), { connect: { users, files } });
```
--------------------------------
### Connect Posts to Seeded Users
Source: https://snaplet-seed.netlify.app/seed/core-concepts
Demonstrates seeding 10 posts and connecting them to 2 previously seeded users using the `connect: true` option.
```javascript
await seed.users((x) => x(2));
await seed.posts((x) => x(10), {
connect: true,
});
```
--------------------------------
### Async Client Creation with createSeedClient
Source: https://snaplet-seed.netlify.app/seed/migrations
Illustrates the change in client instantiation from a synchronous `SnapletClient` class to an asynchronous `createSeedClient` function. This change is necessary to scan the database at instantiation time for sequence values.
```javascript
// before
import { SnapletClient } from '@snaplet/seed'
const snaplet = new SnapletClient({ /* options */ })
// after
import { createSeedClient } from '@snaplet/seed'
const seed = await createSeedClient({ /* options */ })
```
--------------------------------
### Configure Postgres.js Adapter for Snaplet Seed
Source: https://snaplet-seed.netlify.app/seed/reference/adapters
This configuration sets up the Postgres.js adapter for Snaplet Seed. It requires importing `SeedPostgres` and `defineConfig`, and uses the `postgres` library to establish a database connection via `process.env.DATABASE_URL`.
```typescript
import { SeedPostgres } from "@snaplet/seed/adapter-postgres";
import { defineConfig } from "@snaplet/seed/config";
import postgres from "postgres";
export default defineConfig({
adapter: () => {
const client = postgres(process.env.DATABASE_URL);
return new SeedPostgres(client);
},
});
```
--------------------------------
### Generate Assets with Default Copycat
Source: https://snaplet-seed.netlify.app/seed/release-notes-archive
Command to regenerate assets using the default version of `@snaplet/copycat`. This is used to switch back if previously using `--copycat-next`.
```bash
npx snaplet generate
```
--------------------------------
### Enable Dry Run for Supabase Seeding
Source: https://snaplet-seed.netlify.app/seed/integrations/supabase
Utilize the `dryRun: true` option when creating the Snaplet Seed client to generate SQL queries without executing them. This is useful for integrating with Supabase's seeding workflow.
```typescript
import { createSeedClient } from "@snaplet/seed";
const seed = await createSeedClient({ dryRun: true });
```
--------------------------------
### Generate Workspace Data with User Connections
Source: https://snaplet-seed.netlify.app/seed/recipes/relationships
This snippet demonstrates how to generate a pool of users and then create workspaces, connecting them to the user pool. It further illustrates creating channels within workspaces, assigning members to channels, and generating threads and messages, all while maintaining relationships defined by plan connections.
```javascript
// Create a pool of between 2 and 10 users for our workspace
const { users } = await seed.users((x) => x({min: 2, max: 10}));
const workspacesNumber = 1;
// Create our workspace and connect all our users to it
const { workspace, workspace_member } = await seed.workspace((x) =>
x(workspacesNumber, () => ({
// Each workspace will have between 1 and 10 members
workspace_member: (x) => x(users.length)
}),
// Connect the workspace members to the pool of users we created
{ connect: { users }})
);
// Use the workspace and workspace_member objects
// to create more complex relationships
for (const w of workspace) {
// Retrieve all members for this specific workspace
const workspace_members = workspace_member
.filter((m) => m.workspace_id === w.id);
const channel_users = copycat
// Pick some of the workspace members
// to be channel members
.someOf(w.id, [1, workspace_members.length], workspace_members)
.map((m) => ({ id: m.user_id }));
// Create between 1 and 10 channels for this workspace
await seed.channel((x) => x({ min: 1, max: 10 }, () => ({
// Add all channel users as members of the current channel
channel_member: (x) => x(channel_users.length),
// Create between 1 and 10 threads for each channel
channel_thread: (x) => x({ min: 1, max: 10 }, ({
// Create between 0 and 10 messages for each thread
channel_thread_message: (x) => x({ min: 0, max: 10 })
}))
}), {
connect: {
// Connect all channels to the current workspace
workspace: [w],
// Connect all channel users to the pool of users for this channel
users: channel_users
}
});
}
```
--------------------------------
### Seed Posts with Callback Input
Source: https://snaplet-seed.netlify.app/seed/core-concepts
Shows how to seed posts using a callback function that receives the plan's context and returns the post data, including dynamic content based on the context's index.
```javascript
await seed.posts([
(ctx) => ({ title: `Hello, world #${ctx.index}!` }),
]);
```
--------------------------------
### Link Local Directory to Snaplet Project
Source: https://snaplet-seed.netlify.app/seed/reference/cli
Links your local directory to a Snaplet Project. This establishes a connection between your local development environment and your Snaplet project.
```bash
npx @snaplet/seed link
```
--------------------------------
### Configure Snaplet to Use Database-Generated IDs
Source: https://snaplet-seed.netlify.app/seed/recipes/contraints-and-defaults
This example shows how to configure Snaplet to use database functions for generating default values, specifically for IDs. It involves creating a Prisma client, defining a function to fetch a database-generated ID, and then passing this function to the Snaplet seed configuration.
```typescript
import { createSeedClient } from "@snaplet/seed";
import { PrismaClient } from "@prisma/client";
// Get a database client
const client = new PrismaClient();
async function getDatabaseGeneratedId() {
// Use the client to call our internal function
const res = (
await client.$queryRawUnsafe
) <
{ id: string } >
`SELECT generate_random_id(12) as id`;
return res[0]["id"];
}
const seed = await createSeedClient({
models: {
post: {
data: {
id: getDatabaseGeneratedId,
},
},
},
});
```
--------------------------------
### Generate Posts with Seed Client
Source: https://snaplet-seed.netlify.app/seed/getting-started/overview
Demonstrates how to generate a specified number of posts using the Seed Client's data generation capabilities. This leverages TypeScript for type safety and auto-completion.
```TypeScript
await seed.posts((x) => x(5))
```
--------------------------------
### Assign Specific Roles using Field Connections
Source: https://snaplet-seed.netlify.app/seed/recipes/relationships
This example shows how to use field connections to assign specific roles to workspace members. It first defines 'admin' and 'member' user types and then, during workspace member creation, uses the 'index' to assign the 'admin' role to the first member and 'member' roles to the rest.
```javascript
const { workspace_user_type } = await baseClient.workspace_user_type([
{ type: "admin" },
{ type: "member" }
]);
const seed = await createSeedClient({
connect: {
workspace_user_type
}
});
const { users } = await seed.users((x) => x({ min: 2, max: 10 }));
const { workspace, workspace_member } = await seed.workspace((x) =>
x(3, () => ({
workspace_member: (x) => x(users.length, ({ index }) => {
// Make the first member an admin and the rest members
const wtype = index === 0
? workspace_user_type.find((wut) => wut.type === "admin")
: workspace_user_type.find((wut) => wut.type === "member");
return {
workspace_user_type: (ctx) => ctx.connect(wtype!)
};
})
}),
{ connect: { users }})
);
```
--------------------------------
### Configure Snaplet Seed with Postgres Adapter
Source: https://snaplet-seed.netlify.app/seed/reference/configuration
Sets up the Snaplet Seed configuration to use the PostgreSQL adapter. It initializes a `postgres` client with a database URL from environment variables and passes it to `SeedPostgres`.
```typescript
import { SeedPostgres } from "@snaplet/seed/adapter-postgres";
import { defineConfig } from "@snaplet/seed/config";
import postgres from "postgres";
export default defineConfig({
adapter: () => {
const client = postgres(process.env.DATABASE_URL);
return new SeedPostgres(client);
},
});
```
--------------------------------
### Configure Database Adapters in seed.config.ts
Source: https://snaplet-seed.netlify.app/seed/release-notes-archive
Demonstrates how to configure database adapters like Prisma, pg, postgres-js, and betterSqlite3 using the new `adapter` parameter in `seed.config.ts`.
```typescript
// seed.config.ts
export default {
adapter: 'prisma' // or 'pg', 'postgres-js', 'better-sqlite3'
// ... other configurations
};
```
--------------------------------
### Create Snaplet Seed Client Asynchronously
Source: https://snaplet-seed.netlify.app/seed/release-notes-archive
Shows the updated method for creating a Snaplet Seed client, which is now an asynchronous operation requiring `await`.
```JavaScript
import { createSeedClient } from '@snaplet/seed'
const seed = await createSeedClient({ /* options */ })
```
--------------------------------
### Snaplet Generate with Consistent Seeding (JavaScript)
Source: https://snaplet-seed.netlify.app/seed/release-notes-archive
Illustrates Snaplet's improved seeding strategy for the 'generate' feature. It shows how the same ID would be returned for different users before the fix and explains that the new approach produces a hash based on inputs to 'snaplet.(inputs)' for more predictable output.
```javascript
await snaplet.User({ email: 'alice@acme.com' });
await snaplet.User({ email: 'bob@acme.com' });
```
--------------------------------
### Use Seed CLI with Config
Source: https://snaplet-seed.netlify.app/seed/reference/cli
Applies a configuration file to Seed CLI commands. This allows for custom configurations for operations like syncing.
```bash
npx @snaplet/seed --config prisma/seed/seed.config.ts sync
```
--------------------------------
### Create Seed Client with Global Connect
Source: https://snaplet-seed.netlify.app/seed/release-notes-archive
Creates a Seed Client instance with a global connect strategy, allowing all generated data to be automatically connected to the global store. This is demonstrated by connecting posts to previously created users.
```typescript
const seed = await createSeedClient({ connect: true })
await seed.users(x => x(2))
// all the posts will be connected to the previously created users in the seed.$store
await seed.posts(x => x(2))
```
--------------------------------
### Integrate Seed Script with Prisma Seeding
Source: https://snaplet-seed.netlify.app/seed/integrations/prisma
Configures the `package.json` file to execute the Snaplet Seed script when Prisma seeding commands are run, ensuring data is seeded automatically.
```json
{
"prisma": {
"seed": "npx tsx prisma/seed/seed.ts"
}
}
```
--------------------------------
### Configure better-sqlite3 Adapter for Snaplet Seed
Source: https://snaplet-seed.netlify.app/seed/reference/adapters
This configuration sets up the better-sqlite3 adapter for Snaplet Seed. It involves importing `SeedBetterSqlite3` and `defineConfig`, and creating a `better-sqlite3` database instance connected to 'sqlite.db'.
```typescript
import { SeedBetterSqlite3 } from "@snaplet/seed/adapter-better-sqlite3";
import { defineConfig } from "@snaplet/seed/config";
import Database from "better-sqlite3";
export default defineConfig({
adapter: () => {
const client = new Database('sqlite.db');
return new SeedBetterSqlite3(client);
},
});
```
--------------------------------
### Snaplet Local and Global Stores
Source: https://snaplet-seed.netlify.app/seed/release-notes-archive
Shows how to retrieve data produced by a plan as a local store and access the global store containing all generated data.
```javascript
const usersStore = await snaplet.users((x) => x(2))
// { users: [user, user] }
console.log(usersStore)
// Access the global store
console.log(snaplet.$store)
// Reset the global store state
snaplet.$reset()
```
--------------------------------
### Snaplet Fingerprint Command
Source: https://snaplet-seed.netlify.app/seed/release-notes-archive
Command to inspect a database URL and collect statistical details for more realistic data generation with `@snaplet/seed`.
```bash
snaplet fingerprint
```
--------------------------------
### Configure Snaplet Seed with package.json
Source: https://snaplet-seed.netlify.app/seed/release-notes
If you use a custom configuration path for Snaplet Seed, such as `prisma/seed/seed.config.ts`, you can save this path in your `package.json`. This eliminates the need to use the `--config` option for every CLI command. Refer to the Configuration Reference for more details.
```json
{
"snaplet": {
"configPath": "prisma/seed/seed.config.ts"
}
}
```
--------------------------------
### Configure mysql2 Adapter for Snaplet Seed
Source: https://snaplet-seed.netlify.app/seed/reference/adapters
This snippet shows the configuration for the mysql2 adapter in Snaplet Seed, currently in alpha. It uses `mysql2/promise` to create a connection via `process.env.DATABASE_URL` and initializes `SeedMysql2`.
```typescript
import { SeedMysql2 } from "@snaplet/seed/adapter-mysql2";
import { defineConfig } from "@snaplet/seed/config";
import { createConnection } from "mysql2/promise";
export default defineConfig({
adapter: async () => {
const client = await createConnection(process.env.DATABASE_URL);
await client.connect();
return new SeedMysql2(client);
},
});
```
--------------------------------
### Login to Snaplet Account
Source: https://snaplet-seed.netlify.app/seed/reference/cli
Logs into your Snaplet account. Supports interactive login or login using a Snaplet Cloud access token obtained from the Snaplet website.
```bash
npx @snaplet/seed login
```
```bash
npx @snaplet/seed login --access-token
```
--------------------------------
### Configure node-postgres Adapter for Snaplet Seed
Source: https://snaplet-seed.netlify.app/seed/reference/adapters
This snippet demonstrates configuring the node-postgres adapter for Snaplet Seed. It uses the `pg` library's `Client` to connect to the database using `process.env.DATABASE_URL` and enables inflection.
```typescript
import { SeedPg } from "@snaplet/seed/adapter-pg";
import { defineConfig } from "@snaplet/seed/config";
import { Client } from "pg";
export default defineConfig({
alias: {
inflection: true,
},
adapter: async () => {
const client = new Client({ connectionString: process.env.DATABASE_URL });
await client.connect();
return new SeedPg(client);
},
});
```
--------------------------------
### Define Snaplet Seed Configuration with defineConfig
Source: https://snaplet-seed.netlify.app/seed/reference/configuration
Demonstrates how to use the `defineConfig` helper in `seed.client.ts` to define Snaplet Seed configuration options, providing Intellisense for available settings.
```typescript
import { defineConfig } from "@snaplet/seed/config";
export default defineConfig({
// your configuration options here...
});
```
--------------------------------
### Snaplet: Stateful Client - Creating New Client Instance
Source: https://snaplet-seed.netlify.app/seed/migrations
Demonstrates how to obtain a new instance of the data client with a reset state using the `$transaction` function. This is beneficial for isolating test cases and ensuring a clean state for each test.
```typescript
await snaplet.$transaction(async (snaplet) => {
await snaplet.users([{}]);
});
```
--------------------------------
### Snaplet Auto-Connection with External Store
Source: https://snaplet-seed.netlify.app/seed/release-notes-archive
Shows how to use the `connect` option with an external store to connect generated data to specific data.
```javascript
const externalStore = { users: [{ id: 42 }, { id: 5432 }] };
await snaplet.posts(x => x(3), { connect: externalStore });
```
--------------------------------
### Snaplet: Fine-grained Connections - Shorthand
Source: https://snaplet-seed.netlify.app/seed/migrations
Demonstrates the shorthand `connect: true` for connecting generated data to the global store. This is used when linking related data, such as posts to users, without explicitly passing the store.
```typescript
await snaplet.users(x => x(3));
// it will connect the authors of the posts to the previously generated users
await snaplet.posts(x => x(3), { connect: true });
```
--------------------------------
### Snaplet: Fine-grained Connections - Custom Store
Source: https://snaplet-seed.netlify.app/seed/migrations
Shows how to use a custom store with the `connect` option to link generated data to specific existing data. This provides flexibility when the target data is not in the global store.
```typescript
// it will connect the authors of the posts to one of these users
const externalStore = { users: [{ id: 42 }, { id: 5432 }]} };
await snaplet.posts(x => x(3), { connect: externalStore });
```
--------------------------------
### Configure Snaplet Seed Adapter
Source: https://snaplet-seed.netlify.app/seed/release-notes-archive
Defines the adapter for generating the Snaplet Seed Client. The adapter is persisted in the `.snaplet/config.json` file. Possible values include 'prisma', 'postgres', 'pg', 'better-sqlite3', and 'mysql2'.
```json
{
// possible values: "prisma" | "postgres" | "pg" | "better-sqlite3" | "mysql2"
"adapter": "prisma"
}
```
--------------------------------
### Snaplet Auto-Connection with Global Store
Source: https://snaplet-seed.netlify.app/seed/release-notes-archive
Demonstrates the new `connect: true` option for automatically connecting generated data to existing data in the global store.
```javascript
await snaplet.organizations(x => x(2));
// the 10 users will be automatically connected to one of the 2 previously generated organizations contained in snaplet.$store
snaplet.users(x => x(10), { connect: true });
```