tribunal-kit 4.3.0 → 4.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.agent/scripts/case_law_manager.js +684 -684
- package/.agent/scripts/graph_builder.js +199 -0
- package/.agent/scripts/graph_zoom.js +154 -0
- package/.agent/skills/agent-organizer/SKILL.md +9 -1
- package/.agent/skills/agentic-patterns/SKILL.md +9 -1
- package/.agent/skills/ai-prompt-injection-defense/SKILL.md +9 -1
- package/.agent/skills/api-patterns/SKILL.md +206 -198
- package/.agent/skills/api-security-auditor/SKILL.md +9 -1
- package/.agent/skills/app-builder/SKILL.md +9 -1
- package/.agent/skills/app-builder/templates/SKILL.md +77 -69
- package/.agent/skills/appflow-wireframe/SKILL.md +9 -1
- package/.agent/skills/architecture/SKILL.md +9 -1
- package/.agent/skills/authentication-best-practices/SKILL.md +9 -1
- package/.agent/skills/bash-linux/SKILL.md +9 -1
- package/.agent/skills/behavioral-modes/SKILL.md +9 -1
- package/.agent/skills/brainstorming/SKILL.md +9 -1
- package/.agent/skills/building-native-ui/SKILL.md +9 -1
- package/.agent/skills/clean-code/SKILL.md +9 -1
- package/.agent/skills/code-review-checklist/SKILL.md +9 -1
- package/.agent/skills/config-validator/SKILL.md +9 -1
- package/.agent/skills/csharp-developer/SKILL.md +9 -1
- package/.agent/skills/data-validation-schemas/SKILL.md +287 -279
- package/.agent/skills/database-design/SKILL.md +199 -191
- package/.agent/skills/deployment-procedures/SKILL.md +9 -1
- package/.agent/skills/devops-engineer/SKILL.md +9 -1
- package/.agent/skills/devops-incident-responder/SKILL.md +9 -1
- package/.agent/skills/documentation-templates/SKILL.md +9 -1
- package/.agent/skills/edge-computing/SKILL.md +9 -1
- package/.agent/skills/error-resilience/SKILL.md +387 -379
- package/.agent/skills/extract-design-system/SKILL.md +9 -1
- package/.agent/skills/framer-motion-expert/SKILL.md +203 -195
- package/.agent/skills/frontend-design/SKILL.md +160 -152
- package/.agent/skills/game-design-expert/SKILL.md +9 -1
- package/.agent/skills/game-engineering-expert/SKILL.md +9 -1
- package/.agent/skills/geo-fundamentals/SKILL.md +9 -1
- package/.agent/skills/github-operations/SKILL.md +9 -1
- package/.agent/skills/gsap-core/SKILL.md +54 -46
- package/.agent/skills/gsap-frameworks/SKILL.md +54 -46
- package/.agent/skills/gsap-performance/SKILL.md +54 -46
- package/.agent/skills/gsap-plugins/SKILL.md +54 -46
- package/.agent/skills/gsap-react/SKILL.md +54 -46
- package/.agent/skills/gsap-scrolltrigger/SKILL.md +54 -46
- package/.agent/skills/gsap-timeline/SKILL.md +54 -46
- package/.agent/skills/gsap-utils/SKILL.md +54 -46
- package/.agent/skills/i18n-localization/SKILL.md +9 -1
- package/.agent/skills/intelligent-routing/SKILL.md +38 -30
- package/.agent/skills/knowledge-graph/SKILL.md +36 -0
- package/.agent/skills/lint-and-validate/SKILL.md +9 -1
- package/.agent/skills/llm-engineering/SKILL.md +9 -1
- package/.agent/skills/local-first/SKILL.md +9 -1
- package/.agent/skills/mcp-builder/SKILL.md +9 -1
- package/.agent/skills/mobile-design/SKILL.md +222 -214
- package/.agent/skills/monorepo-management/SKILL.md +293 -285
- package/.agent/skills/motion-engineering/SKILL.md +193 -185
- package/.agent/skills/nextjs-react-expert/SKILL.md +193 -185
- package/.agent/skills/nodejs-best-practices/SKILL.md +9 -1
- package/.agent/skills/observability/SKILL.md +9 -1
- package/.agent/skills/parallel-agents/SKILL.md +9 -1
- package/.agent/skills/performance-profiling/SKILL.md +9 -1
- package/.agent/skills/plan-writing/SKILL.md +9 -1
- package/.agent/skills/platform-engineer/SKILL.md +9 -1
- package/.agent/skills/playwright-best-practices/SKILL.md +9 -1
- package/.agent/skills/powershell-windows/SKILL.md +9 -1
- package/.agent/skills/project-idioms/SKILL.md +9 -1
- package/.agent/skills/python-patterns/SKILL.md +9 -1
- package/.agent/skills/python-pro/SKILL.md +282 -274
- package/.agent/skills/react-specialist/SKILL.md +236 -228
- package/.agent/skills/readme-builder/SKILL.md +9 -1
- package/.agent/skills/realtime-patterns/SKILL.md +9 -1
- package/.agent/skills/red-team-tactics/SKILL.md +9 -1
- package/.agent/skills/rust-pro/SKILL.md +9 -1
- package/.agent/skills/seo-fundamentals/SKILL.md +9 -1
- package/.agent/skills/server-management/SKILL.md +9 -1
- package/.agent/skills/shadcn-ui-expert/SKILL.md +9 -1
- package/.agent/skills/skill-creator/SKILL.md +9 -1
- package/.agent/skills/sql-pro/SKILL.md +9 -1
- package/.agent/skills/supabase-postgres-best-practices/SKILL.md +9 -1
- package/.agent/skills/swiftui-expert/SKILL.md +9 -1
- package/.agent/skills/systematic-debugging/SKILL.md +9 -1
- package/.agent/skills/tailwind-patterns/SKILL.md +9 -1
- package/.agent/skills/tdd-workflow/SKILL.md +9 -1
- package/.agent/skills/test-result-analyzer/SKILL.md +9 -1
- package/.agent/skills/testing-patterns/SKILL.md +9 -1
- package/.agent/skills/trend-researcher/SKILL.md +9 -1
- package/.agent/skills/typescript-advanced/SKILL.md +294 -286
- package/.agent/skills/ui-ux-pro-max/SKILL.md +9 -1
- package/.agent/skills/ui-ux-researcher/SKILL.md +9 -1
- package/.agent/skills/vue-expert/SKILL.md +234 -226
- package/.agent/skills/vulnerability-scanner/SKILL.md +9 -1
- package/.agent/skills/web-accessibility-auditor/SKILL.md +9 -1
- package/.agent/skills/web-design-guidelines/SKILL.md +9 -1
- package/.agent/skills/webapp-testing/SKILL.md +9 -1
- package/.agent/skills/whimsy-injector/SKILL.md +9 -1
- package/.agent/skills/workflow-optimizer/SKILL.md +9 -1
- package/README.md +242 -242
- package/bin/tribunal-kit.js +30 -22
- package/package.json +81 -80
- package/scripts/validate-payload.js +73 -0
|
@@ -1,193 +1,193 @@
|
|
|
1
|
-
---
|
|
2
|
-
name: database-design
|
|
3
|
-
description: Database design mastery. Schema design with normalization, denormalization strategies, indexing, migration pipelines, ORM selection (Prisma/Drizzle/SQLAlchemy/EF Core), connection pooling, soft deletes, audit trails, multi-tenancy, and serverless database patterns. Use when designing schemas, choosing databases, planning migrations, or architecting data layers.
|
|
4
|
-
allowed-tools: Read, Write, Edit, Glob, Grep
|
|
5
|
-
version: 3.1.0
|
|
6
|
-
last-updated: 2026-04-07
|
|
7
|
-
applies-to-model: gemini-3-1-pro, claude-3-7-sonnet
|
|
8
|
-
---
|
|
9
|
-
|
|
10
|
-
# Database Design — Schema & Architecture Mastery
|
|
11
|
-
|
|
12
|
-
## Hallucination Traps (Read First)
|
|
13
|
-
- ❌ `TIMESTAMP` → ✅ Always `TIMESTAMPTZ` (with timezone). `TIMESTAMP` is ambiguous across timezones.
|
|
14
|
-
- ❌ UUID v4 as primary key → ✅ UUID v7 (time-ordered) or `BIGINT GENERATED ALWAYS AS IDENTITY`. UUID v4 is random — destroys B-tree index performance on high-insert tables.
|
|
15
|
-
- ❌ No index on foreign keys → ✅ PostgreSQL does NOT auto-index FK columns. Cascading deletes cause full table scans without them.
|
|
16
|
-
- ❌ Adding `NOT NULL` column directly to a large table → ✅ Locks the entire table. Add as nullable, backfill in batches, then add constraint.
|
|
17
|
-
- ❌ Soft delete without a partial index → ✅ Every query must filter `WHERE deleted_at IS NULL`. Add `CREATE INDEX ... WHERE deleted_at IS NULL` or use a view.
|
|
18
|
-
- ❌ Serverless functions without a connection pooler → ✅ Each Lambda/Vercel invocation opens a new connection. Use PgBouncer or Supabase Supavisor — without it, you'll hit `max_connections` instantly.
|
|
19
|
-
|
|
20
|
-
---
|
|
21
|
-
|
|
22
|
-
## Database Selection
|
|
23
|
-
|
|
24
|
-
```
|
|
25
|
-
Relational / Complex queries → PostgreSQL (primary choice)
|
|
26
|
-
Serverless PG → Neon, Supabase
|
|
27
|
-
Edge / Ultra-low latency → Turso (SQLite @ edge)
|
|
28
|
-
Simple / Embedded → SQLite
|
|
29
|
-
Global distribution (MySQL) → PlanetScale (no FK support)
|
|
30
|
-
|
|
31
|
-
Key-value / Cache → Redis / Valkey / Upstash
|
|
32
|
-
Document store → MongoDB / Firestore
|
|
33
|
-
Full-text search → PostgreSQL tsvector (built-in) or Meilisearch / Typesense
|
|
34
|
-
Time-series → TimescaleDB / ClickHouse
|
|
35
|
-
Vector (AI embeddings) → pgvector (PostgreSQL ext) / Pinecone / Weaviate
|
|
36
|
-
```
|
|
37
|
-
|
|
38
|
-
---
|
|
39
|
-
|
|
40
|
-
## Standard Table Template
|
|
41
|
-
|
|
42
|
-
```sql
|
|
43
|
-
CREATE TABLE users (
|
|
44
|
-
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
|
45
|
-
-- OR: id UUID DEFAULT gen_random_uuid() PRIMARY KEY (use v7 for perf)
|
|
46
|
-
email TEXT NOT NULL UNIQUE,
|
|
47
|
-
name TEXT NOT NULL,
|
|
48
|
-
role TEXT NOT NULL DEFAULT 'user' CHECK (role IN ('admin', 'user', 'moderator')),
|
|
49
|
-
is_active BOOLEAN NOT NULL DEFAULT true,
|
|
50
|
-
metadata JSONB DEFAULT '{}',
|
|
51
|
-
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
52
|
-
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
53
|
-
deleted_at TIMESTAMPTZ -- soft delete
|
|
54
|
-
);
|
|
55
|
-
|
|
56
|
-
-- Required: auto-update updated_at
|
|
57
|
-
CREATE OR REPLACE FUNCTION update_updated_at() RETURNS TRIGGER AS $$
|
|
58
|
-
BEGIN NEW.updated_at = now(); RETURN NEW; END; $$ LANGUAGE plpgsql;
|
|
59
|
-
CREATE TRIGGER trg_users_updated_at BEFORE UPDATE ON users FOR EACH ROW EXECUTE FUNCTION update_updated_at();
|
|
60
|
-
|
|
61
|
-
-- Required indexes
|
|
62
|
-
CREATE INDEX idx_users_email ON users (email);
|
|
63
|
-
CREATE INDEX idx_users_active ON users (email) WHERE deleted_at IS NULL; -- partial index for soft delete
|
|
64
|
-
CREATE INDEX idx_users_created_at ON users (created_at DESC);
|
|
65
|
-
```
|
|
66
|
-
|
|
67
|
-
---
|
|
68
|
-
|
|
69
|
-
## Schema Patterns
|
|
70
|
-
|
|
71
|
-
### Relationships
|
|
72
|
-
```sql
|
|
73
|
-
-- One-to-Many: FK on the "many" side + INDEX
|
|
74
|
-
CREATE TABLE posts (
|
|
75
|
-
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
|
76
|
-
author_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
|
77
|
-
...
|
|
78
|
-
);
|
|
79
|
-
CREATE INDEX idx_posts_author_id ON posts (author_id); -- REQUIRED in Postgres
|
|
80
|
-
|
|
81
|
-
-- Many-to-Many: junction table with composite PK
|
|
82
|
-
CREATE TABLE post_tags (
|
|
83
|
-
post_id BIGINT NOT NULL REFERENCES posts(id) ON DELETE CASCADE,
|
|
84
|
-
tag_id BIGINT NOT NULL REFERENCES tags(id) ON DELETE CASCADE,
|
|
85
|
-
PRIMARY KEY (post_id, tag_id)
|
|
86
|
-
);
|
|
87
|
-
CREATE INDEX idx_post_tags_tag_id ON post_tags (tag_id); -- index the non-PK side
|
|
88
|
-
```
|
|
89
|
-
|
|
90
|
-
### Multi-Tenancy
|
|
91
|
-
```sql
|
|
92
|
-
-- Pattern 1: tenant_id column (simplest — enforce via RLS)
|
|
93
|
-
ALTER TABLE projects ENABLE ROW LEVEL SECURITY;
|
|
94
|
-
CREATE POLICY tenant_isolation ON projects
|
|
95
|
-
USING (tenant_id = current_setting('app.current_tenant_id')::bigint);
|
|
96
|
-
|
|
97
|
-
-- Pattern 2: Schema per tenant (better isolation, harder migrations)
|
|
98
|
-
-- CREATE SCHEMA tenant_acme;
|
|
99
|
-
|
|
100
|
-
-- Pattern 3: DB per tenant — only for compliance/regulatory needs
|
|
101
|
-
```
|
|
102
|
-
|
|
103
|
-
---
|
|
104
|
-
|
|
105
|
-
## ORM Selection
|
|
106
|
-
|
|
107
|
-
| ORM | Best For | Trade-offs |
|
|
108
|
-
|-----|----------|------------|
|
|
109
|
-
| **Drizzle** | Edge, TypeScript, bundle-size sensitive | Newer, fewer examples |
|
|
110
|
-
| **Prisma** | DX, schema management, Prisma Studio | Heavy, NOT edge-compatible |
|
|
111
|
-
| **Kysely** | Type-safe SQL builder, full control | Manual migrations |
|
|
112
|
-
| **Raw SQL** | Complex queries, performance-critical | Manual type safety |
|
|
113
|
-
| **SQLAlchemy 2.0** | Python async ecosystem | Python only |
|
|
114
|
-
|
|
115
|
-
```typescript
|
|
116
|
-
// Drizzle — SQL-like, edge-compatible
|
|
117
|
-
const result = await db.select({ id: users.id, name: users.name }).from(users)
|
|
118
|
-
.where(and(eq(users.role, "admin"), eq(users.isActive, true)))
|
|
119
|
-
.orderBy(desc(users.createdAt)).limit(20);
|
|
120
|
-
|
|
121
|
-
// Prisma — ❌ TRAP: can't express complex joins natively → use prisma.$queryRaw<Type>
|
|
122
|
-
const user = await prisma.user.findUnique({ where: { email }, include: { posts: { take: 10 } } });
|
|
123
|
-
```
|
|
124
|
-
|
|
125
|
-
---
|
|
126
|
-
|
|
127
|
-
## Migrations (Zero-Downtime Strategy)
|
|
128
|
-
|
|
129
|
-
```sql
|
|
130
|
-
-- Safe column add on a large production table:
|
|
131
|
-
-- Step 1: Add nullable (no lock)
|
|
132
|
-
ALTER TABLE users ADD COLUMN phone TEXT;
|
|
133
|
-
-- Step 2: Backfill in batches (non-blocking)
|
|
134
|
-
UPDATE users SET phone = '' WHERE phone IS NULL AND id BETWEEN 1 AND 10000;
|
|
135
|
-
-- Step 3: Add constraint AFTER all code deploys write the column
|
|
136
|
-
ALTER TABLE users ALTER COLUMN phone SET NOT NULL;
|
|
137
|
-
```
|
|
138
|
-
|
|
139
|
-
**Migration Rules:**
|
|
140
|
-
- Never modify a migration already applied to production — create a new one
|
|
141
|
-
- Remove column in 2 deploys: first remove all code references, then `DROP COLUMN`
|
|
142
|
-
- `CREATE INDEX CONCURRENTLY` to avoid table locks on existing data
|
|
143
|
-
- Test migrations against a copy of production data before running live
|
|
144
|
-
|
|
145
|
-
---
|
|
146
|
-
|
|
147
|
-
## Indexing Reference
|
|
148
|
-
|
|
149
|
-
| Index Type | Use For |
|
|
150
|
-
|------------|---------|
|
|
151
|
-
| **B-tree** | General purpose — equality & range queries (default) |
|
|
152
|
-
| **Hash** | Equality-only lookups (faster than B-tree for =) |
|
|
153
|
-
| **GIN** | JSONB, arrays, full-text (`tsvector`) |
|
|
154
|
-
| **GiST** | Geometric, range types |
|
|
155
|
-
| **HNSW / IVFFlat** | Vector similarity (pgvector) |
|
|
156
|
-
|
|
157
|
-
**Composite index column order:** equality columns first → range columns last → most selective first
|
|
158
|
-
|
|
159
|
-
---
|
|
160
|
-
|
|
161
|
-
## Audit Trail
|
|
162
|
-
|
|
163
|
-
```sql
|
|
164
|
-
CREATE TABLE audit_log (
|
|
165
|
-
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
|
166
|
-
table_name TEXT NOT NULL, record_id BIGINT NOT NULL,
|
|
167
|
-
action TEXT NOT NULL CHECK (action IN ('INSERT', 'UPDATE', 'DELETE')),
|
|
168
|
-
old_data JSONB, new_data JSONB,
|
|
169
|
-
changed_by BIGINT REFERENCES users(id),
|
|
170
|
-
changed_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
171
|
-
);
|
|
172
|
-
CREATE INDEX idx_audit_log_table_record ON audit_log (table_name, record_id);
|
|
173
|
-
CREATE INDEX idx_audit_log_changed_at ON audit_log USING brin (changed_at); -- BRIN for time-ordered append-only tables
|
|
174
|
-
```
|
|
175
|
-
|
|
176
|
-
---
|
|
177
|
-
|
|
178
|
-
## Connection Pooling
|
|
179
|
-
|
|
180
|
-
```
|
|
181
|
-
Without pooling: 100 concurrent requests → 100 DB connections → overwhelms DB
|
|
182
|
-
With pooling: 100 concurrent requests → 10–20 reused connections
|
|
183
|
-
|
|
184
|
-
Sizing formula: max_connections = (cpu_cores × 2) + disk_spindles (typically 25–50)
|
|
185
|
-
|
|
186
|
-
Poolers:
|
|
187
|
-
PgBouncer → External, most common for self-hosted Postgres
|
|
188
|
-
Prisma Accelerate → Managed, for Prisma projects
|
|
189
|
-
Supabase Supavisor → Managed, for Supabase projects
|
|
190
|
-
```
|
|
1
|
+
---
|
|
2
|
+
name: database-design
|
|
3
|
+
description: Database design mastery. Schema design with normalization, denormalization strategies, indexing, migration pipelines, ORM selection (Prisma/Drizzle/SQLAlchemy/EF Core), connection pooling, soft deletes, audit trails, multi-tenancy, and serverless database patterns. Use when designing schemas, choosing databases, planning migrations, or architecting data layers.
|
|
4
|
+
allowed-tools: Read, Write, Edit, Glob, Grep
|
|
5
|
+
version: 3.1.0
|
|
6
|
+
last-updated: 2026-04-07
|
|
7
|
+
applies-to-model: gemini-3-1-pro, claude-3-7-sonnet
|
|
8
|
+
---
|
|
9
|
+
|
|
10
|
+
# Database Design — Schema & Architecture Mastery
|
|
11
|
+
|
|
12
|
+
## Hallucination Traps (Read First)
|
|
13
|
+
- ❌ `TIMESTAMP` → ✅ Always `TIMESTAMPTZ` (with timezone). `TIMESTAMP` is ambiguous across timezones.
|
|
14
|
+
- ❌ UUID v4 as primary key → ✅ UUID v7 (time-ordered) or `BIGINT GENERATED ALWAYS AS IDENTITY`. UUID v4 is random — destroys B-tree index performance on high-insert tables.
|
|
15
|
+
- ❌ No index on foreign keys → ✅ PostgreSQL does NOT auto-index FK columns. Cascading deletes cause full table scans without them.
|
|
16
|
+
- ❌ Adding `NOT NULL` column directly to a large table → ✅ Locks the entire table. Add as nullable, backfill in batches, then add constraint.
|
|
17
|
+
- ❌ Soft delete without a partial index → ✅ Every query must filter `WHERE deleted_at IS NULL`. Add `CREATE INDEX ... WHERE deleted_at IS NULL` or use a view.
|
|
18
|
+
- ❌ Serverless functions without a connection pooler → ✅ Each Lambda/Vercel invocation opens a new connection. Use PgBouncer or Supabase Supavisor — without it, you'll hit `max_connections` instantly.
|
|
19
|
+
|
|
20
|
+
---
|
|
21
|
+
|
|
22
|
+
## Database Selection
|
|
23
|
+
|
|
24
|
+
```
|
|
25
|
+
Relational / Complex queries → PostgreSQL (primary choice)
|
|
26
|
+
Serverless PG → Neon, Supabase
|
|
27
|
+
Edge / Ultra-low latency → Turso (SQLite @ edge)
|
|
28
|
+
Simple / Embedded → SQLite
|
|
29
|
+
Global distribution (MySQL) → PlanetScale (no FK support)
|
|
30
|
+
|
|
31
|
+
Key-value / Cache → Redis / Valkey / Upstash
|
|
32
|
+
Document store → MongoDB / Firestore
|
|
33
|
+
Full-text search → PostgreSQL tsvector (built-in) or Meilisearch / Typesense
|
|
34
|
+
Time-series → TimescaleDB / ClickHouse
|
|
35
|
+
Vector (AI embeddings) → pgvector (PostgreSQL ext) / Pinecone / Weaviate
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
---
|
|
39
|
+
|
|
40
|
+
## Standard Table Template
|
|
41
|
+
|
|
42
|
+
```sql
|
|
43
|
+
CREATE TABLE users (
|
|
44
|
+
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
|
45
|
+
-- OR: id UUID DEFAULT gen_random_uuid() PRIMARY KEY (use v7 for perf)
|
|
46
|
+
email TEXT NOT NULL UNIQUE,
|
|
47
|
+
name TEXT NOT NULL,
|
|
48
|
+
role TEXT NOT NULL DEFAULT 'user' CHECK (role IN ('admin', 'user', 'moderator')),
|
|
49
|
+
is_active BOOLEAN NOT NULL DEFAULT true,
|
|
50
|
+
metadata JSONB DEFAULT '{}',
|
|
51
|
+
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
52
|
+
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
53
|
+
deleted_at TIMESTAMPTZ -- soft delete
|
|
54
|
+
);
|
|
55
|
+
|
|
56
|
+
-- Required: auto-update updated_at
|
|
57
|
+
CREATE OR REPLACE FUNCTION update_updated_at() RETURNS TRIGGER AS $$
|
|
58
|
+
BEGIN NEW.updated_at = now(); RETURN NEW; END; $$ LANGUAGE plpgsql;
|
|
59
|
+
CREATE TRIGGER trg_users_updated_at BEFORE UPDATE ON users FOR EACH ROW EXECUTE FUNCTION update_updated_at();
|
|
60
|
+
|
|
61
|
+
-- Required indexes
|
|
62
|
+
CREATE INDEX idx_users_email ON users (email);
|
|
63
|
+
CREATE INDEX idx_users_active ON users (email) WHERE deleted_at IS NULL; -- partial index for soft delete
|
|
64
|
+
CREATE INDEX idx_users_created_at ON users (created_at DESC);
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
---
|
|
68
|
+
|
|
69
|
+
## Schema Patterns
|
|
70
|
+
|
|
71
|
+
### Relationships
|
|
72
|
+
```sql
|
|
73
|
+
-- One-to-Many: FK on the "many" side + INDEX
|
|
74
|
+
CREATE TABLE posts (
|
|
75
|
+
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
|
76
|
+
author_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
|
77
|
+
...
|
|
78
|
+
);
|
|
79
|
+
CREATE INDEX idx_posts_author_id ON posts (author_id); -- REQUIRED in Postgres
|
|
80
|
+
|
|
81
|
+
-- Many-to-Many: junction table with composite PK
|
|
82
|
+
CREATE TABLE post_tags (
|
|
83
|
+
post_id BIGINT NOT NULL REFERENCES posts(id) ON DELETE CASCADE,
|
|
84
|
+
tag_id BIGINT NOT NULL REFERENCES tags(id) ON DELETE CASCADE,
|
|
85
|
+
PRIMARY KEY (post_id, tag_id)
|
|
86
|
+
);
|
|
87
|
+
CREATE INDEX idx_post_tags_tag_id ON post_tags (tag_id); -- index the non-PK side
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
### Multi-Tenancy
|
|
91
|
+
```sql
|
|
92
|
+
-- Pattern 1: tenant_id column (simplest — enforce via RLS)
|
|
93
|
+
ALTER TABLE projects ENABLE ROW LEVEL SECURITY;
|
|
94
|
+
CREATE POLICY tenant_isolation ON projects
|
|
95
|
+
USING (tenant_id = current_setting('app.current_tenant_id')::bigint);
|
|
96
|
+
|
|
97
|
+
-- Pattern 2: Schema per tenant (better isolation, harder migrations)
|
|
98
|
+
-- CREATE SCHEMA tenant_acme;
|
|
99
|
+
|
|
100
|
+
-- Pattern 3: DB per tenant — only for compliance/regulatory needs
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
---
|
|
104
|
+
|
|
105
|
+
## ORM Selection
|
|
106
|
+
|
|
107
|
+
| ORM | Best For | Trade-offs |
|
|
108
|
+
|-----|----------|------------|
|
|
109
|
+
| **Drizzle** | Edge, TypeScript, bundle-size sensitive | Newer, fewer examples |
|
|
110
|
+
| **Prisma** | DX, schema management, Prisma Studio | Heavy, NOT edge-compatible |
|
|
111
|
+
| **Kysely** | Type-safe SQL builder, full control | Manual migrations |
|
|
112
|
+
| **Raw SQL** | Complex queries, performance-critical | Manual type safety |
|
|
113
|
+
| **SQLAlchemy 2.0** | Python async ecosystem | Python only |
|
|
114
|
+
|
|
115
|
+
```typescript
|
|
116
|
+
// Drizzle — SQL-like, edge-compatible
|
|
117
|
+
const result = await db.select({ id: users.id, name: users.name }).from(users)
|
|
118
|
+
.where(and(eq(users.role, "admin"), eq(users.isActive, true)))
|
|
119
|
+
.orderBy(desc(users.createdAt)).limit(20);
|
|
120
|
+
|
|
121
|
+
// Prisma — ❌ TRAP: can't express complex joins natively → use prisma.$queryRaw<Type>
|
|
122
|
+
const user = await prisma.user.findUnique({ where: { email }, include: { posts: { take: 10 } } });
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
---
|
|
126
|
+
|
|
127
|
+
## Migrations (Zero-Downtime Strategy)
|
|
128
|
+
|
|
129
|
+
```sql
|
|
130
|
+
-- Safe column add on a large production table:
|
|
131
|
+
-- Step 1: Add nullable (no lock)
|
|
132
|
+
ALTER TABLE users ADD COLUMN phone TEXT;
|
|
133
|
+
-- Step 2: Backfill in batches (non-blocking)
|
|
134
|
+
UPDATE users SET phone = '' WHERE phone IS NULL AND id BETWEEN 1 AND 10000;
|
|
135
|
+
-- Step 3: Add constraint AFTER all code deploys write the column
|
|
136
|
+
ALTER TABLE users ALTER COLUMN phone SET NOT NULL;
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
**Migration Rules:**
|
|
140
|
+
- Never modify a migration already applied to production — create a new one
|
|
141
|
+
- Remove column in 2 deploys: first remove all code references, then `DROP COLUMN`
|
|
142
|
+
- `CREATE INDEX CONCURRENTLY` to avoid table locks on existing data
|
|
143
|
+
- Test migrations against a copy of production data before running live
|
|
144
|
+
|
|
145
|
+
---
|
|
146
|
+
|
|
147
|
+
## Indexing Reference
|
|
148
|
+
|
|
149
|
+
| Index Type | Use For |
|
|
150
|
+
|------------|---------|
|
|
151
|
+
| **B-tree** | General purpose — equality & range queries (default) |
|
|
152
|
+
| **Hash** | Equality-only lookups (faster than B-tree for =) |
|
|
153
|
+
| **GIN** | JSONB, arrays, full-text (`tsvector`) |
|
|
154
|
+
| **GiST** | Geometric, range types |
|
|
155
|
+
| **HNSW / IVFFlat** | Vector similarity (pgvector) |
|
|
156
|
+
|
|
157
|
+
**Composite index column order:** equality columns first → range columns last → most selective first
|
|
158
|
+
|
|
159
|
+
---
|
|
160
|
+
|
|
161
|
+
## Audit Trail
|
|
162
|
+
|
|
163
|
+
```sql
|
|
164
|
+
CREATE TABLE audit_log (
|
|
165
|
+
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
|
166
|
+
table_name TEXT NOT NULL, record_id BIGINT NOT NULL,
|
|
167
|
+
action TEXT NOT NULL CHECK (action IN ('INSERT', 'UPDATE', 'DELETE')),
|
|
168
|
+
old_data JSONB, new_data JSONB,
|
|
169
|
+
changed_by BIGINT REFERENCES users(id),
|
|
170
|
+
changed_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
171
|
+
);
|
|
172
|
+
CREATE INDEX idx_audit_log_table_record ON audit_log (table_name, record_id);
|
|
173
|
+
CREATE INDEX idx_audit_log_changed_at ON audit_log USING brin (changed_at); -- BRIN for time-ordered append-only tables
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
---
|
|
177
|
+
|
|
178
|
+
## Connection Pooling
|
|
179
|
+
|
|
180
|
+
```
|
|
181
|
+
Without pooling: 100 concurrent requests → 100 DB connections → overwhelms DB
|
|
182
|
+
With pooling: 100 concurrent requests → 10–20 reused connections
|
|
183
|
+
|
|
184
|
+
Sizing formula: max_connections = (cpu_cores × 2) + disk_spindles (typically 25–50)
|
|
185
|
+
|
|
186
|
+
Poolers:
|
|
187
|
+
PgBouncer → External, most common for self-hosted Postgres
|
|
188
|
+
Prisma Accelerate → Managed, for Prisma projects
|
|
189
|
+
Supabase Supavisor → Managed, for Supabase projects
|
|
190
|
+
```
|
|
191
191
|
|
|
192
192
|
|
|
193
193
|
---
|
|
@@ -229,4 +229,12 @@ Review these questions before confirming output:
|
|
|
229
229
|
|
|
230
230
|
**CRITICAL:** You must follow a strict "evidence-based closeout" state machine.
|
|
231
231
|
- ❌ **Forbidden:** Declaring a task complete because the output "looks correct."
|
|
232
|
-
- ✅ **Required:** You are explicitly forbidden from finalizing any task without providing **concrete evidence** (terminal output, passing tests, compile success, or equivalent proof) that your output works as intended.
|
|
232
|
+
- ✅ **Required:** You are explicitly forbidden from finalizing any task without providing **concrete evidence** (terminal output, passing tests, compile success, or equivalent proof) that your output works as intended.
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
## Pre-Flight Checklist
|
|
236
|
+
- [ ] Have I reviewed the user's specific constraints and requests?
|
|
237
|
+
- [ ] Have I checked the environment for relevant existing implementations?
|
|
238
|
+
|
|
239
|
+
## VBC Protocol (Verification-Before-Completion)
|
|
240
|
+
You MUST verify existing code signatures and variables before attempting to modify or call them. No hallucination is permitted.
|
|
@@ -158,4 +158,12 @@ Review these questions before confirming output:
|
|
|
158
158
|
|
|
159
159
|
**CRITICAL:** You must follow a strict "evidence-based closeout" state machine.
|
|
160
160
|
- ❌ **Forbidden:** Declaring a task complete because the output "looks correct."
|
|
161
|
-
- ✅ **Required:** You are explicitly forbidden from finalizing any task without providing **concrete evidence** (terminal output, passing tests, compile success, or equivalent proof) that your output works as intended.
|
|
161
|
+
- ✅ **Required:** You are explicitly forbidden from finalizing any task without providing **concrete evidence** (terminal output, passing tests, compile success, or equivalent proof) that your output works as intended.
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
## Pre-Flight Checklist
|
|
165
|
+
- [ ] Have I reviewed the user's specific constraints and requests?
|
|
166
|
+
- [ ] Have I checked the environment for relevant existing implementations?
|
|
167
|
+
|
|
168
|
+
## VBC Protocol (Verification-Before-Completion)
|
|
169
|
+
You MUST verify existing code signatures and variables before attempting to modify or call them. No hallucination is permitted.
|
|
@@ -334,4 +334,12 @@ Review these questions before confirming output:
|
|
|
334
334
|
|
|
335
335
|
**CRITICAL:** You must follow a strict "evidence-based closeout" state machine.
|
|
336
336
|
- ❌ **Forbidden:** Declaring a task complete because the output "looks correct."
|
|
337
|
-
- ✅ **Required:** You are explicitly forbidden from finalizing any task without providing **concrete evidence** (terminal output, passing tests, compile success, or equivalent proof) that your output works as intended.
|
|
337
|
+
- ✅ **Required:** You are explicitly forbidden from finalizing any task without providing **concrete evidence** (terminal output, passing tests, compile success, or equivalent proof) that your output works as intended.
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
## Pre-Flight Checklist
|
|
341
|
+
- [ ] Have I reviewed the user's specific constraints and requests?
|
|
342
|
+
- [ ] Have I checked the environment for relevant existing implementations?
|
|
343
|
+
|
|
344
|
+
## VBC Protocol (Verification-Before-Completion)
|
|
345
|
+
You MUST verify existing code signatures and variables before attempting to modify or call them. No hallucination is permitted.
|
|
@@ -126,4 +126,12 @@ Review these questions before confirming output:
|
|
|
126
126
|
|
|
127
127
|
**CRITICAL:** You must follow a strict "evidence-based closeout" state machine.
|
|
128
128
|
- ❌ **Forbidden:** Declaring a task complete because the output "looks correct."
|
|
129
|
-
- ✅ **Required:** You are explicitly forbidden from finalizing any task without providing **concrete evidence** (terminal output, passing tests, compile success, or equivalent proof) that your output works as intended.
|
|
129
|
+
- ✅ **Required:** You are explicitly forbidden from finalizing any task without providing **concrete evidence** (terminal output, passing tests, compile success, or equivalent proof) that your output works as intended.
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
## Pre-Flight Checklist
|
|
133
|
+
- [ ] Have I reviewed the user's specific constraints and requests?
|
|
134
|
+
- [ ] Have I checked the environment for relevant existing implementations?
|
|
135
|
+
|
|
136
|
+
## VBC Protocol (Verification-Before-Completion)
|
|
137
|
+
You MUST verify existing code signatures and variables before attempting to modify or call them. No hallucination is permitted.
|
|
@@ -268,4 +268,12 @@ Review these questions before confirming output:
|
|
|
268
268
|
|
|
269
269
|
**CRITICAL:** You must follow a strict "evidence-based closeout" state machine.
|
|
270
270
|
- ❌ **Forbidden:** Declaring a task complete because the output "looks correct."
|
|
271
|
-
- ✅ **Required:** You are explicitly forbidden from finalizing any task without providing **concrete evidence** (terminal output, passing tests, compile success, or equivalent proof) that your output works as intended.
|
|
271
|
+
- ✅ **Required:** You are explicitly forbidden from finalizing any task without providing **concrete evidence** (terminal output, passing tests, compile success, or equivalent proof) that your output works as intended.
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
## Pre-Flight Checklist
|
|
275
|
+
- [ ] Have I reviewed the user's specific constraints and requests?
|
|
276
|
+
- [ ] Have I checked the environment for relevant existing implementations?
|
|
277
|
+
|
|
278
|
+
## VBC Protocol (Verification-Before-Completion)
|
|
279
|
+
You MUST verify existing code signatures and variables before attempting to modify or call them. No hallucination is permitted.
|
|
@@ -170,4 +170,12 @@ Review these questions before confirming output:
|
|
|
170
170
|
|
|
171
171
|
**CRITICAL:** You must follow a strict "evidence-based closeout" state machine.
|
|
172
172
|
- ❌ **Forbidden:** Declaring a task complete because the output "looks correct."
|
|
173
|
-
- ✅ **Required:** You are explicitly forbidden from finalizing any task without providing **concrete evidence** (terminal output, passing tests, compile success, or equivalent proof) that your output works as intended.
|
|
173
|
+
- ✅ **Required:** You are explicitly forbidden from finalizing any task without providing **concrete evidence** (terminal output, passing tests, compile success, or equivalent proof) that your output works as intended.
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
## Pre-Flight Checklist
|
|
177
|
+
- [ ] Have I reviewed the user's specific constraints and requests?
|
|
178
|
+
- [ ] Have I checked the environment for relevant existing implementations?
|
|
179
|
+
|
|
180
|
+
## VBC Protocol (Verification-Before-Completion)
|
|
181
|
+
You MUST verify existing code signatures and variables before attempting to modify or call them. No hallucination is permitted.
|