0
# Schema Management
1
2
Schema validation, formatting, and development utilities for maintaining clean, valid, and consistent Prisma schema files with comprehensive error checking.
3
4
## Capabilities
5
6
### Schema Formatting
7
8
Format Prisma schema files with consistent styling, proper indentation, and standardized structure.
9
10
```bash { .api }
11
/**
12
* Format Prisma schema files with consistent styling
13
* Applies standard formatting rules and validates syntax
14
*/
15
prisma format [options]
16
17
Options:
18
--schema <path> Schema file path (default: ./prisma/schema.prisma)
19
--check Check formatting without modifying files
20
--help/-h Show format command help
21
```
22
23
**Usage Examples:**
24
25
```bash
26
# Format default schema file
27
prisma format
28
29
# Format custom schema location
30
prisma format --schema ./custom/schema.prisma
31
32
# Check formatting without making changes
33
prisma format --check
34
35
# Format multiple schemas in CI/CD
36
find . -name "*.prisma" -exec prisma format --schema {} \;
37
```
38
39
**Formatting Rules Applied:**
40
41
- Consistent indentation (2 spaces)
42
- Proper line spacing between blocks
43
- Standardized attribute ordering
44
- Comment preservation and alignment
45
- Field type alignment
46
- Relation attribute formatting
47
48
**Before/After Example:**
49
50
```prisma
51
// Before formatting
52
model User{
53
id Int @id @default(autoincrement())
54
email String@unique
55
name String?
56
posts Post[]
57
}
58
59
// After formatting
60
model User {
61
id Int @id @default(autoincrement())
62
email String @unique
63
name String?
64
posts Post[]
65
}
66
```
67
68
### Schema Validation
69
70
Validate Prisma schema syntax, configuration, and database compatibility with comprehensive error reporting.
71
72
```bash { .api }
73
/**
74
* Validate Prisma schema syntax and configuration
75
* Checks schema validity, database compatibility, and configuration
76
*/
77
prisma validate [options]
78
79
Options:
80
--schema <path> Schema file path (default: ./prisma/schema.prisma)
81
--config <path> Configuration file path
82
--help/-h Show validate command help
83
```
84
85
**Usage Examples:**
86
87
```bash
88
# Validate default schema
89
prisma validate
90
91
# Validate custom schema location
92
prisma validate --schema ./custom/schema.prisma
93
94
# Validate with custom configuration
95
prisma validate --config ./prisma/config.json
96
97
# Validate in CI/CD pipeline
98
prisma validate && echo "Schema is valid"
99
```
100
101
**Validation Checks:**
102
103
- **Syntax Validation**: Proper Prisma schema language syntax
104
- **Type Checking**: Valid field types and attribute usage
105
- **Relation Validation**: Correct relationship definitions
106
- **Database Compatibility**: Provider-specific feature compatibility
107
- **Configuration Validation**: Valid generator and datasource configurations
108
- **Constraint Validation**: Database constraint compatibility
109
- **Naming Validation**: Valid model and field naming conventions
110
111
### Format Checking
112
113
Check schema formatting without making modifications, useful for CI/CD and code review processes.
114
115
```bash { .api }
116
/**
117
* Check schema formatting without modifying files
118
* Returns exit code indicating whether formatting is needed
119
*/
120
prisma format --check [options]
121
122
Exit Codes:
123
0: Schema is properly formatted
124
1: Schema needs formatting or has syntax errors
125
```
126
127
**CI/CD Integration:**
128
129
```bash
130
# Check formatting in CI pipeline
131
if prisma format --check; then
132
echo "Schema formatting is valid"
133
else
134
echo "Schema needs formatting" >&2
135
exit 1
136
fi
137
```
138
139
**Usage in Pre-commit Hooks:**
140
141
```bash
142
# .git/hooks/pre-commit
143
#!/bin/bash
144
prisma format --check || {
145
echo "Please run 'prisma format' before committing"
146
exit 1
147
}
148
```
149
150
## Schema Development Workflows
151
152
### Development Formatting Workflow
153
154
```bash
155
# Development cycle with formatting
156
# 1. Modify schema
157
vim prisma/schema.prisma
158
159
# 2. Format schema
160
prisma format
161
162
# 3. Validate schema
163
prisma validate
164
165
# 4. Generate client
166
prisma generate
167
```
168
169
### Team Collaboration Workflow
170
171
```bash
172
# Before committing changes
173
prisma format # Format schema
174
prisma validate # Validate schema
175
git add prisma/schema.prisma # Stage formatted schema
176
git commit -m "Update schema" # Commit changes
177
```
178
179
### Multi-Schema Project Management
180
181
```bash
182
# Format multiple schema files
183
prisma format --schema ./apps/api/prisma/schema.prisma
184
prisma format --schema ./apps/admin/prisma/schema.prisma
185
186
# Validate all schemas
187
find . -name "schema.prisma" -exec prisma validate --schema {} \;
188
```
189
190
## Advanced Schema Management
191
192
### Schema File Organization
193
194
```prisma
195
// Well-organized schema structure
196
generator client {
197
provider = "prisma-client-js"
198
output = "../generated/client"
199
}
200
201
datasource db {
202
provider = "postgresql"
203
url = env("DATABASE_URL")
204
}
205
206
// Enums first
207
enum UserRole {
208
ADMIN
209
USER
210
MODERATOR
211
}
212
213
// Base models
214
model User {
215
id Int @id @default(autoincrement())
216
email String @unique
217
name String?
218
role UserRole @default(USER)
219
createdAt DateTime @default(now())
220
updatedAt DateTime @updatedAt
221
222
// Relations
223
posts Post[]
224
profile Profile?
225
226
@@map("users")
227
}
228
229
// Related models
230
model Profile {
231
id Int @id @default(autoincrement())
232
bio String?
233
avatar String?
234
userId Int @unique
235
user User @relation(fields: [userId], references: [id])
236
237
@@map("profiles")
238
}
239
```
240
241
### Schema Validation Rules
242
243
```prisma
244
// Valid schema patterns
245
model Product {
246
id Int @id @default(autoincrement())
247
name String @db.VarChar(255)
248
price Decimal @db.Decimal(10, 2)
249
inStock Boolean @default(true)
250
categoryId Int?
251
createdAt DateTime @default(now())
252
updatedAt DateTime @updatedAt
253
254
// Proper relation definition
255
category Category? @relation(fields: [categoryId], references: [id])
256
orderItems OrderItem[]
257
258
// Proper indexes
259
@@index([categoryId])
260
@@index([createdAt])
261
@@map("products")
262
}
263
```
264
265
### Configuration Validation
266
267
```prisma
268
// Valid generator configuration
269
generator client {
270
provider = "prisma-client-js"
271
output = "./generated/client"
272
previewFeatures = ["jsonProtocol", "metrics"]
273
binaryTargets = ["native", "linux-musl"]
274
}
275
276
// Valid datasource configuration
277
datasource db {
278
provider = "postgresql"
279
url = env("DATABASE_URL")
280
directUrl = env("DIRECT_URL")
281
relationMode = "foreignKeys"
282
}
283
```
284
285
## Error Handling and Debugging
286
287
### Common Validation Errors
288
289
**Syntax Errors:**
290
291
```bash
292
$ prisma validate
293
Error: Schema parsing failed:
294
--> schema.prisma:15:3
295
|
296
15 | posts Post[]
297
| ^^^^^ Type "Post" referenced but not defined
298
```
299
300
**Type Errors:**
301
302
```bash
303
Error: Relation field "posts" must specify both `fields` and `references`
304
or be a list and have a back-relation field with both `fields` and `references`.
305
```
306
307
**Database Compatibility:**
308
309
```bash
310
Error: The preview feature "extendedWhereUnique" is not supported
311
with the current database provider "sqlite".
312
```
313
314
### Formatting Issues
315
316
**Formatting Check Output:**
317
318
```bash
319
$ prisma format --check
320
The following files are not formatted:
321
- prisma/schema.prisma
322
323
Run 'prisma format' to fix formatting issues.
324
```
325
326
**Auto-fixing Common Issues:**
327
328
```bash
329
# Fix formatting automatically
330
prisma format
331
332
# Validate after formatting
333
prisma validate
334
```
335
336
## Integration Patterns
337
338
### Editor Integration
339
340
```json
341
// VS Code settings.json
342
{
343
"prisma.format.enable": true,
344
"editor.formatOnSave": true,
345
"[prisma]": {
346
"editor.defaultFormatter": "Prisma.prisma"
347
}
348
}
349
```
350
351
### Git Hooks Integration
352
353
```bash
354
# .husky/pre-commit
355
#!/bin/sh
356
. "$(dirname "$0")/_/husky.sh"
357
358
# Format and validate schema
359
prisma format
360
prisma validate
361
362
# Add formatted schema to commit
363
git add prisma/schema.prisma
364
```
365
366
### CI/CD Pipeline Integration
367
368
```yaml
369
# GitHub Actions workflow
370
name: Schema Validation
371
on: [push, pull_request]
372
373
jobs:
374
validate-schema:
375
runs-on: ubuntu-latest
376
steps:
377
- uses: actions/checkout@v4
378
379
- name: Setup Node.js
380
uses: actions/setup-node@v4
381
with:
382
node-version: 18
383
384
- name: Install dependencies
385
run: npm ci
386
387
- name: Check schema formatting
388
run: prisma format --check
389
390
- name: Validate schema
391
run: prisma validate
392
```
393
394
### Docker Integration
395
396
```dockerfile
397
# Dockerfile with schema validation
398
FROM node:18-alpine
399
COPY . .
400
RUN npm install
401
402
# Validate schema during build
403
RUN npx prisma validate
404
405
# Format schema and build
406
RUN npx prisma format
407
RUN npx prisma generate
408
```
409
410
## Automated Schema Management
411
412
### Format on Save
413
414
```typescript
415
// VS Code extension configuration
416
{
417
"prisma.format.enable": true,
418
"editor.codeActionsOnSave": {
419
"source.format.prisma": true
420
}
421
}
422
```
423
424
### Batch Processing
425
426
```bash
427
# Script for batch schema management
428
#!/bin/bash
429
for schema in $(find . -name "*.prisma"); do
430
echo "Processing $schema"
431
prisma format --schema "$schema"
432
prisma validate --schema "$schema"
433
done
434
```
435
436
### Quality Gates
437
438
```bash
439
# Quality gate script
440
#!/bin/bash
441
set -e
442
443
echo "Checking schema formatting..."
444
prisma format --check || {
445
echo "Schema formatting check failed"
446
exit 1
447
}
448
449
echo "Validating schema..."
450
prisma validate || {
451
echo "Schema validation failed"
452
exit 1
453
}
454
455
echo "All schema checks passed!"
456
```
457
458
## Best Practices
459
460
### Schema Organization
461
462
- **Consistent Formatting**: Always use `prisma format`
463
- **Logical Grouping**: Group related models together
464
- **Clear Naming**: Use descriptive model and field names
465
- **Comment Usage**: Add comments for complex business logic
466
- **Index Strategy**: Define appropriate database indexes
467
468
### Development Workflow
469
470
- **Format Before Commit**: Always format schemas before committing
471
- **Validate Regularly**: Run validation during development
472
- **Team Standards**: Establish team formatting conventions
473
- **CI Integration**: Include validation in CI/CD pipelines
474
- **Documentation**: Keep schema documentation up to date
475
476
### Error Prevention
477
478
- **Regular Validation**: Validate schemas frequently during development
479
- **Type Safety**: Use proper Prisma types and attributes
480
- **Relation Integrity**: Ensure correct relationship definitions
481
- **Provider Compatibility**: Check database provider compatibility
482
- **Preview Features**: Use preview features cautiously in production