Data Layer Code Implementation
Code Write Boundary
Follow Engineering Boundary Protocol or the equivalent relative path from this skill.
- Scan first: identify framework, package manager, module layout, ORM, migration tool, validation library, auth middleware, and test conventions before implementation.
- Target scope: declare exact files/directories to create or modify; generated code must stay inside the target module unless integration files are explicitly required.
- No overwrite: preserve existing business logic, routes, models, migrations, configs, and tests unless the user explicitly asks for replacement.
- Consistency checks: verify OpenAPI, controller/service signatures, DTO/schema validation, ER model, migrations, repositories, and auth rules are aligned.
- Migration safety: generated migrations must be additive by default; destructive data changes require explicit human confirmation.
- Implementation report: list created/modified files, skipped files, checks run, failed checks, and residual risks.
Core Principles
- Design as Specification: Strictly follow data-architecture-spec outputs, Model fields fully consistent with DDL
- Clear Layering: Models only define data layer structure, API types defined by api-design-impl's types/api.ts
- Cache Alignment: Cache layer code aligned with cache strategy design
- Reversible Migrations: Every Migration script has a corresponding rollback script
- Test Coverage: Every Model and Repository has a test skeleton
Interaction Mode
AI->Human AI suggests, human approves
Input
| Input Item |
Type |
Required |
Source |
Description |
| ER Model |
JSON |
Yes |
output/backend-data-architecture/data-architecture-spec/er_model.json |
Entity relationships and DDL definitions |
| Cache Strategy |
JSON |
Yes |
output/backend-data-architecture/data-architecture-spec/cache_strategy.json |
Cache scheme |
| Migration Plan |
JSON |
O |
output/backend-data-architecture/data-architecture-spec/migration_plan.json |
Migration plan (incremental projects) |
| API Contract |
YAML |
O |
output/backend-api-design/api-design-spec/openapi.yaml |
For API alignment check (empty when API not yet implemented, normal case) |
| Tech Stack Decision |
JSON |
Yes |
output/backend-architecture/backend-architecture-spec/tech_stack_decision.json |
Unified tech stack, including language/ORM/database type |
| project_dir |
string |
Yes |
User provided |
Project root directory absolute path |
| tech_stack |
string |
O |
User provided |
Fallback when tech_stack_decision.json is not available |
Execution Steps
Step 1: Model Code Generation [Core]
Generate data layer entity code based on ER model:
| Generated Content |
Path |
Description |
| Model/Entity |
src/models/ (or entities/) |
One Model file per entity, including field definitions, validation rules, relationships, defining data layer structure only |
| Database Configuration |
src/config/database.ts |
Database connection configuration + connection pool |
Code Quality Requirements:
- Model field types, constraints, default values fully consistent with DDL
- Models only define data layer structure, API types defined by api-design-impl's types/api.ts
Stage Gate: Code compiles (npm run build or tsc --noEmit passes), Model fields consistent with DDL
Step 2: Migration and Seed Data Generation [Core]
Generate migration scripts and seed data based on DDL:
| Generated Content |
Path |
Description |
| Migration Scripts |
src/migrations/ |
Migration scripts for table creation/indexes/seed data |
| Seed Data |
src/seeds/ |
Development environment seed data |
Code Quality Requirements:
- Migration scripts are executable and reversible
- Seed data covers core business entities
Stage Gate: Migrations are executable (verified via npx prisma migrate status or equivalent), 100% have rollback scripts
Step 3: Repository Code Generation [Core]
Generate a Repository for each entity:
| Generated Content |
Path |
Description |
| Repository/DAO |
src/repositories/ (or dao/) |
One Repository per entity, including CRUD operations + common queries |
Code Quality Requirements:
- Repository methods have complete type annotations + error handling
- Query methods cover all API layer data access needs
- Soft delete, pagination, sorting uniformly encapsulated in Repository layer
Stage Gate: Every API data access need has a corresponding Repository method
Step 4: Cache Layer Code Generation [Core]
Generate cache layer code based on cache strategy:
| Generated Content |
Path |
Description |
| Cache Layer |
src/cache/ |
Redis connection configuration, CacheRepository, cache decorators/interceptors |
Code Quality Requirements:
- Cache layer aligned with cache strategy design: hit rate targets, invalidation strategy, penetration/breakdown/avalanche protection
- CacheRepository encapsulates cache read/write logic, Services access data through Repository+CacheRepository
Stage Gate: Cache layer aligned with cache strategy design
Step 5: Alignment Check and Code Self-Review [Core]
API Alignment Check (optional, executed when API contract exists):
- Check each API contract request/response structure one by one, ensuring Model fields cover all API requirements
- Missing fields are marked and automatically supplemented
- When no API contract exists, skip this check, mark "API alignment pending api-design-impl completion, to be verified by backend-architecture-impl unified check"
Code Self-Review:
- Check Model field consistency with DDL
- Check Migration scripts are executable and reversible
- Check cache layer alignment with cache strategy design
- Check Repository queries for N+1 issues
- Check index coverage for high-frequency query scenarios
- Auto-fix discovered issues, P0 issues block output
Stage Gate: Model fields consistent with DDL, code self-review P0 issues=0
Step 6: Data Layer Test Code Generation [Core]
Generate test code for the data layer:
- Generate field validation tests for each Model
- Generate CRUD test skeletons for each Repository
- Generate execution + rollback verification tests for Migrations
- Test files output to src/tests/models/ and src/tests/repositories/
Stage Gate: Every Model and Repository has a test skeleton
Output
Adopts dual output mode:
- Code Files -> Directly written to user-specified
{project_dir}/src/ project directory
- Metadata Files -> Written to
output/ directory for downstream Skill consumption
Code File Output: {project_dir}/src/ (Models, Migrations, Repositories, cache layer, configuration, tests directly written to project directory)
Metadata Output: output/backend-data-architecture/data-architecture-impl/
Metadata Output Files:
- impl-report.json -- Code implementation report (generated file list + alignment check results + self-review results)
impl-report.json Schema:
{
"type": "object",
"required": ["skill_name", "version", "generated_files", "repositories", "alignment_check", "self_audit"],
"properties": {
"skill_name": { "type": "string" },
"version": { "type": "string" },
"generated_files": {
"type": "array",
"items": {
"type": "object",
"required": ["path", "type", "description"],
"properties": {
"path": { "type": "string" },
"type": { "type": "string", "enum": ["model", "migration", "repository", "cache", "config", "seed", "test"] },
"description": { "type": "string" }
}
}
},
"repositories": {
"type": "array",
"description": "Repository list and method signatures, for api-design-impl consumption",
"items": {
"type": "object",
"required": ["name", "entity", "methods"],
"properties": {
"name": { "type": "string" },
"entity": { "type": "string" },
"file_path": { "type": "string" },
"methods": {
"type": "array",
"items": {
"type": "object",
"required": ["name", "return_type"],
"properties": {
"name": { "type": "string" },
"params": { "type": "array", "items": { "type": "object", "properties": { "name": { "type": "string" }, "type": { "type": "string" } } } },
"return_type": { "type": "string" },
"description": { "type": "string" }
}
}
}
}
}
},
"alignment_check": {
"type": "object",
"required": ["passed", "issues"],
"properties": {
"passed": { "type": "boolean" },
"issues": { "type": "array", "items": { "type": "object", "properties": { "severity": { "type": "string", "enum": ["P0", "P1", "P2"] }, "category": { "type": "string" }, "message": { "type": "string" }, "resolution": { "type": "string" } } } }
}
},
"self_audit": {
"type": "object",
"required": ["p0_count", "p1_count", "passed", "items"],
"properties": {
"p0_count": { "type": "integer" },
"p1_count": { "type": "integer" },
"passed": { "type": "boolean" },
"items": { "type": "array", "items": { "type": "object", "properties": { "severity": { "type": "string", "enum": ["P0", "P1", "P2"] }, "check": { "type": "string" }, "result": { "type": "string", "enum": ["pass", "fail", "fixed"] }, "detail": { "type": "string" } } } }
}
}
}
}
Decision Rules
| Condition |
Decision |
| ER model inconsistent with API contract |
Follow ER model, mark differences for human confirmation |
| Cache strategy conflicts with code implementation |
Follow cache strategy, adjust code implementation |
| Code self-review finds P0 issues |
Block output, auto-fix then re-review |
| Repository queries have N+1 issues |
Switch to JOIN or batch queries |
| Tech stack decision conflicts with user specification |
Prefer tech_stack_decision.json (architecture design output), then tech_stack parameter (user direct input), default to Node.js/Prisma. Mark conflicts for human confirmation |
Quality Checks
Degradation Strategy
| Missing Upstream Input |
Degradation Plan |
Output Impact |
| Tech stack decision missing |
Use tech_stack parameter (user provided), default to Node.js/Prisma if absent |
Code style may not match |
| Cache strategy missing |
Do not generate cache layer code |
No cache layer, Services directly access Repository |
| Migration plan missing |
Do not generate migration scripts |
No migration plan |
| API contract missing |
Normal case, generate code based on ER model only, API alignment check degraded to optional |
API field coverage pending api-design-impl completion for verification |
| tech_stack parameter missing |
Default Node.js/Prisma |
Code style may not match |
Upstream Change Response
| Upstream Change |
Impact Scope |
Response Strategy |
| ER model change |
Model+Migration+Repository |
Mark affected code files, assess modification scope |
| Cache strategy change |
Cache layer code |
Update CacheRepository and cache configuration |
| Tech stack decision change |
Tech stack related configuration |
Update ORM configuration and database connection code |
| API contract change |
Repository query methods |
Assess whether new or modified query methods are needed |
| Change Type |
Impact Scope |
Notification Method |
| Repository method signature change |
api-design-impl |
Mark affected Service calls, update repositories field in impl-report.json |
| Model field change |
api-design-impl (mappers.ts) |
Mark affected type conversions, update impl-report.json |
| Cache layer interface change |
api-design-impl, backend-architecture-impl |
Mark affected cache calls, update impl-report.json |
1---2name: data-architecture-impl3description: "Use when generating data layer code. Implements data layer code from data-architecture-spec ER models and table structure designs, generating runnable Models, Migrations, Repositories, and cache layer code to the project directory. Built-in API alignment check and code self-review. Keywords: generate Model code, generate Migration, generate Repository, generate cache code, data layer code generation."4metadata:5 source: https://skillmd.com/skills/luckyonetwothree/data-architecture-impl6 module: "Backend Architecture & Development"7 sub-module: "Data Architecture"8 type: "pipeline"9 version: "5.0"10 trigger_examples:11 - "Generate Model code"12 - "Generate Migration scripts"13 - "Generate Repository code"14 - "Generate cache layer code"15 - "Table creation script generation"16---1718# Data Layer Code Implementation1920## Code Write Boundary2122Follow [Engineering Boundary Protocol](../../../codex-templates/engineering-boundary-protocol.md) or the equivalent relative path from this skill.23241. Scan first: identify framework, package manager, module layout, ORM, migration tool, validation library, auth middleware, and test conventions before implementation.252. Target scope: declare exact files/directories to create or modify; generated code must stay inside the target module unless integration files are explicitly required.263. No overwrite: preserve existing business logic, routes, models, migrations, configs, and tests unless the user explicitly asks for replacement.274. Consistency checks: verify OpenAPI, controller/service signatures, DTO/schema validation, ER model, migrations, repositories, and auth rules are aligned.285. Migration safety: generated migrations must be additive by default; destructive data changes require explicit human confirmation.296. Implementation report: list created/modified files, skipped files, checks run, failed checks, and residual risks.3031## Core Principles32331. **Design as Specification**: Strictly follow data-architecture-spec outputs, Model fields fully consistent with DDL342. **Clear Layering**: Models only define data layer structure, API types defined by api-design-impl's types/api.ts353. **Cache Alignment**: Cache layer code aligned with cache strategy design364. **Reversible Migrations**: Every Migration script has a corresponding rollback script375. **Test Coverage**: Every Model and Repository has a test skeleton3839## Interaction Mode4041AI->Human AI suggests, human approves4243## Input4445| Input Item | Type | Required | Source | Description |46|--------|------|------|------|------|47| ER Model | JSON | Yes | output/backend-data-architecture/data-architecture-spec/er_model.json | Entity relationships and DDL definitions |48| Cache Strategy | JSON | Yes | output/backend-data-architecture/data-architecture-spec/cache_strategy.json | Cache scheme |49| Migration Plan | JSON | O | output/backend-data-architecture/data-architecture-spec/migration_plan.json | Migration plan (incremental projects) |50| API Contract | YAML | O | output/backend-api-design/api-design-spec/openapi.yaml | For API alignment check (empty when API not yet implemented, normal case) |51| Tech Stack Decision | JSON | Yes | output/backend-architecture/backend-architecture-spec/tech_stack_decision.json | Unified tech stack, including language/ORM/database type |52| project_dir | string | Yes | User provided | Project root directory absolute path |53| tech_stack | string | O | User provided | Fallback when tech_stack_decision.json is not available |5455## Execution Steps5657### Step 1: Model Code Generation [Core]5859Generate data layer entity code based on ER model:6061| Generated Content | Path | Description |62|----------|------|------|63| Model/Entity | src/models/ (or entities/) | One Model file per entity, including field definitions, validation rules, relationships, defining data layer structure only |64| Database Configuration | src/config/database.ts | Database connection configuration + connection pool |6566**Code Quality Requirements**:67- Model field types, constraints, default values fully consistent with DDL68- Models only define data layer structure, API types defined by api-design-impl's types/api.ts6970**Stage Gate**: Code compiles (npm run build or tsc --noEmit passes), Model fields consistent with DDL7172### Step 2: Migration and Seed Data Generation [Core]7374Generate migration scripts and seed data based on DDL:7576| Generated Content | Path | Description |77|----------|------|------|78| Migration Scripts | src/migrations/ | Migration scripts for table creation/indexes/seed data |79| Seed Data | src/seeds/ | Development environment seed data |8081**Code Quality Requirements**:82- Migration scripts are executable and reversible83- Seed data covers core business entities8485**Stage Gate**: Migrations are executable (verified via npx prisma migrate status or equivalent), 100% have rollback scripts8687### Step 3: Repository Code Generation [Core]8889Generate a Repository for each entity:9091| Generated Content | Path | Description |92|----------|------|------|93| Repository/DAO | src/repositories/ (or dao/) | One Repository per entity, including CRUD operations + common queries |9495**Code Quality Requirements**:96- Repository methods have complete type annotations + error handling97- Query methods cover all API layer data access needs98- Soft delete, pagination, sorting uniformly encapsulated in Repository layer99100**Stage Gate**: Every API data access need has a corresponding Repository method101102### Step 4: Cache Layer Code Generation [Core]103104Generate cache layer code based on cache strategy:105106| Generated Content | Path | Description |107|----------|------|------|108| Cache Layer | src/cache/ | Redis connection configuration, CacheRepository, cache decorators/interceptors |109110**Code Quality Requirements**:111- Cache layer aligned with cache strategy design: hit rate targets, invalidation strategy, penetration/breakdown/avalanche protection112- CacheRepository encapsulates cache read/write logic, Services access data through Repository+CacheRepository113114**Stage Gate**: Cache layer aligned with cache strategy design115116### Step 5: Alignment Check and Code Self-Review [Core]117118**API Alignment Check** (optional, executed when API contract exists):119- Check each API contract request/response structure one by one, ensuring Model fields cover all API requirements120- Missing fields are marked and automatically supplemented121- When no API contract exists, skip this check, mark "API alignment pending api-design-impl completion, to be verified by backend-architecture-impl unified check"122123**Code Self-Review**:124- Check Model field consistency with DDL125- Check Migration scripts are executable and reversible126- Check cache layer alignment with cache strategy design127- Check Repository queries for N+1 issues128- Check index coverage for high-frequency query scenarios129- Auto-fix discovered issues, P0 issues block output130131**Stage Gate**: Model fields consistent with DDL, code self-review P0 issues=0132133### Step 6: Data Layer Test Code Generation [Core]134135Generate test code for the data layer:136137- Generate field validation tests for each Model138- Generate CRUD test skeletons for each Repository139- Generate execution + rollback verification tests for Migrations140- Test files output to src/__tests__/models/ and src/__tests__/repositories/141142**Stage Gate**: Every Model and Repository has a test skeleton143144## Output145146Adopts **dual output mode**:1471481. **Code Files** -> Directly written to user-specified `{project_dir}/src/` project directory1492. **Metadata Files** -> Written to `output/` directory for downstream Skill consumption150151**Code File Output**: {project_dir}/src/ (Models, Migrations, Repositories, cache layer, configuration, tests directly written to project directory)152153**Metadata Output**: output/backend-data-architecture/data-architecture-impl/154155**Metadata Output Files**:156- impl-report.json -- Code implementation report (generated file list + alignment check results + self-review results)157158**impl-report.json Schema**:159160```json161{162 "type": "object",163 "required": ["skill_name", "version", "generated_files", "repositories", "alignment_check", "self_audit"],164 "properties": {165 "skill_name": { "type": "string" },166 "version": { "type": "string" },167 "generated_files": {168 "type": "array",169 "items": {170 "type": "object",171 "required": ["path", "type", "description"],172 "properties": {173 "path": { "type": "string" },174 "type": { "type": "string", "enum": ["model", "migration", "repository", "cache", "config", "seed", "test"] },175 "description": { "type": "string" }176 }177 }178 },179 "repositories": {180 "type": "array",181 "description": "Repository list and method signatures, for api-design-impl consumption",182 "items": {183 "type": "object",184 "required": ["name", "entity", "methods"],185 "properties": {186 "name": { "type": "string" },187 "entity": { "type": "string" },188 "file_path": { "type": "string" },189 "methods": {190 "type": "array",191 "items": {192 "type": "object",193 "required": ["name", "return_type"],194 "properties": {195 "name": { "type": "string" },196 "params": { "type": "array", "items": { "type": "object", "properties": { "name": { "type": "string" }, "type": { "type": "string" } } } },197 "return_type": { "type": "string" },198 "description": { "type": "string" }199 }200 }201 }202 }203 }204 },205 "alignment_check": {206 "type": "object",207 "required": ["passed", "issues"],208 "properties": {209 "passed": { "type": "boolean" },210 "issues": { "type": "array", "items": { "type": "object", "properties": { "severity": { "type": "string", "enum": ["P0", "P1", "P2"] }, "category": { "type": "string" }, "message": { "type": "string" }, "resolution": { "type": "string" } } } }211 }212 },213 "self_audit": {214 "type": "object",215 "required": ["p0_count", "p1_count", "passed", "items"],216 "properties": {217 "p0_count": { "type": "integer" },218 "p1_count": { "type": "integer" },219 "passed": { "type": "boolean" },220 "items": { "type": "array", "items": { "type": "object", "properties": { "severity": { "type": "string", "enum": ["P0", "P1", "P2"] }, "check": { "type": "string" }, "result": { "type": "string", "enum": ["pass", "fail", "fixed"] }, "detail": { "type": "string" } } } }221 }222 }223 }224}225```226227## Decision Rules228229| Condition | Decision |230|------|------|231| ER model inconsistent with API contract | Follow ER model, mark differences for human confirmation |232| Cache strategy conflicts with code implementation | Follow cache strategy, adjust code implementation |233| Code self-review finds P0 issues | Block output, auto-fix then re-review |234| Repository queries have N+1 issues | Switch to JOIN or batch queries |235| Tech stack decision conflicts with user specification | Prefer tech_stack_decision.json (architecture design output), then tech_stack parameter (user direct input), default to Node.js/Prisma. Mark conflicts for human confirmation |236237## Quality Checks238239- [ ] Code compiles (npm run build or tsc --noEmit passes)240- [ ] Model fields fully consistent with DDL241- [ ] Migration scripts are executable and reversible242- [ ] Every Repository method has type annotations + error handling243- [ ] Soft delete/pagination/sorting uniformly encapsulated244- [ ] Cache layer aligned with cache strategy design245- [ ] Models only define data layer structure, API types defined by api-design-impl's types/api.ts246- [ ] Code self-review P0 issues=0247- [ ] Every Model and Repository has a test skeleton248- [ ] API field coverage (mandatory when API contract exists, mark pending verification when absent)249250## Degradation Strategy251252| Missing Upstream Input | Degradation Plan | Output Impact |253|---------------|---------|---------|254| Tech stack decision missing | Use tech_stack parameter (user provided), default to Node.js/Prisma if absent | Code style may not match |255| Cache strategy missing | Do not generate cache layer code | No cache layer, Services directly access Repository |256| Migration plan missing | Do not generate migration scripts | No migration plan |257| API contract missing | Normal case, generate code based on ER model only, API alignment check degraded to optional | API field coverage pending api-design-impl completion for verification |258| tech_stack parameter missing | Default Node.js/Prisma | Code style may not match |259260## Upstream Change Response261262| Upstream Change | Impact Scope | Response Strategy |263|----------|----------|----------|264| ER model change | Model+Migration+Repository | Mark affected code files, assess modification scope |265| Cache strategy change | Cache layer code | Update CacheRepository and cache configuration |266| Tech stack decision change | Tech stack related configuration | Update ORM configuration and database connection code |267| API contract change | Repository query methods | Assess whether new or modified query methods are needed |268269| Change Type | Impact Scope | Notification Method |270|----------|----------|----------|271| Repository method signature change | api-design-impl | Mark affected Service calls, update repositories field in impl-report.json |272| Model field change | api-design-impl (mappers.ts) | Mark affected type conversions, update impl-report.json |273| Cache layer interface change | api-design-impl, backend-architecture-impl | Mark affected cache calls, update impl-report.json |