- Introduced backend patterns skill with guidelines on API design, database optimization, and server-side best practices. - Added coding standards skill outlining universal coding principles for TypeScript, NestJS, and Node.js development. - Implemented continuous learning skill to automatically extract reusable patterns from Cursor sessions. - Created NestJS best practices skill detailing architecture patterns, dependency injection, error handling, and security measures. - Included various rules and templates for NestJS best practices to ensure production-ready applications.
62 lines
1.6 KiB
Markdown
62 lines
1.6 KiB
Markdown
---
|
|
title: Use Database Migrations
|
|
impact: HIGH
|
|
impactDescription: Enables safe, repeatable database schema changes
|
|
tags: database, migrations, drizzle, schema
|
|
---
|
|
|
|
## Use Database Migrations
|
|
|
|
Never push schema changes with `drizzle-kit push` in production. Use versioned SQL migrations for all schema changes. Migrations provide version control for your database, enable safe rollbacks, and ensure consistency across all environments.
|
|
|
|
**Incorrect (pushing schema or running ad-hoc SQL):**
|
|
|
|
```typescript
|
|
// drizzle-kit push against production
|
|
// Mutates the live database with no rollback file
|
|
|
|
@Injectable()
|
|
export class DatabaseService {
|
|
async addColumn(): Promise<void> {
|
|
await this.db.execute(sql`ALTER TABLE users ADD COLUMN age INT`);
|
|
}
|
|
}
|
|
```
|
|
|
|
**Correct (generate and apply Drizzle migrations):**
|
|
|
|
```typescript
|
|
// drizzle.config.ts
|
|
import { defineConfig } from 'drizzle-kit';
|
|
|
|
export default defineConfig({
|
|
schema: './drizzle/schema.ts',
|
|
out: './drizzle/migrations',
|
|
dialect: 'postgresql',
|
|
dbCredentials: {
|
|
url: process.env.DATABASE_URL!,
|
|
},
|
|
});
|
|
```
|
|
|
|
```bash
|
|
# Generate a migration from schema diffs
|
|
npx drizzle-kit generate
|
|
|
|
# Apply migrations
|
|
npx drizzle-kit migrate
|
|
```
|
|
|
|
```typescript
|
|
// drizzle/schema.ts
|
|
export const users = pgTable('users', {
|
|
id: uuid('id').primaryKey().defaultRandom(),
|
|
email: varchar('email', { length: 255 }).notNull(),
|
|
age: integer('age').default(0),
|
|
});
|
|
```
|
|
|
|
Always keep `down`/rollback SQL when a migration is destructive. Never edit an already-applied migration file; add a new one.
|
|
|
|
Reference: [Drizzle Kit Migrations](https://orm.drizzle.team/docs/kit-overview)
|