---
# Database Patterns

<!--
GENERATION INSTRUCTIONS:
1. Detect ORM/query builder/raw SQL approach
2. Scan models/entities for relationships
3. Extract actual query patterns from repositories/services
4. Find transaction usage examples
5. Locate migration files and commands
6. Output: 150-300 lines max
-->

**Project**: [Extract from config]
**Database**: [Detect: PostgreSQL | MySQL | MongoDB | SQLite | etc.]
**Data Access**: [Detect: ORM (name) | Query Builder | Raw SQL | Mixed]
**Models Location**: `[Detect path]`

---

## Connection Setup

<!-- Extract actual connection configuration -->

```[lang]
// Source: [file:lines]
[Extract connection/pool configuration]
```

**Environment Variables**:
| Variable | Purpose |
|----------|---------|
| `[DB_HOST/DATABASE_URL]` | [Connection string or host] |
| `[DB_NAME]` | [Database name] |
| `[DB_POOL_SIZE]` | [Pool size if configured] |

---

## Data Access Pattern

<!-- Identify how this codebase accesses data -->

**Pattern**: [Detect: Repository | Active Record | DAO | Direct ORM | Service Layer]

```[lang]
// Source: [file:lines]
[Extract canonical data access example - the PRIMARY pattern used]
```

**To add new data access:**
1. Create in `[detected path]`
2. Follow pattern: `[detected naming convention]`
3. Inject/import via `[detected DI or import pattern]`

---

## Entity/Model Definition

<!-- Extract representative model showing conventions -->

```[lang]
// Source: [file:lines]
[Extract one model with relationships, validations, typical fields]
```

**Conventions:**
| Aspect | Convention |
|--------|------------|
| Table naming | `[singular/plural, snake_case/PascalCase]` |
| Primary key | `[id/uuid/_id pattern]` |
| Timestamps | `[created_at/createdAt, updated_at/updatedAt]` |
| Soft delete | `[deleted_at field or N/A]` |

---

## Relationships

<!-- Scan models and document relationship patterns -->

```
[EntityA] ──1:N──► [EntityB] ──N:M──► [EntityC]
                       │
                   1:1─┴─► [EntityD]
```

| Relationship | Implementation | Source |
|--------------|----------------|--------|
| One-to-Many | `[syntax used]` | `[file:line]` |
| Many-to-Many | `[syntax used]` | `[file:line]` |
| One-to-One | `[syntax used]` | `[file:line]` |

---

## Query Patterns

<!-- Extract actual query patterns used in codebase -->

### Basic Operations

| Operation | Pattern | Source |
|-----------|---------|--------|
| Find by ID | `[extract syntax]` | `[file:line]` |
| Find many | `[extract syntax]` | `[file:line]` |
| Create | `[extract syntax]` | `[file:line]` |
| Update | `[extract syntax]` | `[file:line]` |
| Delete | `[extract syntax]` | `[file:line]` |

### Filtering & Search

```[lang]
// Source: [file:lines]
[Extract example with WHERE conditions, filtering]
```

### Pagination

```[lang]
// Source: [file:lines]
[Extract pagination implementation]
```

**Type**: [Offset-based | Cursor-based | Keyset]
**Params**: `[page/limit or cursor/take]`

### Complex Query Example

```[lang]
// Source: [file:lines]
[Extract query with joins, aggregations, or subqueries if exists]
```

---

## Transactions

<!-- Find transaction usage in codebase -->

```[lang]
// Source: [file:lines]
[Extract transaction pattern]
```

**Transaction boundaries managed at**: `[Service layer | Repository | Controller]`

**Rules in this codebase:**
- [Extract or infer transaction conventions]
- [When transactions are used]

---

## Eager Loading / N+1 Prevention

<!-- Find include/join/populate patterns -->

```[lang]
// Source: [file:lines]
[Extract eager loading example]
```

**Syntax**: `[include/populate/joinedLoad/with - whatever ORM uses]`

---

## Migrations

<!-- Extract exact commands from package.json, Makefile, or docs -->

| Action | Command |
|--------|---------|
| Create migration | `[exact command]` |
| Run pending | `[exact command]` |
| Rollback last | `[exact command]` |
| Check status | `[exact command]` |

**Migrations location**: `[path]`

**Naming convention**: `[timestamp_description | sequential | etc.]`

```[lang]
// Source: [file:lines]
[Extract example migration structure]
```

---

## Seeding / Fixtures

<!-- Find seed data patterns if they exist -->

| Action | Command |
|--------|---------|
| Run seeds | `[command or N/A]` |
| Reset + seed | `[command or N/A]` |

**Seeds location**: `[path or N/A]`

---

## Raw Queries

<!-- Find if/how raw SQL is used -->

**Used for**: [Complex reports | Bulk operations | Not used | etc.]

```[lang]
// Source: [file:lines] - ALWAYS parameterized
[Extract parameterized raw query example]
```

⚠️ **Never**: String interpolation → SQL injection risk

---

## Error Handling

<!-- Find database error handling patterns -->

| Error Type | Handling | Source |
|------------|----------|--------|
| Not found | `[throw/return pattern]` | `[file:line]` |
| Duplicate key | `[catch/handle pattern]` | `[file:line]` |
| Connection error | `[retry/fail pattern]` | `[file:line]` |

---

## Conventions Summary

| ✅ DO | ❌ DON'T |
|-------|----------|
| Use `[detected data access pattern]` | Direct DB calls in `[wrong layer]` |
| `[eager load syntax]` for relations | Lazy load in loops (N+1) |
| Parameterized queries | String interpolation |
| Transactions for multi-writes | Individual saves for related data |
| `[soft delete if used]` | Hard delete `[if soft delete is convention]` |

---

## Quick Reference

| Need | Location | Pattern |
|------|----------|---------|
| Models/Entities | `[path]` | `[naming]` |
| Repositories/DAOs | `[path]` | `[naming]` |
| Migrations | `[path]` | `[naming]` |
| Seeds | `[path]` | `[naming]` |
| DB Config | `[path]` | - |

---