backend-database-and-orm
Guides backend database design, ORM patterns, zero-downtime migrations, and query performance tailored specifically for Neon (Serverless Postgres) and Firebase (Firestore / Auth / Rules). Use when modeling database schemas, writing ORM code, setting up database migrations, optimizing SQL/Firestore queries, or configuring connection pooling.
- License 许可
- MIT
- 最近更新
- 2026-11-05
- Stars
- ★ 0
- Forks
- 0
01 前言 Front Matter
- name
- backend-database-and-orm
- description
- Guides backend database design, ORM patterns, zero-downtime migrations, and query performance tailored specifically for Neon (Serverless Postgres) and Firebase (Firestore / Auth / Rules). Use when modeling database schemas, writing ORM code, setting up database migrations, optimizing SQL/Firestore queries, or configuring connection pooling.
03 SKILL.md 正文
Backend Database & ORM Engineering
Overview
High-performance, scalable backend database design focusing on Neon (Serverless Postgres) and Firebase (Firestore, Security Rules, Admin SDK). Enforces clean data modeling, zero-downtime schema evolution, N+1 query prevention, and safe connection pooling across serverless and stateful environments.
When to Use
- Designing or modifying database schemas (SQL table structures, Firestore collections)
- Writing database queries or using ORMs (Drizzle ORM, Prisma, TypeORM)
- Configuring Neon database connections, WebSocket pooling, or database branching
- Implementing Firebase Firestore queries, Security Rules, or Cloud Functions backend logic
- Executing database migrations in staging or production environments
- Diagnosing database query performance bottlenecks, slow queries, or missing indexes
Pillar 1: Neon (Serverless PostgreSQL)
Neon is a serverless Postgres platform with decoupled compute and storage, instant database branching, and HTTP/WebSocket proxies for serverless environments.
1. Connection Management & Driver Selection
- Serverless Environments (Vercel, AWS Lambda, Cloudflare Workers): Use
@neondatabase/serverlessover WebSockets / HTTP proxy to avoid connection exhaustion.import { Pool, neonConfig } from '@neondatabase/serverless'; import ws from 'ws'; neonConfig.webSocketConstructor = ws; const pool = new Pool({ connectionString: process.env.DATABASE_URL }); - Stateful Long-Running Servers (Node.js / Express): Use standard PostgreSQL connection poolers (e.g.
pg.Pool) with Neon's pooled connection string (-poolersuffix).
2. ORM Patterns (Drizzle ORM & Prisma with Neon)
- Drizzle ORM (Recommended for Light Overhead & Explicit SQL):
- Always explicit select fields instead of returning
SELECT *. - Use relational queries
db.query.users.findMany(...)for structured tree fetches.
- Always explicit select fields instead of returning
- Prisma with Neon:
- Enable
@prisma/adapter-neondriver adapter when running in serverless contexts. - Avoid deeply nested
includestatements that cause wide SQL joins; use explicitselectpayloads.
- Enable
3. Neon Branching Workflow for DB Migrations
- Use Neon's instant copy-on-write branching for dev & staging test environments:
- Branch main database:
neon branches create --name feature-branch - Run migrations against
feature-branch - Verify application queries against
feature-branch - Apply approved migration to
main
- Branch main database:
Pillar 2: Firebase (Firestore, Rules & Functions)
Firebase provides document-based Firestore, real-time sync, identity management, and serverless Cloud Functions.
1. Data Modeling & Firestore Layout
- Normalized vs Denormalized: Firestore charges per document read/write. Prefer denormalizing frequently accessed sub-fields (e.g.
authorNamestored insidepostsdocument) to avoid secondary fetches. - Collection Structures:
- Subcollections for tightly bound sub-resources (
users/{userId}/orders/{orderId}). - Root collections with indexed reference IDs (
orderswithuserIdfield) when cross-user queries are required.
- Subcollections for tightly bound sub-resources (
2. Firestore Security Rules & Access Control
- Never rely solely on client-side checks. Every collection must have explicit
firestore.rules. - Enforce strict data validation & auth checking:
match /users/{userId} { allow read, write: if request.auth != null && request.auth.uid == userId; } match /posts/{postId} { allow read: if resource.data.isPublic == true; allow create: if request.auth != null && request.resource.data.authorId == request.auth.uid; }
3. Query Optimization & Indexing
- Composite Indexes: Any query combining filtering (
where) with sorting (orderBy) across multiple fields requires a composite index infirestore.indexes.json. - Pagination: Always use
limit()combined withstartAfter(lastDoc)for collection pagination. Never fetch entire collections into memory.
Pillar 3: Zero-Downtime Migration Pattern (Expand-Contract)
When changing database schemas in production (especially on Neon Postgres or Firestore schemas), NEVER drop or rename fields in a single breaking deploy. Use the Expand-Contract (Parallel Write) pattern:
Phase 1: Expand ---> Phase 2: Dual Write ---> Phase 3: Backfill ---> Phase 4: Contract
(Add new col/field) (Write to old & new) (Migrate old rows) (Remove old col/field)
- Expand (Deploy 1): Add the new column/field as optional (
NULLablein SQL, optional in Firestore). Existing code continues using the old field. - Dual Write (Deploy 2): Update backend code to write to BOTH old and new fields simultaneously. Read from old field if new field is missing.
- Backfill Script: Run an async background script to update existing rows/documents to populate the new field.
- Read Switch (Deploy 3): Switch read logic to strictly read from the new field.
- Contract (Deploy 4): Remove writes to the old field, drop the old column/field.
Pillar 4: Query Performance & Quality Checklist
- [ ] N+1 Prevention: Are multi-row queries fetching relations in a single join / single batch query instead of looping async calls?
- [ ] Indexing: Are all
WHERE,JOIN, andORDER BYcolumns in Postgres covered by B-Tree or GIN indexes? Are Firestore composite queries defined infirestore.indexes.json? - [ ] Transaction Boundaries: Are multi-statement updates wrapped in explicit SQL transactions (
db.transaction(...)) or Firestore Batched Writes / Transactions? - [ ] Connection Leak Prevention: Are SQL connection pools cleanly shut down on process termination (
SIGTERM)?
04 同仓库更多 Skills
taste-design
Semantic Design System Skill for Google Stitch. Generates agent-friendly DESIGN.md files that enforce premium, anti-generic UI standards — strict typography, calibrated color, asymmetric layouts, perpetual micro-motion, and hardware-accelerated performance.
stitch-loop
Teaches agents to iteratively build websites using Stitch with an autonomous baton-passing loop pattern
site-md
Analyze a project description or site requirements and synthesize a project constitution into SITE.md for the Stitch Build Loop
enhance-prompt
Transforms vague UI ideas into polished, Stitch-optimized prompts. Enhances specificity, adds UI/UX keywords, injects design system context, and structures output for better generation results.
design-md
Analyze Stitch projects and synthesize a semantic design system into DESIGN.md files
stitch::upload-to-stitch
Upload local assets (images, mockups, extracted HTML, design markdown) to a Stitch project. ALWAYS use this skill when you need to upload visual assets, HTML pages, or design docs to Stitch, particularly when direct MCP tool calls fail or truncate due to base64 token limits.