agentleFS
girijashankarjgirijashankarj/cursor-handbook/.cursor/rules/database/query-patterns.mdc

cursor-handbook / database

Cursor rule31 starsChanged 3 months agoMITView on GitHub

Database query patterns, optimization, and safety rules. Apply when writing or editing queries.

The file

Show its rules and text

We split this query-patterns.mdc into the rules it gives an agent

21 rules. About 0 are common, 12 are distinctive, and 9 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈12

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 9

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    NEVER: use DELETE FROM statements

    line 12
  2. Very specific:

    ALWAYS: use soft delete: UPDATE table SET {{CONFIG.database.softDeleteField}} = false WHERE id = $1

    line 13
  3. Very specific:

    All queries MUST filter by {{CONFIG.database.softDeleteField}} = true unless explicitly recovering deleted records

    line 14
  4. Distinctive:

    Every table MUST include:

    line 27
  5. Distinctive:

    Use composite indexes for multi-column queries

    line 40
  6. Distinctive:

    Consider partial indexes for filtered queries

    line 41
  7. Very specific:

    Use LIMIT + OFFSET only for small datasets

    line 46
  8. Very specific:

    Always include ORDER BY with pagination

    line 47
  9. Distinctive:

    Use JOINs or batch queries instead of loops

    line 66
  10. Distinctive:

    Use DataLoader pattern for GraphQL resolvers

    line 67
  11. Distinctive:

    Every schema change MUST be a migration

    line 72
  12. Distinctive:

    Test migrations against a copy of production data

    line 74
  13. Distinctive:

    Never modify existing migrations — create new ones

    line 75
  14. Very specific:

    Don't use SELECT * in production — list columns explicitly

    line 79
  15. Distinctive:

    Don't use OFFSET for large tables — use cursor-based pagination

    line 80
  16. Distinctive:

    Don't run queries in loops — batch or JOIN

    line 81
  17. Very specific:

    Don't skip {{CONFIG.database.softDeleteField}} filter — all reads must filter

    line 82
  18. Distinctive:

    Don't use raw strings in queries — always parameterize

    line 83
  19. Distinctive:

    NULL in unique index: Use partial index or COALESCE for "one active per user"

    line 95
  20. Very specific:

    Timezone in timestamps: Always use TIMESTAMP WITH TIME ZONE

    line 97
  21. Very specific:

    Use @create-migration skill for new migrations

    line 100

≈ “Common” is an estimate: at least 1 in 5 of the 3,030 Cursor rule files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
query-patterns.mdc
---
description: "Database query patterns, optimization, and safety rules. Apply when writing or editing queries."
alwaysApply: false
globs: "**/*.sql,**/*.model.ts,**/*.repository.ts,**/migrations/**/*"
---

# Database Query Patterns

## Absolute Rules

### 1. Soft Delete Only
- **NEVER** use `DELETE FROM` statements
- **ALWAYS** use soft delete: `UPDATE table SET {{CONFIG.database.softDeleteField}} = false WHERE id = $1`
- All queries MUST filter by `{{CONFIG.database.softDeleteField}} = true` unless explicitly recovering deleted records
- Column naming convention: `{{CONFIG.database.naming}}`

### 2. Parameterized Queries Only
```sql
-- CORRECT: Parameterized
SELECT * FROM orders WHERE id = $1 AND {{CONFIG.database.softDeleteField}} = true;

-- WRONG: String concatenation (SQL injection risk)
SELECT * FROM orders WHERE id = '${orderId}';
```

### 3. Required Columns
Every table MUST include:
| Column | Type | Description |
|--------|------|-------------|
| `id` | UUID / BIGINT | Primary key |
| `{{CONFIG.database.timestampFields.created}}` | TIMESTAMP | Record creation time |
| `{{CONFIG.database.timestampFields.updated}}` | TIMESTAMP | Last update time |
| `{{CONFIG.database.softDeleteField}}` | BOOLEAN | Soft delete flag (default: true) |

## Query Optimization

### Indexing Strategy
- Index all foreign key columns
- Index columns used in WHERE clauses frequently
- Use composite indexes for multi-column queries
- Consider partial indexes for filtered queries
- Monitor slow query logs and add indexes accordingly

### Pagination
- **Prefer cursor-based pagination** for large datasets
- Use `LIMIT` + `OFFSET` only for small datasets
- Always include `ORDER BY` with pagination
- Return `hasNextPage` and `cursor` in pagination metadata

```sql
-- Cursor-based pagination (preferred)
SELECT * FROM orders
WHERE {{CONFIG.database.softDeleteField}} = true
  AND {{CONFIG.database.timestampFields.created}} < $1
ORDER BY {{CONFIG.database.timestampFields.created}} DESC
LIMIT 20;

-- Offset pagination (simple cases only)
SELECT * FROM orders
WHERE {{CONFIG.database.softDeleteField}} = true
ORDER BY {{CONFIG.database.timestampFields.created}} DESC
LIMIT $1 OFFSET $2;
```

### N+1 Prevention
- Use JOINs or batch queries instead of loops
- Use DataLoader pattern for GraphQL resolvers
- Preload associations when you know they'll be needed
- Monitor query counts per request in development

## Migration Rules
- Every schema change MUST be a migration
- Migrations MUST be reversible (up and down)
- Test migrations against a copy of production data
- Never modify existing migrations — create new ones
- Name format: `YYYYMMDDHHMMSS_descriptive_name`

## Anti-patterns
- Don't use `SELECT *` in production — list columns explicitly
- Don't use OFFSET for large tables — use cursor-based pagination
- Don't run queries in loops — batch or JOIN
- Don't skip `{{CONFIG.database.softDeleteField}}` filter — all reads must filter
- Don't use raw strings in queries — always parameterize

## Examples
```sql
-- BAD: String concatenation
WHERE id = '${id}'

-- GOOD: Parameterized
WHERE id = $1 AND active_indicator = true
```

## Edge Cases
- **NULL in unique index**: Use partial index or COALESCE for "one active per user"
- **Large IN clauses**: Batch into chunks of 100–500; or use temp table
- **Timezone in timestamps**: Always use `TIMESTAMP WITH TIME ZONE`

## Related
- Use `@create-migration` skill for new migrations
- See `@schema-design` for table structure

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.