Schema and migrations
Configure Drizzle Kit
Point Drizzle Kit at the schema, migration directory, SQLite dialect, and database without leaking credentials into version control.
Drizzle is two tools. Drizzle ORM runs queries inside your application. Drizzle Kit is a command-line tool that reads your schema, compares it with what it saw last time, and writes migration files. Kit needs its own configuration, because it runs outside your app.
Create drizzle.config.ts in the project root:
import 'dotenv/config'
import { defineConfig } from 'drizzle-kit'
export default defineConfig({
schema: './src/db/schema.ts',
out: './drizzle',
dialect: 'sqlite',
dbCredentials: {
url: process.env.DB_FILE_NAME!,
},
})
Four settings. schema is the file with our tables. out is where migration files go. dialect tells Kit which flavor of SQL to write. dbCredentials.url is the database to apply migrations to, and for SQLite that’s just the filename.
Notice we read the same DB_FILE_NAME variable the application uses. One variable, one database. If the two ever pointed at different files, you’d migrate one and query the other, and nothing would make sense.
Commit the config, not the secrets
drizzle.config.ts goes in Git. It contains no secrets, only the variable name. The .env file with the real value stays out, as we set up in the second lesson.
With SQLite the “credential” is a harmless filename. With PostgreSQL it’s a connection string with a password. The habit is the same, so build it now while the stakes are low.
About that exclamation mark
process.env.DB_FILE_NAME! tells TypeScript to trust the value exists. Kit fails with an error if it’s actually missing, so nothing dangerous happens, but the error won’t say why. If several people or environments share the project, add the same explicit check we used in src/db/index.ts. A message like DB_FILE_NAME is required beats a stack trace from inside the tool.
Check it works
Run any Kit command and watch the first lines:
npx drizzle-kit generate
No config path provided, using default 'drizzle.config.ts'
Reading config file '/Users/flavio/drizzle-notes/drizzle.config.ts'
If Kit finds the config and the schema, it proceeds. Mistype the schema path and you get No schema files found for path config ['./src/db/schem.ts']. Leave DB_FILE_NAME empty and generate still works, because it only reads the schema, but migrate stops with Please provide required params: [x] url: '', because it needs the database. Knowing which failure belongs to which setting saves a lot of head-scratching later.
Other databases
For PostgreSQL, dialect becomes 'postgresql' and url becomes a connection string. The schema also changes: pgTable and PostgreSQL column types instead of sqliteTable, int, and text. The workflow is the same, the code is not identical. We come back to this in the last lesson.
Lesson completed