Cursor Database Development: SQL, ORM, and Prisma Integration

Database development is a critical part of modern software engineering, and Cursor's AI capabilities can dramatically speed up schema design, query writing, and ORM integration. This guide covers practical workflows for SQL editing, ORM setup, migrations, and AI-assisted database optimization.
Prerequisites
Before starting:
- Cursor installed (latest version recommended)
- Database server running locally or accessible remotely (PostgreSQL, MySQL, or SQLite)
- Node.js installed (for ORM tools)
- Basic understanding of SQL and database concepts
Setting Up Database Projects in Cursor
Project Structure
Organize your database-related files for optimal AI context:
project/
prisma/
schema.prisma # Prisma schema
migrations/ # Migration files
src/
db/
connection.ts # Database connection
queries/ # Raw SQL queries
repositories/ # Data access layer
scripts/
seed.ts # Database seeding
docker-compose.yml # Local database setup
Open Project in Cursor
cd ~/my-database-project
cursor .
SQL Editing with Cursor
Writing Complex Queries
Cursor excels at generating and optimizing SQL. Use natural language prompts:
Write a PostgreSQL query to find the top 5 customers by total order value
in the last 30 days, including their name, email, and total spent.
Cursor will generate:
SELECT
c.id,
c.name,
c.email,
SUM(o.total_amount) AS total_spent
FROM customers c
JOIN orders o ON c.id = o.customer_id
WHERE o.created_at >= CURRENT_DATE - INTERVAL '30 days'
GROUP BY c.id, c.name, c.email
ORDER BY total_spent DESC
LIMIT 5;
Query Optimization
Paste a slow query and ask Cursor to optimize it:
This query is taking 3+ seconds on a table with 1M rows. Optimize it:
[paste query]
Cursor will suggest indexes, query rewrites, and explain the performance improvements.
SQL File Support
Cursor provides syntax highlighting and IntelliSense for .sql files:
- Create a
.sqlfile - Cursor automatically enables SQL language mode
- Use
Ctrl+Spacefor autocomplete on table and column names
Store reusable query patterns in .sql files. Cursor indexes them and can reference them when generating new queries.
Prisma Integration
Setting Up Prisma
Initialize Prisma in your project:
npm install prisma @prisma/client
npx prisma init
Schema Design with AI
Describe your data model in natural language:
Design a Prisma schema for an e-commerce application with:
- Users (with roles: admin, customer, seller)
- Products (with categories, inventory tracking)
- Orders (with status, shipping details)
- Reviews (linked to products and users)
Cursor generates:
model User {
id Int @id @default(autoincrement())
email String @unique
name String
role Role @default(CUSTOMER)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
orders Order[]
reviews Review[]
}
enum Role {
ADMIN
CUSTOMER
SELLER
}
model Product {
id Int @id @default(autoincrement())
name String
description String?
price Decimal @db.Decimal(10, 2)
inventory Int @default(0)
categoryId Int
category Category @relation(fields: [categoryId], references: [id])
reviews Review[]
orderItems OrderItem[]
}
model Category {
id Int @id @default(autoincrement())
name String @unique
products Product[]
}
model Order {
id Int @id @default(autoincrement())
status OrderStatus @default(PENDING)
total Decimal @db.Decimal(10, 2)
createdAt DateTime @default(now())
userId Int
user User @relation(fields: [userId], references: [id])
orderItems OrderItem[]
}
enum OrderStatus {
PENDING
PROCESSING
SHIPPED
DELIVERED
CANCELLED
}
model OrderItem {
id Int @id @default(autoincrement())
quantity Int
unitPrice Decimal @db.Decimal(10, 2)
orderId Int
productId Int
order Order @relation(fields: [orderId], references: [id])
product Product @relation(fields: [productId], references: [id])
}
model Review {
id Int @id @default(autoincrement())
rating Int
comment String?
createdAt DateTime @default(now())
userId Int
productId Int
user User @relation(fields: [userId], references: [id])
product Product @relation(fields: [productId], references: [id])
@@unique([userId, productId])
}
Generating Migrations
After schema changes, generate and apply migrations:
npx prisma migrate dev --name add_user_roles
Use Cursor to review migration files before applying them:
Review this migration file for potential data loss or issues:
[paste migration.sql content]
Prisma Client Queries
Generate type-safe queries with AI assistance:
Write a Prisma query to get all orders for a user including product details
const userOrders = await prisma.order.findMany({
where: { userId: 1 },
include: {
orderItems: {
include: {
product: {
select: {
name: true,
price: true,
},
},
},
},
},
orderBy: {
createdAt: 'desc',
},
});
TypeORM and Sequelize Workflows
TypeORM Setup
// src/db/data-source.ts
import { DataSource } from 'typeorm';
import { User } from './entities/User';
import { Order } from './entities/Order';
export const AppDataSource = new DataSource({
type: 'postgres',
host: 'localhost',
port: 5432,
username: 'user',
password: 'password',
database: 'myapp',
synchronize: false,
logging: true,
entities: [User, Order],
migrations: ['src/migrations/*.ts'],
});
Sequelize Models
// src/models/User.js
const { DataTypes } = require('sequelize');
module.exports = (sequelize) => {
const User = sequelize.define('User', {
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
},
email: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
validate: {
isEmail: true,
},
},
name: {
type: DataTypes.STRING,
allowNull: false,
},
}, {
tableName: 'users',
timestamps: true,
});
return User;
};
Database Schema Visualization
Using Prisma ERD
Generate entity-relationship diagrams:
npx prisma generate --generator erd
Or ask Cursor to create a visual schema:
Create a Mermaid ERD diagram for the Prisma schema in this project
AI-Assisted Query Optimization
Analyzing Query Performance
Share your query and execution plan:
This query has a sequential scan. How can I add indexes to optimize it?
EXPLAIN ANALYZE SELECT * FROM orders WHERE status = 'pending' AND created_at > '2024-01-01';
Cursor will suggest:
CREATE INDEX idx_orders_status_created_at ON orders(status, created_at);
Database Design Review
Ask Cursor to review your schema for best practices:
Review this database schema for:
1. Normalization issues
2. Missing indexes on foreign keys
3. Data type optimizations
4. Potential concurrency issues
Docker Compose for Local Development
version: '3.8'
services:
postgres:
image: postgres:16-alpine
environment:
POSTGRES_USER: dev
POSTGRES_PASSWORD: devpass
POSTGRES_DB: myapp
ports:
- "5432:5432"
volumes:
- postgres_data:/var/lib/postgresql/data
mysql:
image: mysql:8.0
environment:
MYSQL_ROOT_PASSWORD: rootpass
MYSQL_DATABASE: myapp
MYSQL_USER: dev
MYSQL_PASSWORD: devpass
ports:
- "3306:3306"
volumes:
- mysql_data:/var/lib/mysql
volumes:
postgres_data:
mysql_data:
Common Database Tasks
| Task | Cursor Prompt Example |
|---|---|
| Create migration | "Generate a migration to add a soft delete column to the users table" |
| Seed data | "Write a seed script to populate the database with 100 test users" |
| Backup query | "Write a pg_dump command to backup only the users and orders tables" |
| Connection pooling | "Configure connection pooling for a Node.js app with 100 concurrent users" |
| Audit logging | "Add an audit log table that tracks all changes to the orders table" |
Debugging Database Issues
Connection Problems
My Prisma client can't connect to PostgreSQL. Here is my connection string and error:
[paste error]
Migration Failures
When a migration fails:
- Check the migration status:
npx prisma migrate status
-
Ask Cursor to analyze the failure and suggest fixes
-
Resolve conflicts and mark as applied if needed:
npx prisma migrate resolve --applied migration_name
Best Practices
Security
- Never commit database credentials to version control
- Use environment variables for connection strings
- Enable SSL for production connections
- Use parameterized queries to prevent SQL injection
Performance
- Add indexes on frequently queried columns
- Use connection pooling in production
- Implement query result caching for read-heavy workloads
- Monitor slow query logs
Version Control
# Database
*.db
*.sqlite
*.sqlite3
.env
.env.local
prisma/migrations/migration_lock.toml
Quick Reference
| Action | Command |
|---|---|
| Generate Prisma client | npx prisma generate |
| Run migrations | npx prisma migrate dev |
| Reset database | npx prisma migrate reset |
| Open Prisma Studio | npx prisma studio |
| Seed database | npx prisma db seed |
| Format schema | npx prisma format |
Related Resources
Last updated: July 2025