agents-templated 2.2.1 → 2.2.3
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/package.json +1 -1
- package/templates/.claude/rules/ai-integration.mdc +60 -0
- package/templates/.claude/rules/core.mdc +180 -0
- package/templates/.claude/rules/database.mdc +291 -0
- package/templates/.claude/rules/frontend.mdc +224 -0
- package/templates/.claude/rules/guardrails.mdc +105 -0
- package/templates/.claude/rules/hardening.mdc +58 -0
- package/templates/.claude/rules/intent-routing.mdc +59 -0
- package/templates/.claude/rules/planning.mdc +75 -0
- package/templates/.claude/rules/security.mdc +286 -0
- package/templates/.claude/rules/style.mdc +306 -0
- package/templates/.claude/rules/system-workflow.mdc +69 -0
- package/templates/.claude/rules/testing.mdc +308 -0
- package/templates/.claude/rules/workflows.mdc +61 -0
- package/templates/CLAUDE.md +27 -27
- package/templates/agents/rules/ai-integration.mdc +10 -2
- package/templates/agents/rules/core.mdc +8 -1
- package/templates/agents/rules/database.mdc +10 -2
- package/templates/agents/rules/frontend.mdc +10 -2
- package/templates/agents/rules/guardrails.mdc +10 -2
- package/templates/agents/rules/hardening.mdc +10 -2
- package/templates/agents/rules/intent-routing.mdc +10 -2
- package/templates/agents/rules/planning.mdc +10 -2
- package/templates/agents/rules/security.mdc +11 -2
- package/templates/agents/rules/style.mdc +10 -2
- package/templates/agents/rules/system-workflow.mdc +10 -2
- package/templates/agents/rules/testing.mdc +9 -1
- package/templates/agents/rules/workflows.mdc +10 -2
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "agents-templated",
|
|
3
|
-
"version": "2.2.
|
|
3
|
+
"version": "2.2.3",
|
|
4
4
|
"description": "Technology-agnostic development template with multi-AI agent support (Cursor, Copilot, VSCode, Gemini), security-first patterns, and comprehensive testing guidelines",
|
|
5
5
|
"main": "index.js",
|
|
6
6
|
"bin": {
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: "AI / LLM Integration"
|
|
3
|
+
description: "Apply when integrating LLMs, RAG pipelines, prompt engineering, or working with AI-powered features"
|
|
4
|
+
version: "1.0.0"
|
|
5
|
+
tags: ["ai", "llm", "openai", "anthropic", "rag", "prompt-engineering", "safety"]
|
|
6
|
+
alwaysApply: false
|
|
7
|
+
globs: ["**/*llm*", "**/*openai*", "**/*anthropic*", "**/*langchain*", "**/*rag*", "**/ai/**"]
|
|
8
|
+
triggers:
|
|
9
|
+
- "Integrating OpenAI, Claude, or other LLM APIs"
|
|
10
|
+
- "Building RAG (Retrieval-Augmented Generation) pipeline"
|
|
11
|
+
- "Engineering prompts or prompt chains"
|
|
12
|
+
- "Implementing LLM-powered features"
|
|
13
|
+
- "Evaluating LLM outputs or quality"
|
|
14
|
+
---
|
|
15
|
+
|
|
16
|
+
## Purpose
|
|
17
|
+
|
|
18
|
+
Govern LLM integrations safely: prevent prompt injection, enforce cost boundaries, define fallback behavior, and ensure model outputs are validated before use in any user-facing or downstream context.
|
|
19
|
+
|
|
20
|
+
## Security Requirements
|
|
21
|
+
|
|
22
|
+
1. **Prompt injection prevention** — Never interpolate raw user input directly into system prompts. Delimit user content explicitly (e.g., `<user_input>…</user_input>` tags or equivalent structural separation).
|
|
23
|
+
2. **Output validation** — Treat all LLM outputs as untrusted data. Validate schema, sanitize before rendering in UI, and never execute LLM-generated code without a human or automated review gate.
|
|
24
|
+
3. **Secret isolation** — API keys must live in environment variables only. Never log full request/response payloads that may contain sensitive user data.
|
|
25
|
+
4. **Rate limiting** — Apply per-user and global rate limits on all LLM-backed endpoints to prevent abuse and runaway costs.
|
|
26
|
+
|
|
27
|
+
## Cost Controls
|
|
28
|
+
|
|
29
|
+
- Set explicit `max_tokens` on every API call — never rely on model defaults.
|
|
30
|
+
- Log token usage per request; alert on anomalies (> 2× rolling baseline).
|
|
31
|
+
- Prefer streaming for long generations to enable early cancellation.
|
|
32
|
+
- Use smaller/cheaper models for classification, routing, or validation tasks; reserve large models for generation.
|
|
33
|
+
|
|
34
|
+
## Model Selection
|
|
35
|
+
|
|
36
|
+
| Task | Preferred approach |
|
|
37
|
+
|------|--------------------|
|
|
38
|
+
| Classification / intent detection | Small fast model or fine-tuned classifier |
|
|
39
|
+
| Retrieval-augmented generation | Embed → retrieve → generate pipeline |
|
|
40
|
+
| Code generation | Model with strong code benchmarks; always review output |
|
|
41
|
+
| Summarization | Mid-tier model with explicit length constraints |
|
|
42
|
+
| Production generation | Model with provider SLA; never experimental endpoints in prod |
|
|
43
|
+
|
|
44
|
+
## Fallback & Reliability
|
|
45
|
+
|
|
46
|
+
- Every LLM call must have a timeout and retry with exponential backoff (max 3 retries).
|
|
47
|
+
- Define a graceful degradation path for every LLM-powered feature (static response, cached answer, or user-facing degradation message).
|
|
48
|
+
- Do not block critical user flows on LLM availability.
|
|
49
|
+
|
|
50
|
+
## RAG Pipeline Rules
|
|
51
|
+
|
|
52
|
+
- Chunk documents at semantic boundaries (paragraph, section), not arbitrary byte offsets.
|
|
53
|
+
- Score retrieved chunks; discard chunks below relevance threshold before injecting into prompt.
|
|
54
|
+
- Cite sources in output when content is retrieved — never present retrieved facts as model-generated knowledge.
|
|
55
|
+
|
|
56
|
+
## Evaluation Requirements
|
|
57
|
+
|
|
58
|
+
- New LLM features must include an evaluation suite before production: minimum 20 representative examples with expected outputs.
|
|
59
|
+
- Track: accuracy, latency (p50/p95), token cost per request, failure rate.
|
|
60
|
+
- Accuracy regressions > 5% block promotion to production.
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: "Core Project Guidelines"
|
|
3
|
+
description: "Apply to all architecture, type safety, code organization, and enterprise quality standards. Foundation for every feature"
|
|
4
|
+
alwaysApply: true
|
|
5
|
+
version: "3.0.0"
|
|
6
|
+
tags: ["architecture", "core", "enterprise", "technology-agnostic"]
|
|
7
|
+
globs:
|
|
8
|
+
- "*"
|
|
9
|
+
triggers:
|
|
10
|
+
- "Designing application architecture"
|
|
11
|
+
- "Setting up new project or module"
|
|
12
|
+
- "Defining type systems and validation"
|
|
13
|
+
- "Organizing code structure"
|
|
14
|
+
- "Improving code quality standards"
|
|
15
|
+
- "Making testing or performance decisions"
|
|
16
|
+
---
|
|
17
|
+
|
|
18
|
+
## Developer Identity
|
|
19
|
+
|
|
20
|
+
- The AI assistant should provide clear, step-by-step solutions
|
|
21
|
+
- Focus on security-first thinking in all recommendations
|
|
22
|
+
- Provide concise but comprehensive instructions
|
|
23
|
+
- Adapt all patterns to the chosen technology stack
|
|
24
|
+
|
|
25
|
+
## Architecture Principles
|
|
26
|
+
|
|
27
|
+
### Security-First Development
|
|
28
|
+
- **Validate all inputs** at application boundaries with appropriate validation libraries
|
|
29
|
+
- **Authenticate and authorize** every protected endpoint with secure session management
|
|
30
|
+
- **Rate limit** public endpoints to prevent abuse and DoS attacks
|
|
31
|
+
- **Sanitize outputs** to prevent injection attacks and data leaks
|
|
32
|
+
- **Use encryption** for sensitive data in transit and at rest
|
|
33
|
+
- **Log security events** appropriately without exposing sensitive information
|
|
34
|
+
|
|
35
|
+
### Performance-Focused
|
|
36
|
+
- **Optimize asset delivery** with compression, caching, and lazy loading
|
|
37
|
+
- **Monitor performance metrics** specific to your platform (Web Vitals, response times, etc.)
|
|
38
|
+
- **Implement appropriate caching strategies** for your data freshness requirements
|
|
39
|
+
- **Optimize critical paths** - database queries, API responses, asset loading
|
|
40
|
+
- **Profile and benchmark** before and after optimization changes
|
|
41
|
+
|
|
42
|
+
### Type Safety & Validation
|
|
43
|
+
- **Use strong typing systems** available in your chosen language
|
|
44
|
+
- **Implement runtime validation** for all external/user-provided data
|
|
45
|
+
- **Validate at boundaries** - API endpoints, form submissions, configuration
|
|
46
|
+
- **Document type contracts** between system components
|
|
47
|
+
- **Generate types** from schemas when possible (OpenAPI, GraphQL, database schemas)
|
|
48
|
+
|
|
49
|
+
### Testing Strategy
|
|
50
|
+
- **Unit tests** for business logic and utility functions (80% of test effort)
|
|
51
|
+
- **Integration tests** for API endpoints and data access layers (15% of test effort)
|
|
52
|
+
- **E2E tests** for critical user journeys and workflows (5% of test effort)
|
|
53
|
+
- **Accessibility tests** for all user-facing interfaces
|
|
54
|
+
- **Performance tests** for critical paths and known bottlenecks
|
|
55
|
+
- **Security tests** for authentication, authorization, and validation flows
|
|
56
|
+
|
|
57
|
+
## Code Quality Standards
|
|
58
|
+
|
|
59
|
+
### Architecture & Organization
|
|
60
|
+
- **Feature-based structure** - organize code by business domain, not just technical layer
|
|
61
|
+
- **Separation of concerns** - keep UI, business logic, and data access separate
|
|
62
|
+
- **DRY principle** - don't repeat yourself, extract common patterns
|
|
63
|
+
- **SOLID principles** - single responsibility, open/closed, Liskov substitution, interface segregation, dependency inversion
|
|
64
|
+
- **Consistent naming** conventions throughout the codebase
|
|
65
|
+
|
|
66
|
+
### Code Style
|
|
67
|
+
- **Consistent formatting** with automated tools (prettier, black, gofmt, rustfmt, etc.)
|
|
68
|
+
- **Linting rules** enforced via pre-commit hooks or CI/CD
|
|
69
|
+
- **Clear comments** for complex logic, architectural decisions, and gotchas
|
|
70
|
+
- **Self-documenting code** with meaningful variable and function names
|
|
71
|
+
- **No magic numbers** - extract constants with descriptive names
|
|
72
|
+
|
|
73
|
+
### Component/Module Standards (Framework-Specific)
|
|
74
|
+
- **Single responsibility** - each component/module should have one clear purpose
|
|
75
|
+
- **Reusable units** - build components/modules that can be used in multiple places
|
|
76
|
+
- **Proper error handling** for production resilience
|
|
77
|
+
- **Accessibility attributes** included for user-facing components
|
|
78
|
+
- **Proper documentation** of public APIs and interfaces
|
|
79
|
+
|
|
80
|
+
### Database Standards
|
|
81
|
+
- **Choose ONE approach** and maintain consistency (SQL with ORM, NoSQL, managed service, etc.)
|
|
82
|
+
- **Schema migrations only** for schema changes (never manual database edits in production)
|
|
83
|
+
- **ORM/ODM patterns** to prevent injection attacks (no raw SQL unless performance-critical)
|
|
84
|
+
- **Connection pooling** for all production deployments
|
|
85
|
+
- **Audit logs** for sensitive data operations
|
|
86
|
+
- **Proper indexing** to prevent N+1 query problems
|
|
87
|
+
|
|
88
|
+
## Development Workflow
|
|
89
|
+
|
|
90
|
+
### Quality Gates
|
|
91
|
+
- **Automated formatting** checks before code submission
|
|
92
|
+
- **Type checking** must pass (strict mode where available)
|
|
93
|
+
- **Linting** must pass with zero critical violations
|
|
94
|
+
- **Unit tests** must pass with adequate coverage (>80% for business logic)
|
|
95
|
+
- **Integration tests** must pass for API and data layer changes
|
|
96
|
+
- **Security scans** must pass without high-severity issues
|
|
97
|
+
- **Code review** approval required before merging
|
|
98
|
+
|
|
99
|
+
### Environment Management
|
|
100
|
+
- **Environment variables** with runtime validation at startup
|
|
101
|
+
- **Secrets management** never in code, version control, or logs
|
|
102
|
+
- **Database migrations** applied consistently across environments
|
|
103
|
+
- **Feature flags** for gradual rollouts and A/B testing
|
|
104
|
+
- **Health checks** for deployment validation and monitoring
|
|
105
|
+
|
|
106
|
+
### Performance Standards
|
|
107
|
+
- **Monitor resource usage** - memory, CPU, disk, network
|
|
108
|
+
- **Track performance metrics** specific to your platform
|
|
109
|
+
- **Profile critical paths** regularly to identify bottlenecks
|
|
110
|
+
- **Implement caching** appropriately for your use case
|
|
111
|
+
- **Alert on regressions** when performance degrades
|
|
112
|
+
|
|
113
|
+
## Technology Stack Selection
|
|
114
|
+
|
|
115
|
+
This template is technology-agnostic. Choose your stack based on:
|
|
116
|
+
- **Team expertise** and preferred languages/frameworks
|
|
117
|
+
- **Project requirements** - performance needs, scalability, real-time features
|
|
118
|
+
- **Deployment environment** - cloud platform, container requirements, resources
|
|
119
|
+
- **Time constraints** - rapid prototyping vs. long-term maintenance
|
|
120
|
+
|
|
121
|
+
### Frontend Tiers
|
|
122
|
+
- **Full-stack frameworks**: Next.js, Nuxt, SvelteKit, Remix
|
|
123
|
+
- **Component libraries**: React, Vue, Angular, Svelte, Solid
|
|
124
|
+
- **Traditional**: Server-side rendering with templates (Django, Rails, Laravel)
|
|
125
|
+
- **Mobile-first**: React Native, Flutter, Kotlin, Swift
|
|
126
|
+
|
|
127
|
+
### Backend Tiers
|
|
128
|
+
- **Node.js**: Express, Fastify, NestJS, Koa
|
|
129
|
+
- **Python**: Django, FastAPI, Flask
|
|
130
|
+
- **Go**: Gin, Echo, Fiber
|
|
131
|
+
- **Rust**: Actix-web, Axum, Rocket
|
|
132
|
+
- **Java**: Spring Boot, Quarkus, Ktor
|
|
133
|
+
- **Other**: Ruby on Rails, C#/.NET, PHP, etc.
|
|
134
|
+
|
|
135
|
+
### Database Tiers
|
|
136
|
+
- **SQL**: PostgreSQL, MySQL, SQLite, SQL Server
|
|
137
|
+
- **NoSQL**: MongoDB, DynamoDB, CouchDB, Firestore
|
|
138
|
+
- **Cloud-native**: Supabase, Firebase, AWS RDS, Azure SQL
|
|
139
|
+
- **Search**: Elasticsearch, Meilisearch, Algolia
|
|
140
|
+
|
|
141
|
+
### Authentication
|
|
142
|
+
- **Self-managed**: Custom implementation with JWT, sessions, or cookies
|
|
143
|
+
- **Framework-integrated**: NextAuth, Passport, Django's auth system
|
|
144
|
+
- **SaaS**: Auth0, Firebase Auth, AWS Cognito, Supabase Auth
|
|
145
|
+
|
|
146
|
+
## Maintenance & Evolution
|
|
147
|
+
|
|
148
|
+
### Regular Reviews
|
|
149
|
+
- **Dependency updates** - keep packages current with security patches
|
|
150
|
+
- **Security audits** - regular vulnerability scanning and code review
|
|
151
|
+
- **Performance monitoring** - track metrics and address regressions
|
|
152
|
+
- **Code quality** - refactoring and technical debt management
|
|
153
|
+
- **Documentation** - keep docs current with code changes
|
|
154
|
+
|
|
155
|
+
### Technology Updates
|
|
156
|
+
- **Framework versions** - planned upgrades with migration strategies
|
|
157
|
+
- **Critical patches** - immediate application of security updates
|
|
158
|
+
- **Feature adoption** - stay current with language/framework improvements
|
|
159
|
+
- **Deprecation management** - handle deprecated APIs and patterns
|
|
160
|
+
|
|
161
|
+
## Documentation and Research
|
|
162
|
+
|
|
163
|
+
When deciding what to recommend or implement:
|
|
164
|
+
|
|
165
|
+
- **Local rules** (this file and other `.claude/rules/*.mdc`): Use as the primary source for architecture, security, testing, and style. Follow these when the stack is generic or already covered.
|
|
166
|
+
- **Context7 MCP**: Use for **up-to-date library and framework documentation**. When suggesting or implementing patterns for a specific stack (e.g. Next.js, Express, React), query Context7 (`resolve-library-id` then `query-docs`) so recommendations match current APIs and official guidance.
|
|
167
|
+
- **NotebookLM MCP**: Use for **research and best-practice discourse** (e.g. OWASP, building-systems advice, template design). Query when adding or changing guidelines, or when the audit/planning needs external best practices. Not for real-time API docs—use Context7 for that.
|
|
168
|
+
|
|
169
|
+
## Communication & Collaboration
|
|
170
|
+
|
|
171
|
+
- When providing solutions, be explicit about what to change
|
|
172
|
+
- Show code examples in the language/framework being used
|
|
173
|
+
- Focus on actionable steps, minimize unnecessary explanation
|
|
174
|
+
- Explain security implications of code changes
|
|
175
|
+
- Flag performance implications of design decisions
|
|
176
|
+
|
|
177
|
+
---
|
|
178
|
+
|
|
179
|
+
Remember: This template adapts to **any modern technology stack** while maintaining **enterprise-grade quality standards**.
|
|
180
|
+
Choose your technologies wisely, apply these principles consistently, and keep your codebase maintainable.
|
|
@@ -0,0 +1,291 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: "Database and Data Layer Guidelines"
|
|
3
|
+
description: "Apply when designing schema, building data access layers, running migrations, or optimizing queries"
|
|
4
|
+
alwaysApply: true
|
|
5
|
+
version: "3.0.0"
|
|
6
|
+
tags: ["database", "backend", "data", "orm", "schema"]
|
|
7
|
+
globs:
|
|
8
|
+
- "src/models/**/*"
|
|
9
|
+
- "src/data/**/*"
|
|
10
|
+
triggers:
|
|
11
|
+
- "Designing database schema or tables"
|
|
12
|
+
- "Creating/updating ORM models or queries"
|
|
13
|
+
- "Running database migrations"
|
|
14
|
+
- "Optimizing slow queries"
|
|
15
|
+
- "Selecting database technology"
|
|
16
|
+
- "Implementing access control for data"
|
|
17
|
+
---
|
|
18
|
+
|
|
19
|
+
# Database and Data Layer Guidelines
|
|
20
|
+
|
|
21
|
+
Technology-agnostic patterns for secure, maintainable data access.
|
|
22
|
+
|
|
23
|
+
## Core Principles
|
|
24
|
+
|
|
25
|
+
### Design First
|
|
26
|
+
- **Schema design** - Think through relationships and constraints
|
|
27
|
+
- **Normalization** - Minimize data duplication and anomalies
|
|
28
|
+
- **Scalability** - Design for growth and performance
|
|
29
|
+
- **Consistency** - ACID transactions when needed (SQL) or eventual consistency patterns (NoSQL)
|
|
30
|
+
- **Security** - Access controls at database and application level
|
|
31
|
+
|
|
32
|
+
### Access Patterns
|
|
33
|
+
- **ORM/ODM only** - Use abstraction layer, never raw SQL/queries
|
|
34
|
+
- **Parameterized queries** - Prevent injection attacks
|
|
35
|
+
- **Query optimization** - Avoid N+1 problems and slow queries
|
|
36
|
+
- **Connection pooling** - Manage resources efficiently
|
|
37
|
+
- **Error handling** - Graceful degradation when database unavailable
|
|
38
|
+
|
|
39
|
+
### Migration Strategy
|
|
40
|
+
- **Version control** - All schema changes tracked
|
|
41
|
+
- **Idempotent migrations** - Can run multiple times safely
|
|
42
|
+
- **Reversible migrations** - Can rollback if needed
|
|
43
|
+
- **Testing** - Test migrations in all environments
|
|
44
|
+
- **Documentation** - Document significant schema decisions
|
|
45
|
+
|
|
46
|
+
## Database Strategy Options
|
|
47
|
+
|
|
48
|
+
### SQL Databases (PostgreSQL, MySQL, SQLite, SQL Server)
|
|
49
|
+
|
|
50
|
+
Characteristics:
|
|
51
|
+
- Structured schema with defined tables and relationships
|
|
52
|
+
- ACID transactions for data consistency
|
|
53
|
+
- Powerful querying with SQL
|
|
54
|
+
- Good for relational data
|
|
55
|
+
- Mature tooling and libraries
|
|
56
|
+
|
|
57
|
+
Tools:
|
|
58
|
+
- ORM: Sequelize (Node.js), SQLAlchemy (Python), Hibernate (Java), Entity Framework (.NET)
|
|
59
|
+
- Query Builder: Knex.js (Node.js), SqlAlchemy Core (Python), QueryDSL (Java)
|
|
60
|
+
- Migration tools: Prisma Migrate, Flyway, Liquibase, Alembic
|
|
61
|
+
|
|
62
|
+
Best for:
|
|
63
|
+
- Complex relationships between entities
|
|
64
|
+
- Strong consistency requirements
|
|
65
|
+
- Transactional integrity
|
|
66
|
+
- Complex queries
|
|
67
|
+
- Team comfortable with SQL
|
|
68
|
+
|
|
69
|
+
### NoSQL Databases (MongoDB, DynamoDB, CouchDB, Firestore)
|
|
70
|
+
|
|
71
|
+
Characteristics:
|
|
72
|
+
- Flexible/schemaless documents
|
|
73
|
+
- Eventual consistency
|
|
74
|
+
- Good horizontal scaling
|
|
75
|
+
- Fast for simple lookups
|
|
76
|
+
- Dev-friendly for rapid iteration
|
|
77
|
+
|
|
78
|
+
Tools:
|
|
79
|
+
- ODM: Mongoose (MongoDB), AWS SDK (DynamoDB), Firebase SDK (Firestore)
|
|
80
|
+
- Schema validation: JSONSchema, Zod, Joi
|
|
81
|
+
|
|
82
|
+
Best for:
|
|
83
|
+
- Flexible/evolving data structures
|
|
84
|
+
- Horizontal scaling
|
|
85
|
+
- Fast document lookups
|
|
86
|
+
- Real-time updates
|
|
87
|
+
- Prototyping and MVPs
|
|
88
|
+
|
|
89
|
+
### Managed Database Services (Supabase, Firebase, AWS RDS)
|
|
90
|
+
|
|
91
|
+
Characteristics:
|
|
92
|
+
- Hosted by cloud provider
|
|
93
|
+
- Automatic backups and scaling
|
|
94
|
+
- Built-in authentication
|
|
95
|
+
- Real-time subscriptions (some)
|
|
96
|
+
- Reduced infrastructure complexity
|
|
97
|
+
|
|
98
|
+
Best for:
|
|
99
|
+
- Rapid prototyping
|
|
100
|
+
- Teams without DevOps expertise
|
|
101
|
+
- Projects needing built-in features
|
|
102
|
+
- Compliance-heavy requirements
|
|
103
|
+
- Teams preferring managed services
|
|
104
|
+
|
|
105
|
+
## Schema Design Patterns
|
|
106
|
+
|
|
107
|
+
### Core Tables/Collections
|
|
108
|
+
|
|
109
|
+
Base entities:
|
|
110
|
+
- **Users**: Authentication and identity data
|
|
111
|
+
- **Roles**: Permission groups
|
|
112
|
+
- **Audit logs**: Track changes for compliance
|
|
113
|
+
|
|
114
|
+
Related data:
|
|
115
|
+
- Define relationships clearly
|
|
116
|
+
- Use appropriate constraints (foreign keys, unique constraints)
|
|
117
|
+
- Add indexes for common queries
|
|
118
|
+
- Document connection between tables
|
|
119
|
+
|
|
120
|
+
### Timestamps
|
|
121
|
+
|
|
122
|
+
Include timestamps:
|
|
123
|
+
- **Created at**: When record created (immutable)
|
|
124
|
+
- **Updated at**: When record last modified
|
|
125
|
+
- **Deleted at**: For soft deletes (when applicable)
|
|
126
|
+
|
|
127
|
+
### IDs and Keys
|
|
128
|
+
|
|
129
|
+
ID strategy:
|
|
130
|
+
- **Primary key**: Uniquely identifies record
|
|
131
|
+
- **Foreign key**: References another table (relational)
|
|
132
|
+
- **Unique constraints**: Prevent duplicates
|
|
133
|
+
- **Non-sequential IDs**: Use UUID or similar for security
|
|
134
|
+
|
|
135
|
+
### Data Validation
|
|
136
|
+
|
|
137
|
+
At database level:
|
|
138
|
+
- Required fields (NOT NULL)
|
|
139
|
+
- Data type constraints
|
|
140
|
+
- Length constraints (for strings)
|
|
141
|
+
- Enum constraints (for limited values)
|
|
142
|
+
- Range constraints (for numbers)
|
|
143
|
+
|
|
144
|
+
At application level:
|
|
145
|
+
- Validate before insert/update
|
|
146
|
+
- Validate format (email, URL, etc.)
|
|
147
|
+
- Validate business rules
|
|
148
|
+
- Return clear error messages
|
|
149
|
+
|
|
150
|
+
## Query Patterns
|
|
151
|
+
|
|
152
|
+
### Efficient Queries
|
|
153
|
+
|
|
154
|
+
Do:
|
|
155
|
+
- Use WHERE clauses to filter
|
|
156
|
+
- Use indexes on filtered fields
|
|
157
|
+
- Use SELECT specific columns
|
|
158
|
+
- Use LIMIT for pagination
|
|
159
|
+
- Use JOIN for related data
|
|
160
|
+
- Use aggregation functions
|
|
161
|
+
- Batch operations when possible
|
|
162
|
+
|
|
163
|
+
Don't:
|
|
164
|
+
- SELECT * (select all columns)
|
|
165
|
+
- N+1 queries (query in loop)
|
|
166
|
+
- Unindexed large scans
|
|
167
|
+
- Complex JOINs without indexes
|
|
168
|
+
- Missing WHERE clause
|
|
169
|
+
- Fetching unused data
|
|
170
|
+
|
|
171
|
+
### Pagination
|
|
172
|
+
|
|
173
|
+
Pagination pattern:
|
|
174
|
+
1. Accept limit and offset parameters
|
|
175
|
+
2. Validate reasonable limit (max 100-1000)
|
|
176
|
+
3. Query with LIMIT and OFFSET
|
|
177
|
+
4. Return total count optionally
|
|
178
|
+
5. Include nextPage/previousPage links
|
|
179
|
+
|
|
180
|
+
### Relationships
|
|
181
|
+
|
|
182
|
+
Query related data:
|
|
183
|
+
- One-to-many: JOIN or separate queries
|
|
184
|
+
- Many-to-many: Junction table with JOINs
|
|
185
|
+
- One-to-one: JOIN or embed in document
|
|
186
|
+
- Hierarchical: Recursive queries or denormalization
|
|
187
|
+
|
|
188
|
+
## Security
|
|
189
|
+
|
|
190
|
+
### Access Control
|
|
191
|
+
|
|
192
|
+
Implement at database:
|
|
193
|
+
- Row-level security (RLS in PostgreSQL, Firestore)
|
|
194
|
+
- Column-level access restrictions
|
|
195
|
+
- Database-level user permissions
|
|
196
|
+
|
|
197
|
+
Implement at application:
|
|
198
|
+
- Verify user owns resource before returning
|
|
199
|
+
- Check permissions before allowing modifications
|
|
200
|
+
- Log access to sensitive data
|
|
201
|
+
- Rate limit database operations
|
|
202
|
+
|
|
203
|
+
### Sensitive Data
|
|
204
|
+
|
|
205
|
+
Protect sensitive data:
|
|
206
|
+
- Hash passwords (never store plaintext)
|
|
207
|
+
- Encrypt PII at rest
|
|
208
|
+
- Never log sensitive data
|
|
209
|
+
- Mask sensitive data in backups
|
|
210
|
+
- Use parameterized queries to prevent injection
|
|
211
|
+
|
|
212
|
+
### Backup & Recovery
|
|
213
|
+
|
|
214
|
+
Backup strategy:
|
|
215
|
+
- Automated daily backups
|
|
216
|
+
- Test recovery procedures
|
|
217
|
+
- Retain backups for compliance period
|
|
218
|
+
- Encrypt backups at rest
|
|
219
|
+
- Store backups separately from primary database
|
|
220
|
+
|
|
221
|
+
## Performance
|
|
222
|
+
|
|
223
|
+
### Indexing
|
|
224
|
+
|
|
225
|
+
Index columns that are:
|
|
226
|
+
- Frequently filtered (WHERE clause)
|
|
227
|
+
- Used in JOINs
|
|
228
|
+
- Used in ORDER BY
|
|
229
|
+
- Used in DISTINCT
|
|
230
|
+
|
|
231
|
+
Don't over-index:
|
|
232
|
+
- Too many indexes slow down writes
|
|
233
|
+
- Indexes require storage space
|
|
234
|
+
- Maintain only used indexes
|
|
235
|
+
|
|
236
|
+
### Connection Management
|
|
237
|
+
|
|
238
|
+
Connection pooling:
|
|
239
|
+
- Reuse connections across requests
|
|
240
|
+
- Configure reasonable pool size (10-20 connections)
|
|
241
|
+
- Set idle timeout
|
|
242
|
+
- Monitor connection usage
|
|
243
|
+
- Alert on connection exhaustion
|
|
244
|
+
|
|
245
|
+
### Query Optimization
|
|
246
|
+
|
|
247
|
+
Optimize slow queries:
|
|
248
|
+
1. Profile query execution time
|
|
249
|
+
2. Check execution plan
|
|
250
|
+
3. Add missing indexes
|
|
251
|
+
4. Rewrite queries if needed
|
|
252
|
+
5. Consider denormalization if needed
|
|
253
|
+
6. Verify schema design
|
|
254
|
+
|
|
255
|
+
## Monitoring & Maintenance
|
|
256
|
+
|
|
257
|
+
### Health Checks
|
|
258
|
+
|
|
259
|
+
Monitor:
|
|
260
|
+
- Database connectivity
|
|
261
|
+
- Query performance (slow query logs)
|
|
262
|
+
- Connection pool status
|
|
263
|
+
- Storage space usage
|
|
264
|
+
- Backup completion
|
|
265
|
+
- Replication lag (if applicable)
|
|
266
|
+
|
|
267
|
+
### Database Maintenance
|
|
268
|
+
|
|
269
|
+
Regular tasks:
|
|
270
|
+
- Update statistics/analyze
|
|
271
|
+
- Vacuum/compact (depending on DB)
|
|
272
|
+
- Rebuild indexes if needed
|
|
273
|
+
- Clean up old audit logs
|
|
274
|
+
- Review and optimize slow queries
|
|
275
|
+
|
|
276
|
+
## Testing
|
|
277
|
+
|
|
278
|
+
### Test Data
|
|
279
|
+
|
|
280
|
+
Setup:
|
|
281
|
+
- Use separate test database
|
|
282
|
+
- Reset data before each test
|
|
283
|
+
- Use factories for consistent test data
|
|
284
|
+
- Seed with realistic data
|
|
285
|
+
|
|
286
|
+
Testing patterns:
|
|
287
|
+
- Test CRUD operations
|
|
288
|
+
- Test relationships
|
|
289
|
+
- Test constraints
|
|
290
|
+
- Test error cases
|
|
291
|
+
- Test performance
|