Apply migrations at runtime with migrate function
To apply migrations during runtime, use the `migrate` function from your driver package. For better-sqlite3: `import { migrate } from 'drizzle-orm/better-sqlite3/migrator'; await migrate(db);`. This reads migration files, fetches migration history from the database, picks previously unapplied migrations, and applies new migrations.
Database first approach with drizzle-kit pull
In the database first approach, your database schema is the source of truth. Use the `drizzle-kit pull` command to pull your database schema and generate a TypeScript Drizzle schema file.
Generate SQL migrations with drizzle-kit generate
Use `drizzle-kit generate` to generate SQL migration files based on schema changes. The command reads previous migration folders, finds diffs between current and previous schemas, prompts for renames if necessary, and generates SQL migration files persisted to a timestamped folder with migration.sql and snapshot.json.
drizzle-kit export for SQL output
Use `drizzle-kit export` to output the SQL representation of your Drizzle schema to the console. Read your Drizzle schema, generate SQL representation, and output to console for use with external migration tools like Atlas.
Relational Queries v2: migrating relations with drizzle-kit pull step 3
Step 3 of migrating to v2 using drizzle-kit pull: Update the drizzle database instance initialization from const db = drizzle(url, { schema }) to const db = drizzle(url, { relations }) where relations is imported from the updated relations file.
Relational Queries v2: migrating relations with drizzle-kit pull step 2
Step 2 of migrating to v2 using drizzle-kit pull: Transfer the generated relations code from drizzle/relations.ts to your project's relations file. The generated file includes 'import * as schema from './schema'' which may need to be updated if your schema tables are in multiple files.
Relational Queries v2: drizzle-kit pull generates new relations syntax
The drizzle-kit pull command in v2 supports pulling relations.ts file in the new v2 syntax. After running drizzle-kit pull, the generated drizzle/relations.ts file uses defineRelations() and should be transferred to the project's relations file.
arraySize parameter with isUnique warning
When specifying `arraySize` along with `isUnique` in generators that support both parameters, unique values are generated (not unique arrays), which are then packed into arrays.
companyName generator - company names
The `companyName` generator produces random company names. Parameters: `isUnique` (boolean, defaults to database column uniqueness), `arraySize` (number, optional).
state generator - US states
The `state` generator produces US states. It accepts only one parameter: `arraySize` (number, optional) which if specified causes states to be packed into arrays.
inet generator - IP addresses
The `inet` generator produces IP addresses based on specified parameters. Parameters: `isUnique` (boolean, defaults to database column uniqueness), `arraySize` (number, optional), `ipAddress` (string, default 'ipv4', can be 'ipv4' or 'ipv6'), `includeCidr` (boolean, default true) determining whether generated IPs include a CIDR suffix.
bitString generator - bit strings based on parameters
The `bitString` generator produces bit strings based on specified parameters. Parameters: `isUnique` (boolean, defaults to database column uniqueness), `dimensions` (number, defaults to database column bit-length) specifying desired length of each bit string (e.g., dimensions = 3 produces values like '010'), `arraySize` (number, optional).
line generator - 2D lines with a, b, c parameters
The `line` generator produces 2D lines within specified ranges for a, b, and c parameters of the line equation a*x + b*y + c = 0. Parameters: `isUnique` (boolean, defaults to database column uniqueness), `maxAValue` (number, defaults to `10 * 1000` if isUnique is false or `10 * count` if isUnique is true), `minAValue` (number, defaults to `-maxAValue`), `maxBValue` (number, defaults to `10 * 1000` if isUnique is false or `10 * count` if isUnique is true), `minBValue` (number, defaults to `-maxBValue`), `maxCValue` (number, defaults to `10 * 1000` if isUnique is false or `10 * count` if isUnique is true), `minCValue` (number, defaults to `-maxCValue`), `arraySize` (number, optional).
point generator - 2D points with x and y coordinates
The `point` generator produces 2D points within specified ranges for x and y coordinates. Parameters: `isUnique` (boolean, defaults to database column uniqueness), `maxXValue` (number, defaults to `10 * 1000` if isUnique is false or `10 * count` if isUnique is true), `minXValue` (number, defaults to `-maxXValue`), `maxYValue` (number, defaults to `10 * 1000` if isUnique is false or `10 * count` if isUnique is true), `minYValue` (number, defaults to `-maxYValue`), `arraySize` (number, optional).
loremIpsum generator - lorem ipsum text sentences
The `loremIpsum` generator produces lorem ipsum text sentences. Parameters: `sentencesCount` (number, default 1) specifying the number of sentences to generate as one value, `arraySize` (number, optional) which if specified causes generated text to be packed into arrays.
vector generator - vectors with multiple dimensions
The `vector` generator produces vectors based on provided parameters. Parameters: `isUnique` (boolean, defaults to database column uniqueness), `arraySize` (number, optional), `decimalPlaces` (number, default 2) specifying decimal places for each vector element (e.g., decimalPlaces = 3 produces values like 1.123), `dimensions` (number, defaults to database column's dimensions) specifying number of elements in each generated vector (e.g., dimensions = 3 produces values like [1,2,3]), `minValue` (number, default -1000), `maxValue` (number, default 1000).
jobTitle generator - job titles
The `jobTitle` generator produces job titles. It accepts only one parameter: `arraySize` (number, optional) which if specified causes job titles to be packed into arrays.
streetAddress generator - street addresses
The `streetAddress` generator produces street addresses. Parameters: `isUnique` (boolean, defaults to database column uniqueness), `arraySize` (number, optional).
city generator - city names
The `city` generator produces city names. Parameters: `isUnique` (boolean, defaults to database column uniqueness), `arraySize` (number, optional).
phoneNumber generator - unique phone numbers with template or prefixes
The `phoneNumber` generator produces unique phone numbers. It supports two modes: (1) Template mode with parameter `template` (string, required in this mode) where '#' symbols are substituted with generated digits; (2) Prefix mode with parameters `prefixes` (string[], not compatible with template) and `generatedDigitsNumbers` (number | number[], defaults to 7 if prefixes defined, not compatible with template). Both modes accept `arraySize` (number, optional).
email generator - unique email addresses
The `email` generator produces unique email addresses. It accepts only one parameter: `arraySize` (number, optional) which if specified causes email addresses to be packed into arrays.
fullName generator - person's full name
The `fullName` generator produces a person's full name. Parameters: `isUnique` (boolean, defaults to database column uniqueness), `arraySize` (number, optional).
lastName generator - person's last name
The `lastName` generator produces a person's last name. Parameters: `isUnique` (boolean, defaults to database column uniqueness), `arraySize` (number, optional).
firstName generator - person's first name
The `firstName` generator produces a person's first name. Parameters: `isUnique` (boolean, defaults to database column uniqueness), `arraySize` (number, optional).
uuid generator - v4 UUID strings
The `uuid` generator produces v4 UUID strings. It accepts only one parameter: `arraySize` (number, optional) which if specified causes UUIDs to be packed into arrays.
string generator - random strings
The `string` generator produces random strings. Parameters: `isUnique` (boolean, defaults to database column uniqueness), `arraySize` (number, optional).
interval generator - time intervals
The `interval` generator produces time intervals. Example of a generated value: '1 year 12 days 5 minutes'. Parameters: `isUnique` (boolean, defaults to database column uniqueness), `arraySize` (number, optional).
json generator - fixed structure JSON objects
The `json` generator produces JSON objects with a fixed structure. The JSON structure will be picked randomly from options like `{ email, name, isGraduated, hasJob, salary, startedWorking, visitedCountries }` or `{ email, name, isGraduated, hasJob, visitedCountries }`. It accepts only one parameter: `arraySize` (number, optional) which if specified causes JSON objects to be packed into arrays.
datetime generator - generates datetime objects
The `datetime` generator produces datetime objects. Parameters: `min` (string | Date, defaults to '2024-05-08' minus 2 years if max is not set, or max minus 4 years if max is set), `max` (string | Date, defaults to '2024-05-08' plus 2 years if min is not set, or min plus 4 years if min is set), `arraySize` (number, optional).
country generator - country names
The `country` generator produces country names. Parameters: `isUnique` (boolean, defaults to database column uniqueness), `arraySize` (number, optional).
timestamp generator - generates timestamps
The `timestamp` generator produces timestamp values. Parameters: `min` (string | Date, defaults to '2024-05-08' minus 2 years if max is not set, or max minus 4 years if max is set), `max` (string | Date, defaults to '2024-05-08' plus 2 years if min is not set, or min plus 4 years if min is set), `arraySize` (number, optional).
time generator - 24-hour format times
The `time` generator produces time values in 24-hour format. Parameters: `min` (string | Date, default '00:00:00.000Z'), `max` (string | Date, default '23:59:59.999Z'), `arraySize` (number, optional).
date generator - dates within range
The `date` generator produces dates within a specified range. Parameters: `minDate` (string | Date, defaults to '2024-05-08' minus 4 years if maxDate is not set, or maxDate minus 8 years if maxDate is set), `maxDate` (string | Date, defaults to '2024-05-08' plus 4 years if minDate is not set, or minDate plus 8 years if minDate is set), `arraySize` (number, optional). If only one of minDate or maxDate is provided, the other is calculated by adding or subtracting 8 years.
postcode generator - postal codes
The `postcode` generator produces postal codes. Parameters: `isUnique` (boolean, defaults to database column uniqueness), `arraySize` (number, optional).
boolean generator - true or false values
The `boolean` generator produces boolean values (true or false). It accepts only one parameter: `arraySize` (number, optional) which if specified causes booleans to be packed into arrays.
int generator - integers within range
The `int` generator produces integers within a specified range. Parameters: `isUnique` (boolean, defaults to database column uniqueness), `maxValue` (number | bigint, defaults to 1000 if isUnique is false or `count * 10` if isUnique is true), `minValue` (number | bigint, defaults to `-maxValue`), `arraySize` (number, optional).
number generator - floating point within range
The `number` generator produces floating-point numbers within a specified range. Parameters: `isUnique` (boolean, defaults to database column uniqueness), `precision` (number, default 100), `maxValue` (number, defaults to `precision * 1000` if isUnique is false or `precision * count` if isUnique is true), `minValue` (number, defaults to `-maxValue`), `arraySize` (number, optional). Precision equals 10 means one tenth accuracy (1.2, 34.6); precision equals 100 means one hundredth accuracy (1.23, 34.67).
intPrimaryKey generator - sequential integers from 1
The `intPrimaryKey` generator produces sequential integers starting from 1. It takes no parameters and is designed for auto-incrementing primary key columns.
valuesFromArray generator - picks from array
The `valuesFromArray` generator produces values from a given array. It accepts `values` (required, type `any[]` or array of weighted values `{ weight: number; values: any[] }[]`), `isUnique` (boolean, defaults to database column uniqueness), and `arraySize` (number, optional). Weighted values allow specifying probability distributions.
default generator - generates same value each time
The `default` generator produces the same given value each time it is called. It accepts two parameters: `defaultValue` (any type, required) which is the value to generate, and `arraySize` (number, optional) which if specified causes values to be packed into arrays.
year generator - YYYY format years
The `year` generator produces years in YYYY format. It accepts only one parameter: `arraySize` (number, optional) which if specified causes years to be packed into arrays.
drizzle-seed f.number() generator precision
The f.number() generator accepts minValue, maxValue, and precision parameters. The precision parameter determines the number of decimal places. Example: f.number({ minValue: 0, maxValue: 1000, precision: 100 }) generates numbers with precision up to 100.
drizzle-seed weighted random for with relationships
Use weighted random in the with property to control distribution of related entity counts. Pass an array of objects with weight and count properties, where count is an array of possible values. Example: with: { details: [{ weight: 0.6, count: [1, 2, 3] }, { weight: 0.3, count: [5, 6, 7] }] }
drizzle-seed weighted random for columns
Use f.weightedRandom() to apply weighted probability distributions to column values. It accepts an array of objects, each with weight (0-1 decimal representing probability) and value (generator function or value). Example: f.weightedRandom([{ weight: 0.3, value: f.int({ minValue: 10, maxValue: 100 }) }, { weight: 0.7, value: f.number({ minValue: 100, maxValue: 300 }) }])
drizzle-seed f.valuesFromArray() generator
The f.valuesFromArray() generator randomly selects values from a provided array. It accepts an object with a values property containing an array of possible values. Example: f.valuesFromArray({ values: ['Ms.', 'Mrs.', 'Dr.'] })
drizzle-seed f.fullName() generator
The f.fullName() generator function generates realistic full names for seeding. It takes no parameters and returns a string representing a complete name.
drizzle-seed f.int() generator function
The f.int() generator creates random integers. It accepts an object with: minValue (minimum value, inclusive), maxValue (maximum value, inclusive), and isUnique (boolean to ensure all generated values are unique). Example: f.int({ minValue: 10000, maxValue: 20000, isUnique: true })
drizzle-seed with option for relationships
The with property in refine() defines how many referenced entities to create for each parent table. Example: with: { posts: 10 } means create 10 posts for each user. The with option only works for one-to-many relationships (one parent can have many children).
drizzle-seed columns refinement options
In the refine() columns object, each key is a column name. The value can be: a generator function like f.fullName(), or false to exclude the column from seeding (allowing database defaults). Example: columns: { name: f.fullName(), age: false }
drizzle-seed refine() callback structure
The refine() method receives generator functions (f) and returns an object with table names as keys. Each table configuration can include: columns (object specifying generator functions or false to exclude), count (number of rows), and with (object specifying related entities to generate). Example: .refine((f) => ({ users: { columns: { name: f.fullName() }, count: 20, with: { posts: 10 } } }))
SQLite reset process in drizzle-seed
The drizzle-seed reset function for SQLite executes: PRAGMA foreign_keys = OFF; followed by DELETE FROM statements for each table, then PRAGMA foreign_keys = ON;. This ensures all table data is cleared without foreign key constraint violations.
Reset database with drizzle-seed for SQLite
To reset a SQLite database using drizzle-seed, import reset from 'drizzle-seed' and call await reset(db, schema) where schema contains all tables to reset. For SQLite, this disables foreign_keys pragma, generates DELETE FROM statements for all tables, then re-enables foreign_keys pragma.
drizzle-seed seed option for reproducibility
To generate a different set of values across runs, define a seed number in the seed options: await seed(db, schema, { seed: 12345 }). The same seed number will always generate the same sequence of fake data, ensuring reproducibility.
drizzle-seed count option configuration
To specify the number of rows to generate, pass count as an option: await seed(db, schema, { count: 1000 }). The count option can also be set per-table in the refine() callback, where table-level count overrides the global count.
drizzle-seed default row count
By default, the seed() function creates 10 entities per table. This can be overridden by passing { count: number } in the seed options or in the refine() configuration for individual tables.
drizzle-seed basic usage for SQLite
To seed a SQLite database with drizzle-seed, import sqliteTable and drizzle, define your table schema with columns including an auto-incrementing primary key using integer().primaryKey({ autoIncrement: true }), then call seed(db, { tableName }) inside an async function. Example: const users = sqliteTable('users', { id: integer().primaryKey({ autoIncrement: true }), name: text().notNull() }); await seed(db, { users });
drizzle-seed f.date() generator
The f.date() generator creates random dates within a specified range. It accepts minDate and maxDate as strings in YYYY-MM-DD format. Example: f.date({ minDate: '2010-12-31', maxDate: '2024-08-26' })
drizzle-seed generator functions available
drizzle-seed provides many generator functions including: fullName(), firstName(), lastName(), companyName(), jobTitle(), streetAddress(), city(), state(), country(), postcode(), phoneNumber({ template }), date({ minDate, maxDate }), loremIpsum(), int(), number({ precision }), valuesFromArray(), weightedRandom(), and default({ defaultValue }).
drizzle-seed f.phoneNumber() generator template
The f.phoneNumber() generator creates phone numbers based on a template string. Use # as a placeholder for digits. Example: f.phoneNumber({ template: '(###) ###-####' }) generates numbers like (123) 456-7890.
drizzle-seed f.default() generator
The f.default() generator returns a constant default value for a column. It accepts defaultValue as a parameter. Example: f.default({ defaultValue: 0 }) always returns 0.