Compare commits

...
150 Commits
Author SHA1 Message Date
Rudi bdc864cf94 Working on Standartisation.... #TODO 2026-08-27 18:07:42 +02:00
Rudi da4d67ea47 Added stream API 2026-08-27 17:00:38 +02:00
Rudi 5c9a96357b get song id now returns bookId too 2026-08-27 15:49:45 +02:00
Rudi 7cbbd5466f Bruno file added (API) 2026-08-27 15:49:23 +02:00
Rudi f026db0b68 Merge Konflict
Ist jetzt auf stand von main
2026-08-27 15:18:38 +02:00
Rudi 496a70ffed Update on Songbooksongs number
Number of Song in a Songbook is not number anymore but string
so "3a" would work.
2026-08-27 15:00:04 +02:00
Rudi b060ab29cf API work on SongbookSongs 2026-08-27 14:59:19 +02:00
Rudi 4bdf03426c Work in Songs and Songbooks API 2026-08-27 13:26:50 +02:00
Rudi e1eaea0f17 Added helper file 'checkvars'
In this file comes the code to check the input from the User
e.g. is `id` an integer
2026-08-27 13:26:20 +02:00
robin 941f7aa729 Merge pull request 'Style/adjust receiver page' (#42) from style/adjust-receiver-page into main
Deploy Next.js via Docker / deploy (push) Successful in 1m11s
Reviewed-on: Schanbro/PsalmTafel#42
2026-08-27 09:45:29 +00:00
robin 1088cfd5fd fix: merged conflicts 2026-08-27 11:44:23 +02:00
robin b3870265f6 Merge remote-tracking branch 'Gitea/main' into style/adjust-receiver-page 2026-08-27 11:44:18 +02:00
robin 9c7029bad5 style: adjust receiver page 2026-08-26 15:28:41 +02:00
robin 5afdae2b20 Merge pull request 'Feat/wiki' (#40) from feat/wiki into main
Deploy Next.js via Docker / deploy (push) Successful in 1m2s
Reviewed-on: Schanbro/PsalmTafel#40
2026-08-26 12:47:35 +00:00
robin 59e65e257e Merge branch 'main' into feat/wiki 2026-08-26 12:47:26 +00:00
robin ee6169d948 fix: small issue 2026-08-26 14:46:22 +02:00
robin 9610884703 previous 2026-08-25 12:35:28 +02:00
robin 675c046029 feat: list all wikiPages on the index page 2026-08-25 12:34:47 +02:00
robin 1d34622b39 feat: create wikiIndexPage 2026-08-25 11:54:10 +02:00
robin 9dbbd56664 Merge pull request 'style: adjust Callout style' (#39) from feat/wiki into main
Deploy Next.js via Docker / deploy (push) Successful in 1m14s
Reviewed-on: Schanbro/PsalmTafel#39
2026-08-25 09:49:13 +00:00
robin dba41634ae Merge branch 'main' into feat/wiki 2026-08-25 09:49:08 +00:00
robin 4ebe47e7fa style: adjust Callout style 2026-08-25 11:47:06 +02:00
robin e08ef095e0 Merge pull request 'Feat/wiki' (#38) from feat/wiki into main
Deploy Next.js via Docker / deploy (push) Successful in 5m26s
Reviewed-on: Schanbro/PsalmTafel#38
2026-08-06 15:42:35 +00:00
robin a414f80d0d Merge branch 'main' into feat/wiki 2026-08-06 15:42:26 +00:00
robin 11ebeafdcd chore: wiki: automatic categories 2026-08-06 17:41:37 +02:00
robin 3fc0697db8 chore: wiki: automatic list of all api endpoints 2026-08-06 17:39:51 +02:00
robin 7664d058df chore: wiki: add callout to api wiki page 2026-08-06 16:35:16 +02:00
robin 324e5fca9b chore: wiki: move api wiki to own page 2026-08-06 16:32:43 +02:00
robin 28dc1ce6b1 chore: wiki: add component Article 2026-08-06 16:29:39 +02:00
robin 3c3a4e309a chore: wiki: add API component and add test 2026-08-06 15:02:10 +02:00
robin 91dafe6a06 chore: readme: update installtion wiki link 2026-08-06 14:42:07 +02:00
robin c4f29ef78b Merge pull request 'Feat/wiki' (#37) from feat/wiki into main
Deploy Next.js via Docker / deploy (push) Successful in 3m57s
Reviewed-on: Schanbro/PsalmTafel#37
2026-08-05 10:58:32 +00:00
robin 025ac63275 Merge branch 'main' into feat/wiki 2026-08-05 10:58:15 +00:00
robin e600ba302d feat: wiki: create api page 2026-08-05 12:55:26 +02:00
robin bf8e78d0ba feat: add heading anchor links 2026-08-05 12:52:20 +02:00
robin e403677a71 chore: wiki: add createSongbook 2026-08-05 12:42:27 +02:00
robin 71df1a8384 chore: wiki: add createSong 2026-08-05 12:38:17 +02:00
robin ed2c47aab2 feat: copy button 2026-08-05 12:21:40 +02:00
robin da99471ca5 chore: update wiki 2026-08-05 12:11:52 +02:00
robin 975aba1020 feat: show language on code blocks 2026-08-04 16:12:14 +02:00
robin aee4b8c567 style: adjust style 2026-08-04 16:02:02 +02:00
robin 592b1a158a style: add automatic colors to code 2026-08-04 15:53:13 +02:00
robin 14be41befd fix: fixed html nest issue 2026-08-04 15:40:25 +02:00
robin 3d82ef9671 style: add more components and add test wiki page 2026-08-04 15:37:30 +02:00
robin fd4da2a43f fix: "'article' is possibly 'null'." 2026-08-04 15:32:45 +02:00
robin 18f8496af9 refactor: switched to mdx for better styling 2026-08-04 15:32:04 +02:00
robin 5e78869cbf chore: insert installation and setup wiki 2026-08-04 15:21:48 +02:00
robin 49ed2577ac feat: add own wiki 2026-08-04 15:20:31 +02:00
robin 5f41e47958 chore: install packages for markdown support 2026-08-04 15:06:10 +02:00
robin 9d1fe7e1fc feat: add index page for wiki 2026-08-04 14:56:50 +02:00
robin e3bcb96c4f style: set h1 font-size to 2rem 2026-08-04 14:56:19 +02:00
rudi 66c9dc28fc Some API changes in Song. Added '.trim()' for better string processing 2026-08-03 08:16:55 +02:00
rudi 61f1eb5a2c Fix: Typo
Fehlende klammer
2026-07-31 16:57:18 +02:00
rudi e81e6b5743 Added Status takes from helpermethods
Die Helfermethoden (/lib/db/*) bieten Statuscodes, welche hier übernommen wurden.
2026-07-31 16:00:40 +02:00
rudi 25a253116c Merge remote-tracking branch 'origin/refactor/migration-to-prisma' into refactor/songbook-api-integration 2026-07-31 15:56:46 +02:00
rudi 5ca801e9b4 Added status Codes to SongBook 2026-07-31 15:56:27 +02:00
rudi 31006031f4 Method-name fix 2026-07-31 15:44:18 +02:00
rudi 8b9d47d000 Some Changes 2026-07-31 15:42:49 +02:00
rudi 67888e7f33 Testing the database
Tests der Datenbank hinzugefügt. Alle sind erfolgreich durchgelaufen.
2026-07-31 15:26:48 +02:00
rudi 38c3139403 Merge branch 'refactor/migration-to-prisma' of https://git.schamagusa.de/Schanbro/PsalmTafel into refactor/migration-to-prisma 2026-07-31 15:03:04 +02:00
rudi 3d1448c6aa Some tests and fixes (TODO fixes) 2026-07-31 14:58:40 +02:00
robin ff339fd8e8 Merge pull request 'refactor: updated deplay.yaml action' (#34) from small-fixes into main
Deploy Next.js via Docker / deploy (push) Successful in 39s
Reviewed-on: Schanbro/PsalmTafel#34
2026-07-31 12:43:58 +00:00
robin 63f0835f3b Merge branch 'main' into small-fixes 2026-07-31 12:43:49 +00:00
robin 65aae6af35 refactor: updated deplay.yaml action 2026-07-31 14:42:55 +02:00
robin 670c966868 Merge pull request 'Small fixes' (#33) from small-fixes into main
Deploy Next.js via Docker / deploy (push) Successful in 2m39s
Reviewed-on: Schanbro/PsalmTafel#33
2026-07-31 12:37:05 +00:00
robin e7e73d6882 update version number 2026-07-31 14:36:02 +02:00
robin d2488922e8 fix: fixed typo "talel" to "tafel" 2026-07-31 14:35:36 +02:00
rudi a81ea69a8a Added Statuscodes
Status Rückmeldungen den 'returns' hinzugefügt.
Schanbro/PsalmTafel#30
2026-07-31 13:57:05 +02:00
robin 697ee8d9e3 fix: allow prisma being built 2026-07-31 13:07:48 +02:00
robin 6f15860beb style: move information screen to foreground 2026-07-31 12:49:37 +02:00
rudi 80d88608bd Editeted Doc
Dokumentation über den Funktionen angepasst
2026-07-31 11:56:10 +02:00
rudi 4380669fa3 Added status codes
Status Rückmeldungen den 'returns' hinzugefügt.
Schanbro/PsalmTafel#30
2026-07-31 11:51:08 +02:00
rudi aaedf3a71d Some changes 2026-07-31 11:47:14 +02:00
rudi 6be5cfb974 Added status to return
Status Rückmeldungen den 'returns' hinzugefügt.
Schanbro/PsalmTafel#30
2026-07-31 11:47:03 +02:00
rudi 9d8c7428e6 refactor: /api/songbooks 2026-07-31 11:25:18 +02:00
rudi 69378ca439 Some Route.js changes 2026-07-31 11:15:18 +02:00
rudi cb18b0e14f Added UpdateSongBook 2026-07-31 11:15:03 +02:00
rudi 389fd21975 Correct typo
CreateUser() -> createUser()
2026-07-31 11:14:44 +02:00
rudi d0890347dc AI comments cleanup 2026-07-31 10:46:35 +02:00
rudi df8a768e3e SongBookSongs for connection between tables
Die Verbindung zwischen den Songs und den SongBooks wurde erstellt.
TODO:
- Weitere Functionen implementieren (bei bedarf)
- Testing
2026-07-31 10:39:17 +02:00
rudi 3c20c0a70b Added Delete Function 2026-07-31 10:17:45 +02:00
rudi df169d2943 Paar Verbesserungen 2026-07-31 09:58:59 +02:00
rudi 87a894db1e SongBook Getter & Setter
SongBook Erstellt
2026-07-31 09:58:47 +02:00
rudi b5b5f593f5 Some fixes
Paar verbesserungen und Einheitlichkeiten.
2026-07-31 09:39:02 +02:00
rudi b2545bbdf1 Song Getter & Setter
Ähnlich wie bei user
2026-07-31 09:38:38 +02:00
rudi 8deff3b39f Finished Getter & Setter for User
Die funktionen sollten nun ausreichen für die User. Es muss vielleicht noch 'authorize()' mit JWT-cookies usw angelegt werden. Aber datenbank mäßig funktioniert es jetzt.
2026-07-31 09:07:54 +02:00
rudi 5ff1ca8e3c Comments in english
Änderungen der kommentare (Erklärungen) auf Englisch
2026-07-31 08:33:03 +02:00
rudi d03ff9d26d Some changes in manage.ts --> 3 user.ts, song.ts, songbook.ts
Aufspaltung auf 3 Dateien, aber man muss noch weiter arbeiten

(Task: Von better-sqlite3 --> ORM)
2026-07-30 14:13:02 +02:00
rudi d395308c6d Automatic creation of Admin user (TEST) 2026-07-30 11:57:35 +02:00
rudi 4ccd860814 Database-Layout
Das Datanbankschema wurde an das alte angepasst.
!!Hinzugefügt wurde 'User'!!
2026-07-30 11:48:00 +02:00
rudi 9aa94638d9 Migrated to Prisma
Migrated to the Prisma ORM.
Text TODO: Change code
2026-07-30 11:22:52 +02:00
robin c28a5031f6 refactor: changed to rem 2026-07-30 10:48:34 +02:00
robin 4948946c0d Merge pull request 'add automatic prerelease mark' (#25) from environment into main
Deploy Next.js via Docker / deploy (push) Successful in 2m37s
Reviewed-on: Schanbro/PsalmTafel#25
2026-07-30 08:09:37 +00:00
robin 1ec3bb667d add automatic prerelease mark
release as prerelease if version number starts with "0."
2026-07-30 08:08:25 +00:00
robin 96370fa97a Merge pull request 'Feat dashboard' (#13) from feat-dashboard into main
Deploy Next.js via Docker / deploy (push) Successful in 36s
Reviewed-on: Schanbro/PsalmTafel#13
2026-07-29 11:15:47 +00:00
robin 08b667113b update version number 2026-07-29 13:15:18 +02:00
robin abb451fa47 refactor: update metadata 2026-07-29 12:56:31 +02:00
robin b259f0fbcf Merge pull request 'Main' (#21) from main into feat-dashboard
Reviewed-on: Schanbro/PsalmTafel#21
2026-07-29 10:48:34 +00:00
robin f4c4898c06 Merge pull request 'Feat/admin options' (#14) from feat/admin-options into main
Deploy Next.js via Docker / deploy (push) Successful in 37s
Reviewed-on: Schanbro/PsalmTafel#14
2026-07-28 15:05:03 +00:00
robin cf78d7cea2 feat: add ability to remove song from songbook 2026-07-28 17:03:28 +02:00
robin dc75753f41 feat: add api for removeSongFromSongbook 2026-07-28 16:29:44 +02:00
robin 57ea3907b6 feat: add removeSongFromSongbook to db managing.ts 2026-07-28 16:27:25 +02:00
robin 297b4a9664 Merge branch 'feat/admin-options' of https://git.schamagusa.de/Schanbro/PsalmTafel into feat/admin-options 2026-07-28 16:18:22 +02:00
robin f312217b7c fix: fix typo in admin page 2026-07-28 16:17:20 +02:00
robin fc37aa6e1e Merge branch 'main' into feat/admin-options 2026-07-28 14:16:40 +00:00
robin d8f2235de7 Merge pull request 'Ui-corrections' (#19) from ui-corrections into main
Deploy Next.js via Docker / deploy (push) Successful in 39s
Reviewed-on: Schanbro/PsalmTafel#19
2026-07-28 14:00:39 +00:00
robin e3115df0bd feat: add abilty to attach song to songbook 2026-07-28 15:53:51 +02:00
robin 001a0d6ef8 feat: add API for attachSongToSongbook 2026-07-28 15:40:33 +02:00
robin 8910a1ff05 feat: add attachSongToSongbook to db managing.ts 2026-07-28 15:32:48 +02:00
robin d871bddc99 feat: add api for getSongInfos
feat: show song informations of selected song
2026-07-28 15:00:48 +02:00
robin d6fb6ec16d feat: add getSongInfos to db managing.ts 2026-07-28 14:48:28 +02:00
robin 011f1b6e0b style: rearranged content 2026-07-27 18:50:12 +02:00
robin 5799eee961 style: - 2026-07-27 18:46:36 +02:00
robin f68d9cd9e5 feat: show raw informations about selected song 2026-07-27 18:39:26 +02:00
robin 9b73ce99e7 style: fix margin issue 2026-07-27 18:32:29 +02:00
robin ec9bfce3a7 style: add slate border to the header 2026-07-27 18:26:47 +02:00
robin 089a7fd76b fix: filled children (unimportant) 2026-07-27 17:51:01 +02:00
robin cb1f70e90d Merge pull request 'Main' (#18) from main into feat/admin-options
Reviewed-on: Schanbro/PsalmTafel#18
2026-07-27 15:01:48 +00:00
robin d769273f43 Merge pull request 'Ui corrections' (#17) from ui-corrections into main
Deploy Next.js via Docker / deploy (push) Successful in 32s
Reviewed-on: Schanbro/PsalmTafel#17
2026-07-27 15:01:06 +00:00
robin 4f1686bdfe Merge branch 'main' into ui-corrections 2026-07-27 15:00:57 +00:00
robin 7548429936 remove preview elements 2026-07-27 17:00:11 +02:00
robin cbe0bd6e1d style: redesigned card component 2026-07-27 16:58:41 +02:00
robin 43054e98ad style: add option for left border (unstyled) 2026-07-27 16:50:49 +02:00
robin 3064112595 style: changed arrangement of elements in admin 2026-07-27 16:39:00 +02:00
robin 154b5ee0a1 feat: add ability to select a song 2026-07-27 16:35:28 +02:00
robin 65edd735f1 Merge pull request 'Main' (#16) from main into feat/admin-options
Reviewed-on: Schanbro/PsalmTafel#16
2026-07-27 14:28:04 +00:00
robin 854597ad2f Merge pull request 'Ui corrections' (#15) from ui-corrections into main
Deploy Next.js via Docker / deploy (push) Successful in 2m16s
Reviewed-on: Schanbro/PsalmTafel#15
2026-07-27 14:24:26 +00:00
robin b4084fdb1b style: add Label to FormElements 2026-07-27 16:23:30 +02:00
robin 09c5df8aae Feat: "...props" added to Input.Text 2026-07-27 16:16:16 +02:00
robin 1892314610 feat: add individual actionName 2026-07-27 16:06:43 +02:00
robin ca02fe9e30 style: allow props to the songs screen 2026-07-27 15:10:59 +02:00
robin 0712740eb2 feat: add Songs screen to admin page 2026-07-27 14:59:47 +02:00
robin e51ff6e738 refactor: create and use Songs-Screen in sender 2026-07-27 14:43:44 +02:00
robin 1a0f2614f2 feat: add DatabaseOverview.tsx (component songs) 2026-07-27 14:33:26 +02:00
robin 6773b903d6 Feat: add one card for all songs 2026-07-27 14:10:10 +02:00
robin 8b6d5c09a6 Merge branch 'main' into feat-dashboard 2026-07-27 11:54:27 +00:00
robin 00b3a987f3 Merge pull request 'create tag automaticly' (#11) from environment into main
Deploy Next.js via Docker / deploy (push) Successful in 42s
Reviewed-on: Schanbro/PsalmTafel#11
2026-07-26 09:18:06 +00:00
robin f73660b09f create tag automaticly 2026-07-26 09:17:33 +00:00
robin 1fa44998c4 change version number 2026-07-26 09:50:55 +02:00
robin f6920b0b8c fix: update dashboard route in the navigation 2026-07-26 09:47:14 +02:00
robin 29e0652566 refactor: add redirection from / to /dashboard 2026-07-26 09:46:35 +02:00
robin b9486274a8 refactor: move / route to /dashboard 2026-07-26 09:45:14 +02:00
robin 3f4c528ac7 Merge pull request 'LICENSE aktualisiert' (#10) from environment into main
Deploy Next.js via Docker / deploy (push) Successful in 40s
Reviewed-on: Schanbro/PsalmTafel#10
2026-07-25 18:52:23 +00:00
robin 71324e52c2 LICENSE aktualisiert 2026-07-25 18:51:30 +00:00
robin b41c488a60 Merge pull request 'Environment' (#9) from environment into main
Deploy Next.js via Docker / deploy (push) Successful in 34s
Reviewed-on: Schanbro/PsalmTafel#9
2026-07-25 18:47:57 +00:00
robin fa82153cc7 README.md aktualisiert 2026-07-25 18:45:46 +00:00
robin ddf185e683 LICENSE hinzugefügt 2026-07-25 18:44:21 +00:00
robin 08e2fd088c Merge pull request 'Environment' (#8) from environment into main
Deploy Next.js via Docker / deploy (push) Successful in 6m29s
Reviewed-on: Schanbro/PsalmTafel#8
2026-07-25 18:26:41 +00:00
robin a9b93b5624 change name to psalm-tafel
update version number
2026-07-25 20:23:26 +02:00
robin 55c7837202 change textes to english
removed unnecessary comments
2026-07-25 20:21:36 +02:00
146 changed files with 26279 additions and 4794 deletions

No files matched your search

+247
View File
@@ -0,0 +1,247 @@
---
name: prisma-cli
description: Prisma ORM CLI commands reference covering init, generate, migrate, db, dev, studio, validate, format, debug, and mcp. Use for ORM/database CLI workflows, not Prisma Compute app deployment. For Prisma Compute, `@prisma/cli app deploy`, `compute:deploy`, `create-prisma --deploy`, apps, deployments, logs, or domains, use the `prisma-compute` skill instead. Triggers on "prisma init", "prisma generate", "prisma migrate", "prisma db", "prisma studio", "prisma mcp".
license: MIT
metadata:
author: prisma
version: "7.6.0"
---
# Prisma CLI Reference
Reference for Prisma ORM CLI commands. This skill provides guidance on command usage, options, and best practices for current Prisma ORM releases.
## Boundary: Compute
Do not use this skill for Prisma Compute app deployment. Use `prisma-compute` for `@prisma/cli app deploy`, `compute:deploy`, `create-prisma --deploy`, Compute apps, deployments, logs, domains, and framework deploy readiness.
## When to Apply
Reference this skill when:
- Setting up a new Prisma project (`prisma init`)
- Generating Prisma Client (`prisma generate`)
- Running database migrations (`prisma migrate`)
- Managing database state (`prisma db push/pull`)
- Using local development database (`prisma dev`)
- Debugging Prisma issues (`prisma debug`)
## Rule Categories by Priority
| Priority | Category | Impact | Prefix |
|----------|----------|--------|--------|
| 1 | Setup | HIGH | `init` |
| 2 | Generation | HIGH | `generate` |
| 3 | Development | HIGH | `dev` |
| 4 | Database | HIGH | `db-` |
| 5 | Migrations | CRITICAL | `migrate-` |
| 6 | Utility | MEDIUM | `studio`, `validate`, `format`, `debug`, `mcp` |
## Command Categories
| Category | Commands | Purpose |
|----------|----------|---------|
| Setup | `init` | Bootstrap new Prisma project |
| Generation | `generate` | Generate Prisma Client |
| Validation | `validate`, `format` | Schema validation and formatting |
| Development | `dev` | Local Prisma Postgres for development |
| Database | `db pull`, `db push`, `db seed`, `db execute` | Direct database operations |
| Migrations | `migrate dev`, `migrate deploy`, `migrate reset`, `migrate status`, `migrate diff`, `migrate resolve` | Schema migrations |
| Utility | `studio`, `mcp`, `version`, `debug` | Development and AI tooling |
## Quick Reference
### Project Setup
```bash
# Initialize new project (creates prisma/ folder and prisma.config.ts)
prisma init
# Initialize with specific database
prisma init --datasource-provider postgresql
prisma init --datasource-provider mysql
prisma init --datasource-provider sqlite
# Initialize with Prisma Postgres (cloud)
prisma init --db
# Initialize with an example model
prisma init --with-model
```
### Client Generation
```bash
# Generate Prisma Client
prisma generate
# Watch mode for development
prisma generate --watch
# Generate specific generator only
prisma generate --generator client
```
### Bun Runtime
When using Bun, always add the `--bun` flag so Prisma runs with the Bun runtime (otherwise it falls back to Node.js because of the CLI shebang):
```bash
bunx --bun prisma init
bunx --bun prisma generate
```
### Local Development Database
```bash
# Start local Prisma Postgres
prisma dev
# Start with specific name
prisma dev --name myproject
# Start in background (detached)
prisma dev --detach
# List all local instances
prisma dev ls
# Stop instance
prisma dev stop myproject
# Remove instance data
prisma dev rm myproject
```
### Database Operations
```bash
# Pull schema from existing database
prisma db pull
# Push schema to database (no migrations)
prisma db push
# Seed database
prisma db seed
# Execute raw SQL
prisma db execute --file ./script.sql
```
### Migrations (Development)
```bash
# Create and apply migration
prisma migrate dev
# Create migration with name
prisma migrate dev --name add_users_table
# Create migration without applying
prisma migrate dev --create-only
# Reset database and apply all migrations
prisma migrate reset
```
### Migrations (Production)
```bash
# Apply pending migrations (CI/CD)
prisma migrate deploy
# Check migration status
prisma migrate status
# Compare schemas and generate diff
prisma migrate diff --from-config-datasource --to-schema schema.prisma --script
```
### Utility Commands
```bash
# Open Prisma Studio (database GUI)
prisma studio
# Start Prisma's MCP server for AI tools
prisma mcp
# Show version info
prisma version
prisma -v
# Debug information
prisma debug
# Validate schema
prisma validate
# Format schema
prisma format
```
## Current Prisma CLI Setup
### New Configuration File
Use `prisma.config.ts` for CLI configuration:
```typescript
import 'dotenv/config'
import { defineConfig, env } from 'prisma/config'
export default defineConfig({
schema: 'prisma/schema.prisma',
migrations: {
path: 'prisma/migrations',
seed: 'tsx prisma/seed.ts',
},
datasource: {
url: env('DATABASE_URL'),
},
})
```
### Current Command Behavior
- Run `prisma generate` explicitly after `migrate dev`, `db push`, or other schema syncs when you need fresh client output
- Run `prisma db seed` explicitly after `migrate dev` or `migrate reset` when you need seed data
- Use `prisma db execute --file ...` for raw SQL scripts
### Environment Variables
Load environment variables explicitly in `prisma.config.ts`, commonly with `dotenv`:
```typescript
// prisma.config.ts
import 'dotenv/config'
```
## Rule Files
See individual rule files for detailed command documentation:
```
references/init.md - Project initialization
references/generate.md - Client generation
references/dev.md - Local development database
references/db-pull.md - Database introspection
references/db-push.md - Schema push
references/db-seed.md - Database seeding
references/db-execute.md - Raw SQL execution
references/migrate-dev.md - Development migrations
references/migrate-deploy.md - Production migrations
references/migrate-reset.md - Database reset
references/migrate-status.md - Migration status
references/migrate-resolve.md - Migration resolution
references/migrate-diff.md - Schema diffing
references/studio.md - Database GUI
references/mcp.md - Prisma MCP server
references/validate.md - Schema validation
references/format.md - Schema formatting
references/debug.md - Debug info
```
## How to Use
Use the command categories above for navigation, then open the specific command reference file you need.
@@ -0,0 +1,78 @@
# prisma db execute
Execute native commands (SQL) to your database.
## Command
```bash
prisma db execute [options]
```
## What It Does
- Connects to your database using the configured datasource
- Executes a script provided via file (`--file`) or stdin (`--stdin`)
- Useful for running raw SQL, maintenance tasks, or applying diffs from `migrate diff`
- Not supported on MongoDB
## Options
| Option | Description |
|--------|-------------|
| `--file` | Path to a file containing the script to execute |
| `--stdin` | Use terminal standard input as the script |
| `--config` | Custom path to your Prisma config file |
## Current Option Surface
`prisma db execute` uses the datasource configured in `prisma.config.ts`. Use `--config` if you need a separate config file for another environment.
## Examples
### Execute from file
```bash
prisma db execute --file ./script.sql
```
### Execute from stdin
```bash
echo "TRUNCATE TABLE User;" | prisma db execute --stdin
```
### Execute `migrate diff` output
Pipe the output of `migrate diff` directly to the database:
```bash
prisma migrate diff \
--from-empty \
--to-schema prisma/schema.prisma \
--script \
| prisma db execute --stdin
```
## Configuration
Uses `datasource` from `prisma.config.ts`:
```typescript
export default defineConfig({
datasource: {
url: env('DATABASE_URL'),
},
})
```
## Use Cases
- **Manual Migrations**: Applying raw SQL changes
- **Data Maintenance**: Truncating tables, cleaning up data
- **Schema Synchronization**: Applying `migrate diff` scripts
- **Debugging**: Running test queries (though typically not for fetching data)
## Limitations
- **No Data Return**: The command reports success/failure, not query results (rows). Use Prisma Client or `prisma studio` to view data.
- **SQL Only**: Primarily for SQL databases.
@@ -0,0 +1,185 @@
# prisma db pull
Introspects an existing database and updates your Prisma schema to reflect its structure.
## Command
```bash
prisma db pull [options]
```
## What It Does
- Connects to your database
- Reads the database schema (tables, columns, relations, indexes)
- Updates `schema.prisma` with corresponding Prisma models
- For MongoDB, samples data to infer schema
## Options
| Option | Description |
|--------|-------------|
| `--force` | Ignore current Prisma schema file |
| `--print` | Print the introspected Prisma schema to stdout |
| `--schema` | Custom path to your Prisma schema |
| `--config` | Custom path to your Prisma config file |
| `--url` | Override the datasource URL from the Prisma config file |
| `--composite-type-depth` | Specify the depth for introspecting composite types (default: -1 for infinite, 0 = off) |
| `--schemas` | Specify the database schemas to introspect |
| `--local-d1` | Generate a Prisma schema from a local Cloudflare D1 database |
## Examples
### Basic introspection
```bash
prisma db pull
```
### Preview without writing
```bash
prisma db pull --print
```
Outputs schema to terminal for review.
### Force overwrite
```bash
prisma db pull --force
```
Replaces schema file, losing any manual customizations.
## Prerequisites
Configure database connection in `prisma.config.ts`:
```typescript
import 'dotenv/config'
import { defineConfig, env } from 'prisma/config'
export default defineConfig({
schema: 'prisma/schema.prisma',
datasource: {
url: env('DATABASE_URL'),
},
})
```
## Workflow
### Starting from existing database
1. Initialize Prisma:
```bash
prisma init
```
2. Configure database URL
3. Pull schema:
```bash
prisma db pull
```
4. Review and customize generated schema
5. Generate client:
```bash
prisma generate
```
### Syncing changes from database
When database changes are made outside Prisma:
```bash
prisma db pull
prisma generate
```
## Generated Schema Example
Database tables become Prisma models:
```sql
-- Database tables
CREATE TABLE users (
id SERIAL PRIMARY KEY,
email VARCHAR(255) UNIQUE NOT NULL,
name VARCHAR(100)
);
CREATE TABLE posts (
id SERIAL PRIMARY KEY,
title VARCHAR(255) NOT NULL,
author_id INTEGER REFERENCES users(id)
);
```
Becomes:
```prisma
model users {
id Int @id @default(autoincrement())
email String @unique @db.VarChar(255)
name String? @db.VarChar(100)
posts posts[]
}
model posts {
id Int @id @default(autoincrement())
title String @db.VarChar(255)
author_id Int?
users users? @relation(fields: [author_id], references: [id])
}
```
## Post-Introspection Cleanup
After `db pull`, consider:
1. **Rename models** to PascalCase:
```prisma
model User { // Was: users
@@map("users")
}
```
2. **Rename fields** to camelCase:
```prisma
authorId Int? @map("author_id")
```
3. **Add relation names** for clarity:
```prisma
author User? @relation("PostAuthor", fields: [authorId], references: [id])
```
4. **Add documentation**:
```prisma
/// User account information
model User {
/// Primary email for authentication
email String @unique
}
```
## MongoDB Introspection
For MongoDB, `db pull` samples documents to infer schema:
```bash
prisma db pull
```
May require manual refinement since MongoDB is schemaless.
## Warning
`db pull` overwrites your schema file. Always:
- Commit current schema before pulling
- Use `--print` to preview first
- Backup customizations you want to keep
@@ -0,0 +1,148 @@
# prisma db push
Pushes schema changes directly to database without creating migrations. Ideal for prototyping.
## Command
```bash
prisma db push [options]
```
## What It Does
- Syncs your Prisma schema to the database
- Creates database if it doesn't exist
- Does NOT create migration files
- Does NOT track migration history
## Options
| Option | Description |
|--------|-------------|
| `--force-reset` | Force a reset of the database before push |
| `--accept-data-loss` | Ignore data loss warnings |
| `--schema` | Custom path to your Prisma schema |
| `--config` | Custom path to your Prisma config file |
| `--url` | Override the datasource URL from the Prisma config file |
### Follow-up Command
- Run `prisma generate` explicitly when you need refreshed client output
## Examples
### Basic push
```bash
prisma db push
```
### Accept data loss
```bash
prisma db push --accept-data-loss
```
Required when changes would delete data (dropping columns, etc.)
### Force reset
```bash
prisma db push --force-reset
```
Completely resets database and applies schema.
### Full workflow
```bash
prisma db push
prisma generate
```
## When to Use
- **Prototyping** - Rapid schema iteration
- **Local development** - Quick schema changes
- **MongoDB** - Primary workflow (migrations not supported)
- **Testing** - Setting up test databases
## When NOT to Use
- **Production** - Use `migrate deploy`
- **Team collaboration** - Use migrations for trackable changes
- **When you need rollback** - Migrations provide history
## Comparison with migrate dev
| Feature | db push | migrate dev |
|---------|---------|-------------|
| Creates migration files | No | Yes |
| Tracks history | No | Yes |
| Requires shadow database | No | Yes |
| Speed | Faster | Slower |
| Rollback capability | No | Yes |
| Best for | Prototyping | Development |
## MongoDB Workflow
MongoDB doesn't support migrations. Use `db push` exclusively:
```bash
# Schema changes for MongoDB
prisma db push
prisma generate
```
## Common Patterns
### Prototyping workflow
```bash
# Make schema changes
# ...
# Push to database
prisma db push
# Generate client
prisma generate
# Test your changes
# Repeat as needed
```
### Reset and start fresh
```bash
prisma db push --force-reset
prisma db seed
```
### Handling conflicts
If `db push` can't apply changes safely:
```
Error: The following changes cannot be applied:
- Removing field `email` would cause data loss
Use --accept-data-loss to proceed
```
Decide whether data loss is acceptable, then:
```bash
prisma db push --accept-data-loss
```
## Transition to Migrations
When ready for production, switch to migrations:
```bash
# Create baseline migration from current schema
prisma migrate dev --name init
```
Then use `migrate dev` for future changes.
@@ -0,0 +1,188 @@
# prisma db seed
Runs your database seed script to populate data.
## Command
```bash
prisma db seed [options]
```
## What It Does
- Executes your configured seed script
- Populates database with initial/test data
- Runs independently (not auto-run by migrations in v7)
## Options
| Option | Description |
|--------|-------------|
| `--config` | Custom path to your Prisma config file |
| `--` | Pass custom arguments to seed script |
## Configuration
Configure seed script in `prisma.config.ts`:
```typescript
import 'dotenv/config'
import { defineConfig, env } from 'prisma/config'
export default defineConfig({
schema: 'prisma/schema.prisma',
migrations: {
path: 'prisma/migrations',
seed: 'tsx prisma/seed.ts', // Your seed command
},
datasource: {
url: env('DATABASE_URL'),
},
})
```
### Common seed commands
```typescript
// TypeScript with tsx
seed: 'tsx prisma/seed.ts'
// TypeScript with ts-node
seed: 'ts-node prisma/seed.ts'
// JavaScript
seed: 'node prisma/seed.js'
```
## Seed Script Example
```typescript
// prisma/seed.ts
import { PrismaClient } from '../generated/client'
const prisma = new PrismaClient()
async function main() {
// Create users
const alice = await prisma.user.upsert({
where: { email: 'alice@prisma.io' },
update: {},
create: {
email: 'alice@prisma.io',
name: 'Alice',
posts: {
create: {
title: 'Hello World',
published: true,
},
},
},
})
const bob = await prisma.user.upsert({
where: { email: 'bob@prisma.io' },
update: {},
create: {
email: 'bob@prisma.io',
name: 'Bob',
},
})
console.log({ alice, bob })
}
main()
.then(async () => {
await prisma.$disconnect()
})
.catch(async (e) => {
console.error(e)
await prisma.$disconnect()
process.exit(1)
})
```
## Examples
### Run seed
```bash
prisma db seed
```
### With custom arguments
```bash
prisma db seed -- --environment development
```
Arguments after `--` are passed to your seed script.
## Current Workflow
Run seeding explicitly after migrations when you need seed data:
```bash
prisma migrate dev --name init
prisma generate
prisma db seed # Must run explicitly
```
## Idempotent Seeding
Use `upsert` to make seeds re-runnable:
```typescript
// Good: Can run multiple times
await prisma.user.upsert({
where: { email: 'alice@prisma.io' },
update: {}, // Don't change existing
create: { email: 'alice@prisma.io', name: 'Alice' },
})
// Bad: Fails on second run
await prisma.user.create({
data: { email: 'alice@prisma.io', name: 'Alice' },
})
```
## Common Patterns
### Development reset
```bash
prisma migrate reset --force
prisma db seed
```
### Conditional seeding
```typescript
// prisma/seed.ts
const count = await prisma.user.count()
if (count === 0) {
// Only seed if empty
await seedUsers()
}
```
### Environment-specific seeds
```typescript
// prisma/seed.ts
const env = process.env.NODE_ENV || 'development'
if (env === 'development') {
await seedDevData()
} else if (env === 'test') {
await seedTestData()
}
```
## Best Practices
1. Use `upsert` for idempotent seeds
2. Keep seeds focused and minimal
3. Use realistic but fake data
4. Document required seed data
5. Version control your seed scripts
@@ -0,0 +1,46 @@
# prisma debug
Prints information helpful for debugging and bug reports.
## Command
```bash
prisma debug [options]
```
## What It Does
Outputs details about your Prisma environment, including:
- Prisma CLI version
- Prisma Client version (if installed)
- Engine binaries (Query Engine, Migration Engine, etc.)
- Platform information (OS, Architecture)
- Node.js version
- Configured datasource provider
## Options
| Option | Description |
|--------|-------------|
| `--schema` | Path to schema file |
| `--config` | Custom path to your Prisma config file |
## Example Output
```
prisma : 7.3.0
@prisma/client : 7.3.0
Operating System : darwin
Architecture : arm64
Node.js : v20.10.0
TypeScript : 5.3.3
Query Compiler : enabled
PSL : ...
Schema Engine : ...
```
## When to Use
- **Troubleshooting**: Checking version mismatches
- **Reporting Issues**: Including environment info in GitHub issues
- **Verifying Installation**: Ensuring correct binaries are downloaded
+157
View File
@@ -0,0 +1,157 @@
# prisma dev
Starts a local Prisma Postgres database for development. Provides a PostgreSQL-compatible database that runs entirely on your machine.
## Command
```bash
prisma dev [options]
```
## What It Does
- Starts a local PostgreSQL-compatible database
- Runs in your terminal or as a background process
- Perfect for development and testing
- Easy migration to Prisma Postgres cloud in production
## Options
| Option | Description | Default |
|--------|-------------|---------|
| `--name` / `-n` | Name for the database instance | `default` |
| `--port` / `-p` | HTTP server port | `51213` |
| `--db-port` / `-P` | Database server port | `51214` |
| `--shadow-db-port` | Shadow database port (for migrations) | `51215` |
| `--detach` / `-d` | Run in background | `false` |
| `--debug` | Enable debug logging | `false` |
## Examples
### Start local database
```bash
prisma dev
```
Interactive mode with keyboard shortcuts:
- `q` - Quit
- `h` - Show HTTP URL
- `t` - Show TCP URLs
### Named instance
```bash
prisma dev --name myproject
```
Useful for multiple projects.
### Background mode
```bash
prisma dev --detach
```
Frees your terminal for other commands.
### Custom ports
```bash
prisma dev --port 5000 --db-port 5432
```
## Instance Management
### List all instances
```bash
prisma dev ls
```
Shows all local Prisma Postgres instances with status.
### Start existing instance
```bash
prisma dev start myproject
```
Starts a previously created instance in background.
### Stop instance
```bash
prisma dev stop myproject
```
### Stop with glob pattern
```bash
prisma dev stop "myproject*"
```
Stops all instances matching pattern.
### Remove instance
```bash
prisma dev rm myproject
```
Removes instance data from filesystem.
### Force remove (stops first)
```bash
prisma dev rm myproject --force
```
## Configuration
Configure your `prisma.config.ts` to use local Prisma Postgres:
```typescript
import 'dotenv/config'
import { defineConfig, env } from 'prisma/config'
export default defineConfig({
schema: 'prisma/schema.prisma',
migrations: {
path: 'prisma/migrations',
},
datasource: {
// Local Prisma Postgres URL (from prisma dev output)
url: env('DATABASE_URL'),
},
})
```
## Workflow
1. Start local database:
```bash
prisma dev
```
2. In another terminal, run migrations:
```bash
prisma migrate dev
```
3. Generate client:
```bash
prisma generate
```
4. Run your application
## Production Migration
When ready for production, switch to Prisma Postgres cloud:
```bash
prisma init --db
```
Update your `DATABASE_URL` to the cloud connection string.
@@ -0,0 +1,48 @@
# prisma format
Formats your Prisma schema file.
## Command
```bash
prisma format [options]
```
## What It Does
- Fixes formatting (indentation, spacing)
- Adds missing back-relations (e.g., adds the other side of a relation)
- Adds missing relation arguments (e.g., `fields`, `references`)
- Sorts fields and attributes (opinionated)
## Options
| Option | Description |
|--------|-------------|
| `--schema` | Path to schema file |
| `--config` | Custom path to your Prisma config file |
## Examples
### Format default schema
```bash
prisma format
```
### Format specific schema
```bash
prisma format --schema=./custom/schema.prisma
```
## Behavior
`prisma format` modifies the file in place. It is equivalent to "Prettier for Prisma schemas" but also has semantic understanding to fix/add missing schema definitions.
## Use in Editor
Most Prisma editor extensions (VS Code, WebStorm) run `prisma format` automatically on save. This command is useful for:
- CI pipelines (check formatting)
- CLI-based workflows
- Fixing large schema refactors
@@ -0,0 +1,173 @@
# prisma generate
Generates assets based on the generator blocks in your Prisma schema, most commonly Prisma Client.
## Command
```bash
prisma generate [options]
```
## Bun Runtime
If you're using Bun, run Prisma with `bunx --bun` so it doesn't fall back to Node.js:
```bash
bunx --bun prisma generate
```
## What It Does
1. Reads your `schema.prisma` file
2. Generates a customized Prisma Client based on your models
3. Outputs to the directory specified in the generator block
## Options
| Option | Description |
|--------|-------------|
| `--schema` | Custom path to your Prisma schema |
| `--config` | Custom path to your Prisma config file |
| `--sql` | Generate typed sql module |
| `--watch` | Watch the Prisma schema and rerun after a change |
| `--generator` | Generator to use (may be provided multiple times) |
| `--no-hints` | Hides the hint messages but still outputs errors and warnings |
| `--require-models` | Do not allow generating a client without models |
## Examples
### Basic generation
```bash
prisma generate
```
### Watch mode (development)
```bash
prisma generate --watch
```
Auto-regenerates when `schema.prisma` changes.
### Specific generator
```bash
prisma generate --generator client
```
### Multiple generators
```bash
prisma generate --generator client --generator zod_schemas
```
### Typed SQL generation
```bash
prisma generate --sql
```
## Schema Configuration
```prisma
generator client {
provider = "prisma-client"
output = "../generated"
}
```
### Current Generator Behavior
- `prisma-client` is the standard generator
- `output` is required when using `prisma-client`
- `prisma-client` supports both ESM and CommonJS via `moduleFormat`
- `compilerBuild` supports `fast` and `small` query compiler artifacts
- Use TypeScript `satisfies` for typed query fragments with `prisma-client`
- Import Prisma Client from your generated output path, for example:
```typescript
import { PrismaClient } from '../generated/prisma/client'
```
### Compiler Build Tuning
Use `compilerBuild` when you need to trade artifact size against the default build:
```prisma
generator client {
provider = "prisma-client"
output = "../generated"
compilerBuild = "small"
}
```
- `fast` is the default build for most targets
- `small` is useful for size-constrained targets
- Prisma defaults `vercel-edge` targets to `small`
## Common Patterns
### After schema changes
```bash
prisma migrate dev --name my_migration
prisma generate
```
Run `prisma generate` whenever you need refreshed client code after schema-changing commands.
### CI/CD pipeline
```bash
prisma generate
```
Run before building your application.
### Multiple generators
```prisma
generator client {
provider = "prisma-client"
output = "../generated"
}
generator zod {
provider = "zod-prisma-types"
output = "../generated/zod"
}
```
```bash
prisma generate # Runs all generators
```
## Output Structure
After running `prisma generate`, your output directory contains:
```
generated/
├── browser.ts
├── client.ts
├── commonInputTypes.ts
├── models/
├── enums.ts
├── models.ts
└── ...
```
Import the client:
```typescript
import { PrismaClient, Prisma } from '../generated/prisma/client'
```
Import browser-safe types:
```typescript
import { Prisma } from '../generated/prisma/browser'
import { Role } from '../generated/prisma/enums'
import type { UserModel } from '../generated/prisma/models/User'
```
@@ -0,0 +1,136 @@
# prisma init
Bootstraps a fresh Prisma ORM project in the current directory.
## Command
```bash
prisma init [options]
```
## Bun Runtime
If you're using Bun, run Prisma with `bunx --bun` so it doesn't fall back to Node.js:
```bash
bunx --bun prisma init
```
## What It Creates
- `prisma/schema.prisma` - Your Prisma schema file
- `prisma.config.ts` - TypeScript configuration for Prisma CLI
- `.env` - Environment variables (DATABASE_URL)
- `.gitignore` - Ensures `.env` is ignored and appends the generated client path
## Options
| Option | Description | Default |
|--------|-------------|---------|
| `--datasource-provider` | Database provider: `postgresql`, `mysql`, `sqlite`, `sqlserver`, `mongodb`, `cockroachdb` | `postgresql` |
| `--db` | Provisions a fully managed Prisma Postgres database on the Prisma Data Platform | - |
| `--url` | Define a custom datasource url | - |
| `--generator-provider` | Define the generator provider to use | `prisma-client` |
| `--output` | Define Prisma Client generator output path to use | - |
| `--preview-feature` | Define a preview feature to use | - |
| `--with-model` | Add example model to created schema file | - |
## Examples
### Basic initialization
```bash
prisma init
```
Creates a PostgreSQL project setup.
### SQLite project
```bash
prisma init --datasource-provider sqlite
```
### MySQL with custom URL
```bash
prisma init --datasource-provider mysql --url "mysql://user:password@localhost:3306/mydb"
```
### Prisma Postgres (cloud)
```bash
prisma init --db
```
Opens browser for authentication, creates cloud database instance.
### Add an example model
```bash
prisma init --with-model
```
Adds a starter model to the generated schema.
### With preview features
```bash
prisma init --preview-feature relationJoins --preview-feature fullTextSearch
```
## Generated Schema
```prisma
generator client {
provider = "prisma-client"
output = "../generated/prisma"
}
datasource db {
provider = "postgresql"
}
```
## Generated Config (Node.js default)
```typescript
// prisma.config.ts
import "dotenv/config";
import { defineConfig } from 'prisma/config'
export default defineConfig({
schema: 'prisma/schema.prisma',
migrations: {
path: 'prisma/migrations',
},
datasource: {
url: process.env['DATABASE_URL'],
},
})
```
## Generated Config (Bun)
```typescript
import { defineConfig, env } from 'prisma/config'
export default defineConfig({
schema: 'prisma/schema.prisma',
migrations: {
path: 'prisma/migrations',
},
datasource: {
url: env('DATABASE_URL'),
},
})
```
## Next Steps After Init
1. Configure `DATABASE_URL` in `.env` (and let `prisma.config.ts` read it)
2. Define your models in `prisma/schema.prisma`
3. Run `prisma dev` for local development or connect to remote DB
4. Run `prisma migrate dev` to create migrations
5. Run `prisma generate` to generate Prisma Client
6. Run `prisma db seed` explicitly if you want seed data
@@ -0,0 +1,38 @@
# prisma mcp
Starts Prisma's MCP server for AI development tools.
## Command
```bash
prisma mcp
```
## What It Does
- Starts a Model Context Protocol (MCP) server for your Prisma project
- Exposes Prisma schema and database context to compatible AI tools
- Helps AI assistants understand models, generate queries, and suggest migrations
## Usage
```bash
prisma mcp
```
## Typical Use Cases
- Connect Prisma to ChatGPT, Claude, or other MCP-aware tools
- Give an AI assistant access to your Prisma schema structure
- Help an agent propose queries, schema updates, and migration steps with project context
## Notes
- Run this from the project that contains your Prisma schema and `prisma.config.ts`
- The command is separate from Prisma Studio and does not open a browser UI
- The MCP server wraps Prisma CLI commands. For exact behavior of commands like `migrate dev` or `migrate reset`, follow the underlying CLI command docs rather than relying only on the MCP tool descriptions.
## References
- [Prisma CLI `mcp` command](https://docs.prisma.io/docs/cli/mcp)
- [Prisma MCP Server](https://www.prisma.io/docs/ai/tools/chatgpt)
@@ -0,0 +1,127 @@
# prisma migrate deploy
Applies pending migrations in production/staging environments.
## Command
```bash
prisma migrate deploy
```
## What It Does
- Applies all pending migrations from `prisma/migrations/`
- Updates `_prisma_migrations` table
- Does NOT generate new migrations
- Does NOT run seed scripts
- Safe for CI/CD and production
## Options
| Option | Description |
|--------|-------------|
| `--schema` | Custom path to your Prisma schema |
| `--config` | Custom path to your Prisma config file |
## When to Use
- Production deployments
- Staging environments
- CI/CD pipelines
- Any non-development environment
## Examples
### Basic deployment
```bash
prisma migrate deploy
```
### In CI/CD pipeline
```yaml
# GitHub Actions example
- name: Apply migrations
run: npx prisma migrate deploy
env:
DATABASE_URL: ${{ secrets.DATABASE_URL }}
```
### Docker deployment
```dockerfile
# Run migrations before starting app
CMD npx prisma migrate deploy && node dist/index.js
```
## Comparison with migrate dev
| Feature | migrate dev | migrate deploy |
|---------|-------------|----------------|
| Creates migrations | Yes | No |
| Applies migrations | Yes | Yes |
| Detects drift | Yes | No |
| Prompts for input | Yes | No |
| Uses shadow database | Yes | No |
| Safe for production | No | Yes |
| Resets on issues | Prompts | Fails |
## Production Workflow
1. **Development**: Create migrations locally
```bash
prisma migrate dev --name add_feature
```
2. **Commit**: Include migration files in version control
```bash
git add prisma/migrations
git commit -m "Add feature migration"
```
3. **Deploy**: Apply in production
```bash
prisma migrate deploy
```
## Error Handling
### Failed migration
If a migration fails, `migrate deploy` exits with error. The failed migration is marked as failed in `_prisma_migrations`.
To fix:
1. Resolve the issue (fix SQL, database state, etc.)
2. Mark as resolved: `prisma migrate resolve --applied <migration_name>`
3. Re-run: `prisma migrate deploy`
### Check status first
```bash
prisma migrate status
```
Shows pending and applied migrations before deploying.
## Configuration
Ensure `prisma.config.ts` has the production database URL:
```typescript
import 'dotenv/config'
import { defineConfig, env } from 'prisma/config'
export default defineConfig({
datasource: {
url: env('DATABASE_URL'),
},
})
```
## Best Practices
1. Always run `migrate status` before `migrate deploy` in CI
2. Have a rollback plan (backup before migrations)
3. Test migrations in staging first
4. Never use `migrate dev` in production
@@ -0,0 +1,145 @@
# prisma migrate dev
Creates and applies migrations during development. Requires a shadow database.
## Command
```bash
prisma migrate dev [options]
```
## What It Does
1. Runs existing migrations in shadow database to detect drift
2. Applies any pending migrations
3. Generates new migration from schema changes
4. Applies new migration to development database
5. Updates `_prisma_migrations` table
## Options
| Option | Description |
|--------|-------------|
| `--name` / `-n` | Name the migration |
| `--create-only` | Create a new migration but do not apply it |
| `--schema` | Custom path to your Prisma schema |
| `--config` | Custom path to your Prisma config file |
| `--url` | Override the datasource URL from the Prisma config file |
### Follow-up Commands
- Run `prisma generate` explicitly when you need refreshed client output
- Run `prisma db seed` explicitly when you need seed data
Note: Prisma CLI help for `7.6.0` still says `migrate dev` "trigger[s] generators", but local verification in a temp Prisma 7.6.0 project did not emit generated client files. Treat `prisma generate` as an explicit follow-up step when you need generated artifacts on disk.
## Examples
### Create and apply migration
```bash
prisma migrate dev
```
Prompts for migration name if schema changed.
### Named migration
```bash
prisma migrate dev --name add_users_table
```
### Create without applying
```bash
prisma migrate dev --create-only
```
Useful for reviewing migration SQL before applying.
### Full workflow
```bash
prisma migrate dev --name my_migration
prisma generate
prisma db seed
```
## Migration Files
Created in `prisma/migrations/`:
```
prisma/migrations/
├── 20240115120000_add_users_table/
│ └── migration.sql
├── 20240116090000_add_posts/
│ └── migration.sql
└── migration_lock.toml
```
## Schema Drift Detection
If `migrate dev` detects drift (manual database changes or edited migrations), it prompts to reset:
```
Drift detected: Your database schema is not in sync.
Do you want to reset your database? All data will be lost.
```
## When to Use
- Local development
- Adding new models/fields
- Changing relations
- Creating indexes
## When NOT to Use
- Production deployments (use `migrate deploy`)
- CI/CD pipelines (use `migrate deploy`)
- MongoDB (use `db push` instead)
## Common Patterns
### After schema changes
```prisma
// schema.prisma - Add new field
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
createdAt DateTime @default(now()) // New field
}
```
```bash
prisma migrate dev --name add_created_at
```
### Handling data loss warnings
When a migration would cause data loss:
```bash
prisma migrate dev --name remove_field
# Warning: You are about to delete data...
# Accept with: --accept-data-loss
```
## Shadow Database
`migrate dev` requires a shadow database for drift detection. Configure in `prisma.config.ts`:
```typescript
export default defineConfig({
datasource: {
url: env('DATABASE_URL'),
shadowDatabaseUrl: env('SHADOW_DATABASE_URL'),
},
})
```
For local Prisma Postgres (`prisma dev`), shadow database is handled automatically.
@@ -0,0 +1,89 @@
# prisma migrate diff
Compares database schemas and generates diffs (SQL or summary).
## Command
```bash
prisma migrate diff [options]
```
## What It Does
- Compares two sources (`--from-...` and `--to-...`)
- Sources can be:
- Empty (`empty`)
- Schema file (`schema`)
- Migrations directory (`migrations`)
- Database URL (`url`) or Configured Datasource (`config-datasource`)
- Outputs the difference:
- Human-readable summary (default)
- SQL script (`--script`)
## Options
| Option | Description |
|--------|-------------|
| `--script` | Render SQL script to stdout |
| `--exit-code` | Exit 2 if changes detected, 0 if empty, 1 if error |
| `--config` | Custom path to your Prisma config file |
### Sources (Must provide one `from` and one `to`)
- `--from-empty`, `--to-empty`
- `--from-schema <path>`, `--to-schema <path>`
- `--from-migrations <path>`, `--to-migrations <path>`
- `--from-url <url>`, `--to-url <url>`
- `--from-config-datasource`, `--to-config-datasource` (uses `prisma.config.ts`)
## Examples
### Generate SQL for a schema change
Compare current production DB to your local schema:
```bash
prisma migrate diff \
--from-url "$PROD_DB_URL" \
--to-schema ./prisma/schema.prisma \
--script
```
### Review pending migrations
Compare database state to migrations directory:
```bash
prisma migrate diff \
--from-config-datasource \
--to-migrations ./prisma/migrations
```
### Create baseline migration
Compare empty state to current schema:
```bash
prisma migrate diff \
--from-empty \
--to-schema ./prisma/schema.prisma \
--script > prisma/migrations/0_init/migration.sql
```
### Check for drift (CI)
Check if database matches schema:
```bash
prisma migrate diff \
--from-config-datasource \
--to-schema ./prisma/schema.prisma \
--exit-code
```
## Use Cases
- **Forward-generating migrations**: Creating SQL without `migrate dev`.
- **Drift detection**: Checking if DB is in sync.
- **Baselining**: Creating initial migration from existing DB.
- **Debugging**: Understanding what `migrate dev` would do.
@@ -0,0 +1,78 @@
# prisma migrate reset
Resets your database and re-applies all migrations.
## Command
```bash
prisma migrate reset [options]
```
## What It Does
1. **Drops** the database (if possible) or deletes all data/tables
2. **Re-creates** the database
3. **Applies** all migrations from `prisma/migrations/`
4. Stops there - run seed and generate explicitly if needed
**Warning: All data will be lost.**
## Options
| Option | Description |
|--------|-------------|
| `--force` / `-f` | Skip confirmation prompt |
| `--schema` | Path to schema file |
| `--config` | Custom path to your Prisma config file |
## Examples
### Basic reset
```bash
prisma migrate reset
```
Prompts for confirmation in interactive terminals.
### Force reset (CI/Automation)
```bash
prisma migrate reset --force
```
### With custom schema
```bash
prisma migrate reset --schema=./custom/schema.prisma
```
## When to Use
- **Development**: When you want a fresh start
- **Testing**: Resetting test database before suites
- **Drift Recovery**: When the database is out of sync and you can't migrate
## Follow-up Steps
Run `prisma generate` and `prisma db seed` explicitly when you need refreshed client output or seed data after a reset.
## Configuration
Configure the seed script in `prisma.config.ts`, then run it explicitly after reset:
```typescript
export default defineConfig({
migrations: {
seed: 'tsx prisma/seed.ts',
},
})
```
Typical workflow:
```bash
prisma migrate reset --force
prisma generate
prisma db seed
```
@@ -0,0 +1,57 @@
# prisma migrate resolve
Resolves issues with database migrations, such as failed migrations or baselining.
## Command
```bash
prisma migrate resolve [options]
```
## What It Does
Updates the `_prisma_migrations` table to manually change the state of a migration. This is a recovery tool.
## Options
You must provide exactly one of `--applied` or `--rolled-back`.
| Option | Description |
|--------|-------------|
| `--applied <name>` | Mark a migration as **applied** (success) |
| `--rolled-back <name>` | Mark a migration as **rolled back** (ignored/failed) |
| `--schema` | Path to schema file |
| `--config` | Custom path to your Prisma config file |
## Examples
### Mark as Applied (Baselining)
If you have existing tables and want to initialize migrations without running the SQL:
```bash
prisma migrate resolve --applied 20240101000000_initial_migration
```
This tells Prisma "Assume this migration has already run".
### Mark as Rolled Back (Fixing Failures)
If a migration failed (e.g., syntax error) and you fixed the SQL or want to retry:
```bash
prisma migrate resolve --rolled-back 20240115120000_failed_migration
```
This tells Prisma "Forget this migration run, let me try applying it again".
## Use Cases
1. **Baselining**: Adopting Prisma Migrate on an existing production database.
2. **Failed Migrations**: Recovering from a failed `migrate deploy` in production.
3. **Hotfixes**: reconciling manual database changes (rare).
## References
- [Baselining](https://www.prisma.io/docs/guides/database/developing-with-prisma-migrate/baselining)
- [Troubleshooting](https://www.prisma.io/docs/guides/database/production-troubleshooting)
@@ -0,0 +1,65 @@
# prisma migrate status
Checks the status of your database migrations.
## Command
```bash
prisma migrate status [options]
```
## What It Does
- Connects to the database
- Checks the `_prisma_migrations` table
- Compares applied migrations with local migration files
- Reports:
- **Status**: Database is up-to-date or behind
- **Unapplied migrations**: Count of pending migrations
- **Missing migrations**: Migrations present in DB but missing locally
- **Failed migrations**: Any migrations that failed to apply
## Options
| Option | Description |
|--------|-------------|
| `--schema` | Path to schema file |
| `--config` | Custom path to your Prisma config file |
## Examples
### Check status
```bash
prisma migrate status
```
Output example (Up to date):
```
Database schema is up to date!
```
Output example (Pending):
```
Following migration have not yet been applied:
20240115120000_add_user
To apply migrations in development, run:
prisma migrate dev
To apply migrations in production, run:
prisma migrate deploy
```
## When to Use
- **Debugging**: Why is `migrate dev` complaining about drift?
- **CI/CD**: Verify database state before deploying
- **Production**: Check if migrations are needed (`migrate deploy`) or if a deployment failed
## Exit Codes
- `0`: Success (may have pending migrations, but command ran successfully)
- `1`: Error
To check for pending migrations programmatically, you might need to parse the output or use `migrate diff` with exit code flags.
@@ -0,0 +1,137 @@
# prisma studio
Opens a visual database browser for viewing and editing data.
## Command
```bash
prisma studio [options]
```
## What It Does
- Starts a web-based database GUI
- View all your models and records
- Create, update, and delete records
- Filter and sort data
- Navigate relations
## Options
| Option | Description | Default |
|--------|-------------|---------|
| `--port` / `-p` | Port to start Studio on | `5555` |
| `--browser` / `-b` | Browser to open Studio in | System default |
| `--config` | Custom path to your Prisma config file | - |
| `--url` | Database connection string (overrides the one in your Prisma config) | - |
## Examples
### Open Studio
```bash
prisma studio
```
Opens at http://localhost:5555
### Custom port
```bash
prisma studio --port 3000
```
### Specific browser
```bash
prisma studio --browser firefox
```
### Don't open browser
```bash
BROWSER=none prisma studio
```
Useful for remote servers.
## Features
### View Records
- See all records in table format
- Pagination for large datasets
- Column sorting
### Filter Data
- Filter by any field
- Multiple conditions
- Relation filtering
### Edit Records
- Click to edit inline
- Add new records
- Delete records (with confirmation)
### Navigate Relations
- Click relations to view related records
- See counts of related items
- Follow relation links
## Recent Studio Capabilities
Recent Prisma Studio releases added richer editor workflows:
- multi-cell selection and editing
- full-table search and more intuitive filtering
- command palette shortcuts
- dark mode
- copy selections as Markdown
- back-relation navigation
- SQL workflows including raw SQL queries
Some recent builds also expose AI-assisted SQL authoring. Treat these as interactive Studio features rather than a replacement for checked-in migrations or application queries.
## Use Cases
- **Development**: Quick data inspection
- **Debugging**: Check data state
- **Testing**: Verify seed data
- **Demo**: Show data to stakeholders
## Limitations
- Development tool only
- Not for production use
- Limited to configured database
- Prisma Studio in Prisma 7 currently targets PostgreSQL, MySQL, and SQLite first
- For reproducible application logic, prefer Prisma Client and checked-in SQL scripts
## Common Workflow
1. Run migrations:
```bash
prisma migrate dev
```
2. Seed data:
```bash
prisma db seed
```
3. Open Studio to verify:
```bash
prisma studio
```
4. Make manual edits if needed
## Security Note
Studio provides direct database access. Only run on:
- Local development machines
- Secure internal networks
- Never expose publicly
@@ -0,0 +1,53 @@
# prisma validate
Validates your Prisma schema file.
## Command
```bash
prisma validate [options]
```
## What It Does
- Parses the `schema.prisma` file
- Checks for syntax errors
- Validates model definitions, relations, and types
- Reports any errors or warnings without generating code
## Options
| Option | Description |
|--------|-------------|
| `--schema` | Path to schema file |
| `--config` | Custom path to your Prisma config file |
## Examples
### Validate default schema
```bash
prisma validate
```
### Validate specific schema
```bash
prisma validate --schema=./custom/schema.prisma
```
### Use in CI
Run `validate` in your CI pipeline to catch schema errors early:
```yaml
- name: Validate Schema
run: npx prisma validate
```
## Common Errors
- Missing `@relation` fields
- Invalid types
- Duplicate model names
- Syntax errors (missing braces, etc.)
+216
View File
@@ -0,0 +1,216 @@
---
name: prisma-client-api
description: Prisma Client API reference covering model queries, filters, operators, and client methods. Use when writing database queries, using CRUD operations, filtering data, or configuring Prisma Client. Triggers on "prisma query", "findMany", "create", "update", "delete", "$transaction".
license: MIT
metadata:
author: prisma
version: "7.6.0"
---
# Prisma Client API Reference
Complete API reference for Prisma Client. This skill provides guidance on model queries, filtering, relations, and client methods for current Prisma projects.
## When to Apply
Reference this skill when:
- Writing database queries with Prisma Client
- Performing CRUD operations (create, read, update, delete)
- Filtering and sorting data
- Working with relations
- Using transactions
- Configuring client options
## Rule Categories by Priority
| Priority | Category | Impact | Prefix |
|----------|----------|--------|--------|
| 1 | Client Construction | HIGH | `constructor` |
| 2 | Model Queries | CRITICAL | `model-queries` |
| 3 | Query Shape | HIGH | `query-options` |
| 4 | Filtering | HIGH | `filters` |
| 5 | Relations | HIGH | `relations` |
| 6 | Transactions | CRITICAL | `transactions` |
| 7 | Raw SQL | CRITICAL | `raw-queries` |
| 8 | Client Methods | MEDIUM | `client-methods` |
## Quick Reference
- `constructor` - `PrismaClient` setup, adapter wiring, logging, and SQL commenter plugins
- `model-queries` - CRUD operations and bulk operations
- `query-options` - `select`, `include`, `omit`, sort, pagination
- `filters` - scalar and logical filter operators
- `relations` - relation reads and nested writes
- `transactions` - array and interactive transaction patterns
- `raw-queries` - `$queryRaw` and `$executeRaw` safety
- `client-methods` - lifecycle methods, extensions, and `satisfies` patterns for `prisma-client`
## Client Instantiation
```typescript
import { PrismaClient } from '../generated/client'
import { PrismaPg } from '@prisma/adapter-pg'
const adapter = new PrismaPg({
connectionString: process.env.DATABASE_URL
})
const prisma = new PrismaClient({ adapter })
```
## Model Query Methods
| Method | Description |
|--------|-------------|
| `findUnique()` | Find one record by unique field |
| `findUniqueOrThrow()` | Find one or throw error |
| `findFirst()` | Find first matching record |
| `findFirstOrThrow()` | Find first or throw error |
| `findMany()` | Find multiple records |
| `create()` | Create a new record |
| `createMany()` | Create multiple records |
| `createManyAndReturn()` | Create multiple and return them |
| `update()` | Update one record |
| `updateMany()` | Update multiple records |
| `updateManyAndReturn()` | Update multiple and return them |
| `upsert()` | Update or create record |
| `delete()` | Delete one record |
| `deleteMany()` | Delete multiple records |
| `count()` | Count matching records |
| `aggregate()` | Aggregate values (sum, avg, etc.) |
| `groupBy()` | Group and aggregate |
## Query Options
| Option | Description |
|--------|-------------|
| `where` | Filter conditions |
| `select` | Fields to include |
| `include` | Relations to load |
| `omit` | Fields to exclude |
| `orderBy` | Sort order |
| `take` | Limit results |
| `skip` | Skip results (pagination) |
| `cursor` | Cursor-based pagination |
| `distinct` | Unique values only |
## Client Methods
| Method | Description |
|--------|-------------|
| `$connect()` | Explicitly connect to database |
| `$disconnect()` | Disconnect from database |
| `$transaction()` | Execute transaction |
| `$queryRaw()` | Execute raw SQL query |
| `$executeRaw()` | Execute raw SQL command |
| `$on()` | Subscribe to events |
| `$extends()` | Add extensions |
## Quick Examples
### Find records
```typescript
// Find by unique field
const user = await prisma.user.findUnique({
where: { email: 'alice@prisma.io' }
})
// Find with filter
const users = await prisma.user.findMany({
where: { role: 'ADMIN' },
orderBy: { createdAt: 'desc' },
take: 10
})
```
### Create records
```typescript
const user = await prisma.user.create({
data: {
email: 'alice@prisma.io',
name: 'Alice',
posts: {
create: { title: 'Hello World' }
}
},
include: { posts: true }
})
```
### Update records
```typescript
const user = await prisma.user.update({
where: { id: 1 },
data: { name: 'Alice Smith' }
})
```
### Delete records
```typescript
await prisma.user.delete({
where: { id: 1 }
})
```
### Transactions
```typescript
const [user, post] = await prisma.$transaction([
prisma.user.create({ data: { email: 'alice@prisma.io' } }),
prisma.post.create({ data: { title: 'Hello', authorId: 1 } })
])
```
## Rule Files
Detailed API documentation:
```
references/constructor.md - PrismaClient constructor options
references/model-queries.md - CRUD operations
references/query-options.md - select, include, omit, where, orderBy
references/filters.md - Filter conditions and operators
references/relations.md - Relation queries and nested operations
references/transactions.md - Transaction API
references/raw-queries.md - $queryRaw, $executeRaw
references/client-methods.md - $connect, $disconnect, $on, $extends
```
## Filter Operators
| Operator | Description |
|----------|-------------|
| `equals` | Exact match |
| `not` | Not equal |
| `in` | In array |
| `notIn` | Not in array |
| `lt`, `lte` | Less than |
| `gt`, `gte` | Greater than |
| `contains` | String contains |
| `startsWith` | String starts with |
| `endsWith` | String ends with |
| `mode` | Case sensitivity |
## Relation Filters
| Operator | Description |
|----------|-------------|
| `some` | At least one related record matches |
| `every` | All related records match |
| `none` | No related records match |
| `is` | Related record matches (1-to-1) |
| `isNot` | Related record doesn't match |
## Resources
- [Prisma Client API Reference](https://www.prisma.io/docs/orm/reference/prisma-client-reference)
- [CRUD Operations](https://www.prisma.io/docs/orm/prisma-client/queries/crud)
- [Filtering and Sorting](https://www.prisma.io/docs/orm/prisma-client/queries/filtering-and-sorting)
## How to Use
Pick the category from the table above, then open the matching reference file for implementation details and examples.
@@ -0,0 +1,223 @@
# Client Methods
Prisma Client instance methods.
## $connect()
Explicitly connect to the database:
```typescript
const prisma = new PrismaClient({ adapter })
// Explicit connection
await prisma.$connect()
```
### When to use
Usually not needed - Prisma connects automatically on first query. Use for:
- Fail fast on startup
- Health checks
- Pre-warming connections
```typescript
async function main() {
try {
await prisma.$connect()
console.log('Database connected')
} catch (e) {
console.error('Failed to connect:', e)
process.exit(1)
}
}
```
## $disconnect()
Close database connection:
```typescript
await prisma.$disconnect()
```
### Graceful shutdown
```typescript
process.on('beforeExit', async () => {
await prisma.$disconnect()
})
// Or with SIGTERM
process.on('SIGTERM', async () => {
await prisma.$disconnect()
process.exit(0)
})
```
### In tests
```typescript
afterAll(async () => {
await prisma.$disconnect()
})
```
## $on()
Subscribe to events:
### Query events
```typescript
const prisma = new PrismaClient({
adapter,
log: [{ level: 'query', emit: 'event' }]
})
prisma.$on('query', (e) => {
console.log('Query:', e.query)
console.log('Params:', e.params)
console.log('Duration:', e.duration, 'ms')
})
```
### Log events
```typescript
const prisma = new PrismaClient({
adapter,
log: [
{ level: 'info', emit: 'event' },
{ level: 'warn', emit: 'event' },
{ level: 'error', emit: 'event' }
]
})
prisma.$on('info', (e) => console.log(e.message))
prisma.$on('warn', (e) => console.warn(e.message))
prisma.$on('error', (e) => console.error(e.message))
```
## $extends()
Add extensions for custom behavior:
### Add custom methods
```typescript
const prisma = new PrismaClient({ adapter }).$extends({
client: {
$log: (message: string) => console.log(message)
}
})
prisma.$log('Hello!')
```
### Add model methods
```typescript
const prisma = new PrismaClient({ adapter }).$extends({
model: {
user: {
async findByEmail(email: string) {
return prisma.user.findUnique({ where: { email } })
}
}
}
})
const user = await prisma.user.findByEmail('alice@prisma.io')
```
### Query extensions
```typescript
const prisma = new PrismaClient({ adapter }).$extends({
query: {
user: {
async findMany({ args, query }) {
// Add default filter
args.where = { ...args.where, deletedAt: null }
return query(args)
}
}
}
})
```
### Result extensions
```typescript
const prisma = new PrismaClient({ adapter }).$extends({
result: {
user: {
fullName: {
needs: { firstName: true, lastName: true },
compute(user) {
return `${user.firstName} ${user.lastName}`
}
}
}
}
})
const user = await prisma.user.findFirst()
console.log(user.fullName) // Computed field
```
### Chain extensions
```typescript
const prisma = new PrismaClient({ adapter })
.$extends(loggingExtension)
.$extends(softDeleteExtension)
.$extends(computedFieldsExtension)
```
## $transaction()
See `transactions.md` for details.
## $queryRaw() / $executeRaw()
See `raw-queries.md` for details.
## Type utilities
### Prisma namespace
```typescript
import { Prisma } from '../generated/client'
// Input types
type UserCreateInput = Prisma.UserCreateInput
type UserWhereInput = Prisma.UserWhereInput
// Output types
type User = Prisma.UserGetPayload<{}>
type UserWithPosts = Prisma.UserGetPayload<{
include: { posts: true }
}>
```
### Type-safe query fragments with satisfies
Type-safe query fragments:
```typescript
import { Prisma } from '../generated/client'
const userSelect = {
id: true,
email: true,
name: true
} satisfies Prisma.UserSelect
const user = await prisma.user.findUnique({
where: { id: 1 },
select: userSelect
})
```
With the `prisma-client` generator, use TypeScript `satisfies` for typed query fragments. You may still see older examples that use `Prisma.validator()` with `prisma-client-js`.
@@ -0,0 +1,208 @@
# PrismaClient Constructor
Configure Prisma Client when instantiating.
## Basic Instantiation
```typescript
import { PrismaClient } from '../generated/client'
import { PrismaPg } from '@prisma/adapter-pg'
const adapter = new PrismaPg({
connectionString: process.env.DATABASE_URL
})
const prisma = new PrismaClient({ adapter })
```
## Constructor Options
### adapter (Required for the SQL provider workflow)
Driver adapter instance:
```typescript
import { PrismaPg } from '@prisma/adapter-pg'
const adapter = new PrismaPg({
connectionString: process.env.DATABASE_URL
})
const prisma = new PrismaClient({ adapter })
```
### accelerateUrl (For Accelerate users)
```typescript
import { withAccelerate } from '@prisma/extension-accelerate'
const prisma = new PrismaClient({
accelerateUrl: process.env.DATABASE_URL, // prisma:// URL
}).$extends(withAccelerate())
```
### log
Configure logging:
```typescript
const prisma = new PrismaClient({
adapter,
log: ['query', 'info', 'warn', 'error'],
})
```
#### Log levels
| Level | Description |
|-------|-------------|
| `query` | All SQL queries |
| `info` | Informational messages |
| `warn` | Warnings |
| `error` | Errors |
#### Log to events
```typescript
const prisma = new PrismaClient({
adapter,
log: [
{ level: 'query', emit: 'event' },
{ level: 'error', emit: 'stdout' },
],
})
prisma.$on('query', (e) => {
console.log('Query:', e.query)
console.log('Duration:', e.duration, 'ms')
})
```
### errorFormat
Control error formatting:
```typescript
const prisma = new PrismaClient({
adapter,
errorFormat: 'pretty', // 'pretty' | 'colorless' | 'minimal'
})
```
### comments
Attach SQL commenter plugins for observability, tracing, or query insights:
```typescript
import { PrismaClient } from '../generated/client'
import { PrismaPg } from '@prisma/adapter-pg'
import { prismaQueryInsights } from '@prisma/sqlcommenter-query-insights'
import { queryTags, withQueryTags } from '@prisma/sqlcommenter-query-tags'
import { traceContext } from '@prisma/sqlcommenter-trace-context'
const prisma = new PrismaClient({
adapter: new PrismaPg(process.env.DATABASE_URL!),
comments: [prismaQueryInsights(), traceContext(), queryTags()],
})
await withQueryTags({ route: '/api/users', requestId: 'req-123' }, () =>
prisma.user.findMany(),
)
```
Use `comments` only for SQL providers. This is the clean way to add trace or query-shape metadata without changing your query calls.
### transactionOptions
Default transaction settings:
```typescript
const prisma = new PrismaClient({
adapter,
transactionOptions: {
maxWait: 5000, // Max wait to acquire transaction (ms)
timeout: 10000, // Max transaction duration (ms)
isolationLevel: 'Serializable',
},
})
```
## Singleton Pattern
Prevent multiple client instances in development:
```typescript
// lib/prisma.ts
import { PrismaClient } from '../generated/client'
import { PrismaPg } from '@prisma/adapter-pg'
const globalForPrisma = globalThis as unknown as {
prisma: PrismaClient | undefined
}
function createPrismaClient() {
const adapter = new PrismaPg({
connectionString: process.env.DATABASE_URL!
})
return new PrismaClient({ adapter })
}
export const prisma = globalForPrisma.prisma ?? createPrismaClient()
if (process.env.NODE_ENV !== 'production') {
globalForPrisma.prisma = prisma
}
```
## Next.js Pattern
```typescript
// lib/prisma.ts
import { PrismaClient } from '@/generated/client'
import { PrismaPg } from '@prisma/adapter-pg'
const createAdapter = () => new PrismaPg({
connectionString: process.env.DATABASE_URL!
})
const prismaClientSingleton = () => {
return new PrismaClient({ adapter: createAdapter() })
}
declare const globalThis: {
prismaGlobal: ReturnType<typeof prismaClientSingleton>
} & typeof global
const prisma = globalThis.prismaGlobal ?? prismaClientSingleton()
export default prisma
if (process.env.NODE_ENV !== 'production') {
globalThis.prismaGlobal = prisma
}
```
## Query Events
Listen to query events:
```typescript
const prisma = new PrismaClient({
adapter,
log: [{ level: 'query', emit: 'event' }],
})
prisma.$on('query', (e) => {
console.log('Query:', e.query)
console.log('Params:', e.params)
console.log('Duration:', e.duration)
})
```
## Log Events
```typescript
prisma.$on('info', (e) => console.log(e.message))
prisma.$on('warn', (e) => console.warn(e.message))
prisma.$on('error', (e) => console.error(e.message))
```
@@ -0,0 +1,256 @@
# Filter Conditions and Operators
Filter operators for the `where` clause.
## Equality
```typescript
// Exact match (implicit)
where: { email: 'alice@prisma.io' }
// Explicit equals
where: { email: { equals: 'alice@prisma.io' } }
// Not equal
where: { email: { not: 'alice@prisma.io' } }
```
## Comparison
```typescript
// Greater than
where: { age: { gt: 18 } }
// Greater than or equal
where: { age: { gte: 18 } }
// Less than
where: { age: { lt: 65 } }
// Less than or equal
where: { age: { lte: 65 } }
// Combined
where: { age: { gte: 18, lte: 65 } }
```
## Lists
```typescript
// In array
where: { role: { in: ['ADMIN', 'MODERATOR'] } }
// Not in array
where: { role: { notIn: ['GUEST', 'BANNED'] } }
```
## String Filters
```typescript
// Contains
where: { email: { contains: 'prisma' } }
// Starts with
where: { email: { startsWith: 'alice' } }
// Ends with
where: { email: { endsWith: '@prisma.io' } }
// Case-insensitive (default for some databases)
where: {
email: {
contains: 'PRISMA',
mode: 'insensitive'
}
}
```
## Null Checks
```typescript
// Is null
where: { deletedAt: null }
// Is not null
where: { deletedAt: { not: null } }
// Using isSet (for optional fields)
where: { middleName: { isSet: true } }
```
## Logical Operators
### AND (implicit)
```typescript
// Multiple conditions = AND
where: {
email: { contains: '@prisma.io' },
role: 'ADMIN'
}
```
### AND (explicit)
```typescript
where: {
AND: [
{ email: { contains: '@prisma.io' } },
{ role: 'ADMIN' }
]
}
```
### OR
```typescript
where: {
OR: [
{ email: { contains: '@gmail.com' } },
{ email: { contains: '@prisma.io' } }
]
}
```
### NOT
```typescript
where: {
NOT: {
role: 'GUEST'
}
}
// Multiple NOT conditions
where: {
NOT: [
{ role: 'GUEST' },
{ verified: false }
]
}
```
### Combined
```typescript
where: {
AND: [
{ verified: true },
{
OR: [
{ role: 'ADMIN' },
{ role: 'MODERATOR' }
]
}
],
NOT: { deletedAt: { not: null } }
}
```
## Relation Filters
### some
At least one related record matches:
```typescript
// Users with at least one published post
where: {
posts: {
some: { published: true }
}
}
```
### every
All related records match:
```typescript
// Users where all posts are published
where: {
posts: {
every: { published: true }
}
}
```
### none
No related records match:
```typescript
// Users with no published posts
where: {
posts: {
none: { published: true }
}
}
```
### is / isNot (1-to-1)
```typescript
// Users with profile in specific country
where: {
profile: {
is: { country: 'USA' }
}
}
// Users without profile
where: {
profile: {
isNot: null
}
}
```
## Array Field Filters
For fields like `String[]`:
```typescript
// Has element
where: { tags: { has: 'typescript' } }
// Has some elements
where: { tags: { hasSome: ['typescript', 'javascript'] } }
// Has every element
where: { tags: { hasEvery: ['typescript', 'prisma'] } }
// Is empty
where: { tags: { isEmpty: true } }
```
## JSON Filters
```typescript
// Path-based filter
where: {
metadata: {
path: ['settings', 'theme'],
equals: 'dark'
}
}
// String contains in JSON
where: {
metadata: {
path: ['bio'],
string_contains: 'developer'
}
}
```
## Full-Text Search
```typescript
// Requires @@fulltext index
where: {
content: {
search: 'prisma database'
}
}
```
@@ -0,0 +1,281 @@
# Model Queries
CRUD operations for your Prisma models.
## Read Operations
### findUnique
Find a single record by unique field:
```typescript
const user = await prisma.user.findUnique({
where: { id: 1 }
})
const user = await prisma.user.findUnique({
where: { email: 'alice@prisma.io' }
})
```
#### With composite unique key
```typescript
// Model with @@unique([firstName, lastName])
const user = await prisma.user.findUnique({
where: {
firstName_lastName: {
firstName: 'Alice',
lastName: 'Smith'
}
}
})
```
### findUniqueOrThrow
Same as findUnique but throws if not found:
```typescript
const user = await prisma.user.findUniqueOrThrow({
where: { id: 1 }
})
// Throws PrismaClientKnownRequestError if not found
```
### findFirst
Find first matching record:
```typescript
const user = await prisma.user.findFirst({
where: { role: 'ADMIN' },
orderBy: { createdAt: 'desc' }
})
```
### findFirstOrThrow
```typescript
const user = await prisma.user.findFirstOrThrow({
where: { role: 'ADMIN' }
})
```
### findMany
Find multiple records:
```typescript
const users = await prisma.user.findMany({
where: { role: 'USER' },
orderBy: { name: 'asc' },
take: 10,
skip: 0
})
```
## Create Operations
### create
Create a single record:
```typescript
const user = await prisma.user.create({
data: {
email: 'alice@prisma.io',
name: 'Alice'
}
})
```
#### With relations
```typescript
const user = await prisma.user.create({
data: {
email: 'alice@prisma.io',
posts: {
create: [
{ title: 'First Post' },
{ title: 'Second Post' }
]
}
},
include: { posts: true }
})
```
### createMany
Create multiple records:
```typescript
const result = await prisma.user.createMany({
data: [
{ email: 'alice@prisma.io', name: 'Alice' },
{ email: 'bob@prisma.io', name: 'Bob' }
],
skipDuplicates: true // Skip records with duplicate unique fields
})
// Returns { count: 2 }
```
### createManyAndReturn
Create multiple and return them:
```typescript
const users = await prisma.user.createManyAndReturn({
data: [
{ email: 'alice@prisma.io', name: 'Alice' },
{ email: 'bob@prisma.io', name: 'Bob' }
]
})
// Returns array of created users
```
## Update Operations
### update
Update a single record:
```typescript
const user = await prisma.user.update({
where: { id: 1 },
data: { name: 'Alice Smith' }
})
```
#### Atomic operations
```typescript
const post = await prisma.post.update({
where: { id: 1 },
data: {
views: { increment: 1 },
likes: { decrement: 1 },
score: { multiply: 2 },
rating: { divide: 2 },
version: { set: 5 }
}
})
```
### updateMany
Update multiple records:
```typescript
const result = await prisma.user.updateMany({
where: { role: 'USER' },
data: { verified: true }
})
// Returns { count: 42 }
```
### updateManyAndReturn
```typescript
const users = await prisma.user.updateManyAndReturn({
where: { role: 'USER' },
data: { verified: true }
})
// Returns array of updated users
```
### upsert
Update or create:
```typescript
const user = await prisma.user.upsert({
where: { email: 'alice@prisma.io' },
update: { name: 'Alice Smith' },
create: { email: 'alice@prisma.io', name: 'Alice' }
})
```
## Delete Operations
### delete
Delete a single record:
```typescript
const user = await prisma.user.delete({
where: { id: 1 }
})
// Returns deleted record
```
### deleteMany
Delete multiple records:
```typescript
const result = await prisma.user.deleteMany({
where: { role: 'GUEST' }
})
// Returns { count: 5 }
// Delete all
const result = await prisma.user.deleteMany({})
```
## Aggregation Operations
### count
```typescript
const count = await prisma.user.count({
where: { role: 'ADMIN' }
})
```
### aggregate
```typescript
const result = await prisma.post.aggregate({
_avg: { views: true },
_sum: { views: true },
_min: { views: true },
_max: { views: true },
_count: { _all: true }
})
```
### groupBy
```typescript
const groups = await prisma.user.groupBy({
by: ['country'],
_count: { _all: true },
_avg: { age: true },
having: {
age: { _avg: { gt: 30 } }
}
})
```
## Return Types
| Method | Returns |
|--------|---------|
| `findUnique` | Record \| null |
| `findUniqueOrThrow` | Record (throws if not found) |
| `findFirst` | Record \| null |
| `findFirstOrThrow` | Record (throws if not found) |
| `findMany` | Record[] |
| `create` | Record |
| `createMany` | { count: number } |
| `createManyAndReturn` | Record[] |
| `update` | Record |
| `updateMany` | { count: number } |
| `delete` | Record |
| `deleteMany` | { count: number } |
| `count` | number |
| `aggregate` | Aggregate result |
| `groupBy` | Group result[] |
@@ -0,0 +1,276 @@
# Query Options
Options for controlling query behavior.
## select
Choose specific fields to return:
```typescript
const user = await prisma.user.findUnique({
where: { id: 1 },
select: {
id: true,
name: true,
email: true,
// password: false (excluded by not including)
}
})
// Returns: { id: 1, name: 'Alice', email: 'alice@prisma.io' }
```
### Select relations
```typescript
const user = await prisma.user.findUnique({
where: { id: 1 },
select: {
name: true,
posts: {
select: {
title: true,
published: true
}
}
}
})
```
### Select with include inside
```typescript
const user = await prisma.user.findMany({
select: {
name: true,
posts: {
include: {
comments: true
}
}
}
})
```
### Select relation count
```typescript
const users = await prisma.user.findMany({
select: {
name: true,
_count: {
select: { posts: true }
}
}
})
// Returns: { name: 'Alice', _count: { posts: 5 } }
```
## include
Include related records:
```typescript
const user = await prisma.user.findUnique({
where: { id: 1 },
include: {
posts: true,
profile: true
}
})
```
### Filtered include
```typescript
const user = await prisma.user.findUnique({
where: { id: 1 },
include: {
posts: {
where: { published: true },
orderBy: { createdAt: 'desc' },
take: 5
}
}
})
```
### Nested include
```typescript
const user = await prisma.user.findUnique({
where: { id: 1 },
include: {
posts: {
include: {
comments: {
include: {
author: true
}
}
}
}
}
})
```
### Include relation count
```typescript
const users = await prisma.user.findMany({
include: {
_count: {
select: { posts: true, followers: true }
}
}
})
```
## omit
Exclude specific fields:
```typescript
const user = await prisma.user.findUnique({
where: { id: 1 },
omit: {
password: true
}
})
// Returns all fields except password
```
### Omit in relations
```typescript
const users = await prisma.user.findMany({
omit: { password: true },
include: {
posts: {
omit: { content: true }
}
}
})
```
**Note:** Cannot use `select` and `omit` together.
## where
Filter records:
```typescript
const users = await prisma.user.findMany({
where: {
email: { contains: '@prisma.io' },
role: 'ADMIN'
}
})
```
See `filters.md` for detailed filter operators.
## orderBy
Sort results:
```typescript
// Single field
const users = await prisma.user.findMany({
orderBy: { name: 'asc' }
})
// Multiple fields
const users = await prisma.user.findMany({
orderBy: [
{ role: 'desc' },
{ name: 'asc' }
]
})
```
### Order by relation
```typescript
const users = await prisma.user.findMany({
orderBy: {
posts: { _count: 'desc' }
}
})
```
### Null handling
```typescript
const users = await prisma.user.findMany({
orderBy: {
name: { sort: 'asc', nulls: 'last' }
}
})
```
## take & skip
Pagination:
```typescript
// First page
const users = await prisma.user.findMany({
take: 10,
skip: 0
})
// Second page
const users = await prisma.user.findMany({
take: 10,
skip: 10
})
```
### Negative take (reverse)
```typescript
const lastUsers = await prisma.user.findMany({
take: -10,
orderBy: { id: 'asc' }
})
// Returns last 10 users
```
## cursor
Cursor-based pagination:
```typescript
// First page
const firstPage = await prisma.user.findMany({
take: 10,
orderBy: { id: 'asc' }
})
// Next page using cursor
const nextPage = await prisma.user.findMany({
take: 10,
skip: 1, // Skip the cursor record
cursor: { id: firstPage[firstPage.length - 1].id },
orderBy: { id: 'asc' }
})
```
## distinct
Return unique values:
```typescript
const cities = await prisma.user.findMany({
distinct: ['city'],
select: { city: true }
})
```
### Multiple distinct fields
```typescript
const locations = await prisma.user.findMany({
distinct: ['city', 'country']
})
```
@@ -0,0 +1,194 @@
# Raw Queries
Execute raw SQL when Prisma's query API isn't sufficient.
## $queryRaw
Execute SELECT queries and get typed results:
```typescript
const users = await prisma.$queryRaw`
SELECT * FROM "User" WHERE email LIKE ${'%@prisma.io'}
`
```
### With type
```typescript
type User = { id: number; email: string; name: string | null }
const users = await prisma.$queryRaw<User[]>`
SELECT id, email, name FROM "User" WHERE role = ${'ADMIN'}
`
```
### Dynamic table/column names
Use `Prisma.raw()` for identifiers (not safe for user input):
```typescript
import { Prisma } from '../generated/client'
const column = 'email'
const users = await prisma.$queryRaw`
SELECT ${Prisma.raw(column)} FROM "User"
`
```
### With Prisma.sql
Build queries dynamically:
```typescript
import { Prisma } from '../generated/client'
const email = 'alice@prisma.io'
const query = Prisma.sql`SELECT * FROM "User" WHERE email = ${email}`
const users = await prisma.$queryRaw(query)
```
### Join multiple SQL fragments
```typescript
import { Prisma } from '../generated/client'
const conditions = [
Prisma.sql`role = ${'ADMIN'}`,
Prisma.sql`verified = ${true}`
]
const users = await prisma.$queryRaw`
SELECT * FROM "User"
WHERE ${Prisma.join(conditions, ' AND ')}
`
```
## $executeRaw
Execute INSERT, UPDATE, DELETE (returns affected count):
```typescript
const count = await prisma.$executeRaw`
UPDATE "User" SET verified = true WHERE email LIKE ${'%@prisma.io'}
`
console.log(`Updated ${count} users`)
```
### Delete example
```typescript
const deleted = await prisma.$executeRaw`
DELETE FROM "User" WHERE "deletedAt" < ${thirtyDaysAgo}
`
```
### Insert example
```typescript
const inserted = await prisma.$executeRaw`
INSERT INTO "Log" (message, level, timestamp)
VALUES (${message}, ${level}, ${new Date()})
`
```
## $queryRawUnsafe / $executeRawUnsafe
For fully dynamic queries (use with caution!):
```typescript
// ⚠️ SQL injection risk - only use with trusted input
const table = 'User'
const users = await prisma.$queryRawUnsafe(
`SELECT * FROM "${table}" WHERE id = $1`,
userId
)
```
### Parameterized unsafe query
```typescript
const result = await prisma.$executeRawUnsafe(
'UPDATE "User" SET name = $1 WHERE id = $2',
'Alice',
1
)
```
## SQL Injection Prevention
### Safe (parameterized)
```typescript
// ✅ User input is parameterized
const email = userInput
const users = await prisma.$queryRaw`
SELECT * FROM "User" WHERE email = ${email}
`
```
### Unsafe (concatenation)
```typescript
// ❌ SQL injection vulnerability!
const email = userInput
const users = await prisma.$queryRawUnsafe(
`SELECT * FROM "User" WHERE email = '${email}'`
)
```
## Database-Specific Features
### PostgreSQL
```typescript
// Array operations
const users = await prisma.$queryRaw`
SELECT * FROM "User" WHERE 'admin' = ANY(roles)
`
// JSON operations
const users = await prisma.$queryRaw`
SELECT * FROM "User" WHERE metadata->>'theme' = 'dark'
`
```
### MySQL
```typescript
// Full-text search
const posts = await prisma.$queryRaw`
SELECT * FROM Post WHERE MATCH(title, content) AGAINST(${searchTerm})
`
```
## Transactions with Raw Queries
```typescript
await prisma.$transaction(async (tx) => {
await tx.$executeRaw`UPDATE "Account" SET balance = balance - ${amount} WHERE id = ${senderId}`
await tx.$executeRaw`UPDATE "Account" SET balance = balance + ${amount} WHERE id = ${recipientId}`
})
```
## Handling Results
### BigInt handling
PostgreSQL returns BigInt for COUNT:
```typescript
const result = await prisma.$queryRaw<[{ count: bigint }]>`
SELECT COUNT(*) as count FROM "User"
`
const count = Number(result[0].count)
```
### Date handling
```typescript
type Result = { createdAt: Date }
const users = await prisma.$queryRaw<Result[]>`
SELECT "createdAt" FROM "User"
`
// createdAt is already a Date object
```
@@ -0,0 +1,308 @@
# Relation Queries
Query and modify related records.
## Include Relations
Load related records:
```typescript
const user = await prisma.user.findUnique({
where: { id: 1 },
include: {
posts: true,
profile: true
}
})
```
### Filtered include
```typescript
const user = await prisma.user.findUnique({
where: { id: 1 },
include: {
posts: {
where: { published: true },
orderBy: { createdAt: 'desc' },
take: 5,
select: { id: true, title: true }
}
}
})
```
### Nested include
```typescript
const user = await prisma.user.findUnique({
where: { id: 1 },
include: {
posts: {
include: {
comments: {
include: { author: true }
}
}
}
}
})
```
## Select Relations
```typescript
const user = await prisma.user.findUnique({
where: { id: 1 },
select: {
name: true,
posts: {
select: { title: true }
}
}
})
```
## Nested Writes
### Create with relations
```typescript
const user = await prisma.user.create({
data: {
email: 'alice@prisma.io',
posts: {
create: [
{ title: 'Post 1' },
{ title: 'Post 2' }
]
},
profile: {
create: { bio: 'Hello!' }
}
}
})
```
### Create or connect
```typescript
const post = await prisma.post.create({
data: {
title: 'New Post',
author: {
connectOrCreate: {
where: { email: 'alice@prisma.io' },
create: { email: 'alice@prisma.io', name: 'Alice' }
}
}
}
})
```
### Connect existing
```typescript
const post = await prisma.post.create({
data: {
title: 'New Post',
author: {
connect: { id: 1 }
}
}
})
// Shorthand for foreign key
const post = await prisma.post.create({
data: {
title: 'New Post',
authorId: 1
}
})
```
## Update Relations
### Update related records
```typescript
const user = await prisma.user.update({
where: { id: 1 },
data: {
posts: {
update: {
where: { id: 1 },
data: { title: 'Updated Title' }
}
}
}
})
```
### Update many related
```typescript
const user = await prisma.user.update({
where: { id: 1 },
data: {
posts: {
updateMany: {
where: { published: false },
data: { published: true }
}
}
}
})
```
### Upsert related
```typescript
const user = await prisma.user.update({
where: { id: 1 },
data: {
profile: {
upsert: {
create: { bio: 'New bio' },
update: { bio: 'Updated bio' }
}
}
}
})
```
### Disconnect
```typescript
// 1-to-1 optional
const user = await prisma.user.update({
where: { id: 1 },
data: {
profile: { disconnect: true }
}
})
// Many-to-many
const post = await prisma.post.update({
where: { id: 1 },
data: {
tags: {
disconnect: [{ id: 1 }, { id: 2 }]
}
}
})
```
### Delete related
```typescript
const user = await prisma.user.update({
where: { id: 1 },
data: {
posts: {
delete: { id: 1 }
}
}
})
// Delete many
const user = await prisma.user.update({
where: { id: 1 },
data: {
posts: {
deleteMany: { published: false }
}
}
})
```
### Set (replace all)
```typescript
// Replace all related records
const post = await prisma.post.update({
where: { id: 1 },
data: {
tags: {
set: [{ id: 1 }, { id: 2 }]
}
}
})
```
## Relation Filters
### some
At least one matches:
```typescript
const users = await prisma.user.findMany({
where: {
posts: { some: { published: true } }
}
})
```
### every
All match:
```typescript
const users = await prisma.user.findMany({
where: {
posts: { every: { published: true } }
}
})
```
### none
None match:
```typescript
const users = await prisma.user.findMany({
where: {
posts: { none: { published: true } }
}
})
```
### is / isNot (1-to-1)
```typescript
const users = await prisma.user.findMany({
where: {
profile: { is: { country: 'USA' } }
}
})
```
## Count Relations
```typescript
const users = await prisma.user.findMany({
select: {
name: true,
_count: {
select: { posts: true, followers: true }
}
}
})
// { name: 'Alice', _count: { posts: 5, followers: 100 } }
```
### Filter counted relations
```typescript
const users = await prisma.user.findMany({
select: {
name: true,
_count: {
select: {
posts: { where: { published: true } }
}
}
}
})
```
@@ -0,0 +1,184 @@
# Transactions
Execute multiple operations atomically.
## Sequential Transactions
Array of operations executed in order:
```typescript
const [user, post] = await prisma.$transaction([
prisma.user.create({ data: { email: 'alice@prisma.io' } }),
prisma.post.create({ data: { title: 'Hello', authorId: 1 } })
])
```
### All or nothing
If any operation fails, all are rolled back:
```typescript
try {
await prisma.$transaction([
prisma.user.create({ data: { email: 'alice@prisma.io' } }),
prisma.user.create({ data: { email: 'alice@prisma.io' } }) // Duplicate!
])
} catch (e) {
// Both operations rolled back
}
```
## Interactive Transactions
For complex logic and dependent operations:
```typescript
await prisma.$transaction(async (tx) => {
// Decrement sender balance
const sender = await tx.account.update({
where: { id: senderId },
data: { balance: { decrement: amount } }
})
// Check balance
if (sender.balance < 0) {
throw new Error('Insufficient funds')
}
// Increment recipient balance
await tx.account.update({
where: { id: recipientId },
data: { balance: { increment: amount } }
})
})
```
### Transaction options
```typescript
await prisma.$transaction(
async (tx) => {
// operations
},
{
maxWait: 5000, // Max wait to acquire lock (ms)
timeout: 10000, // Max transaction duration (ms)
isolationLevel: 'Serializable' // Isolation level
}
)
```
### Isolation levels
| Level | Description |
|-------|-------------|
| `ReadUncommitted` | Lowest isolation, can read uncommitted changes |
| `ReadCommitted` | Only read committed changes |
| `RepeatableRead` | Consistent reads within transaction |
| `Serializable` | Highest isolation, serialized execution |
## Nested Writes
Automatic transactions for nested operations:
```typescript
// This is automatically a transaction
const user = await prisma.user.create({
data: {
email: 'alice@prisma.io',
posts: {
create: [
{ title: 'Post 1' },
{ title: 'Post 2' }
]
},
profile: {
create: { bio: 'Hello!' }
}
}
})
```
## Transaction Client
The `tx` parameter is a Prisma Client scoped to the transaction:
```typescript
await prisma.$transaction(async (tx) => {
// Use tx instead of prisma
await tx.user.create({ ... })
await tx.post.create({ ... })
// Can call methods
const count = await tx.user.count()
})
```
## OrThrow in Transactions
Use with interactive transactions:
```typescript
await prisma.$transaction(async (tx) => {
// If not found, throws and rolls back entire transaction
const user = await tx.user.findUniqueOrThrow({
where: { id: 1 }
})
await tx.post.create({
data: { title: 'New Post', authorId: user.id }
})
})
```
## Best Practices
### Keep transactions short
```typescript
// Good - only DB operations in transaction
const data = prepareData() // Outside transaction
await prisma.$transaction(async (tx) => {
await tx.user.create({ data })
})
```
### Handle errors
```typescript
try {
await prisma.$transaction(async (tx) => {
// operations
})
} catch (e) {
if (e.code === 'P2002') {
// Handle unique constraint violation
}
throw e
}
```
### Use appropriate isolation
```typescript
// Default is fine for most cases
await prisma.$transaction(async (tx) => {
// operations
})
// Use Serializable for strict consistency
await prisma.$transaction(
async (tx) => { /* operations */ },
{ isolationLevel: 'Serializable' }
)
```
## Sequential vs Interactive
| Feature | Sequential | Interactive |
|---------|------------|-------------|
| Syntax | Array | Async function |
| Dependent ops | No | Yes |
| Conditional logic | No | Yes |
| Performance | Better | More flexible |
| Use case | Simple batch | Complex logic |
+192
View File
@@ -0,0 +1,192 @@
---
name: prisma-compute
description: Prisma Compute deployment and hosting guide. Use whenever the user mentions Prisma Compute, `prisma.compute.ts`, `defineComputeConfig`, deploying or hosting a Prisma app, `@prisma/cli app deploy`, `compute:deploy`, `create-prisma --deploy`, `PRISMA_SERVICE_TOKEN`, `auth workspace`, Compute apps/deployments/build logs/domains, `@prisma/cli agent install`, `@prisma/cli feedback`, localhost vs `0.0.0.0`, deploy port binding, or framework deploy readiness for Hono, Elysia, Next.js, TanStack Start, Astro, Nuxt, Svelte, Nest, Turborepo, or custom/prebuilt artifacts.
license: MIT
metadata:
author: prisma
version: "1.4.1"
---
# Prisma Compute
Guide agents through Prisma Compute app creation, deployment, operations, and framework-specific deploy readiness.
## Prisma Compute CLI Surface
Use the Prisma Platform CLI for Compute app workflows:
```bash
bunx @prisma/cli@latest app deploy --help
bunx @prisma/cli@latest app --help
bunx @prisma/cli@latest build logs --help
bunx create-prisma@latest --help
```
Use `@prisma/cli@latest` for Compute app deployment. Use `create-prisma@latest` for new-project scaffolding.
## Send Feedback and Report CLI Issues
The CLI has a built-in feedback channel. Use it whenever a command crashes (`UNEXPECTED_ERROR`), a failure survives troubleshooting, or the user asks to send feedback to the Prisma team:
```bash
bunx @prisma/cli@latest feedback "app deploy crashed: <first error line>"
bunx @prisma/cli@latest feedback "love the deploy flow" --email you@example.com
```
Crash output points here on its own: `--json` crash envelopes carry the exact pre-filled command as a `recover` entry in `nextActions` (run it verbatim), and human crash output ends with a `Tell us what happened:` hint. Feedback is anonymous unless `--email` is passed and attaches only the CLI version, node version, and OS platform/arch. Never include secrets, connection URLs, or user data in the message.
## Source-of-Truth Order
Use evidence in this order when deciding what to edit or run:
1. The project's generated scripts and config, especially `prisma.compute.ts`, `compute:deploy`, framework config, and `package.json`.
2. CLI help output from `create-prisma` and `@prisma/cli`.
3. Local installed package code, generated artifacts, and type definitions.
4. Official docs.
## When to Apply
Use this skill for:
- Creating a new app that can deploy to Prisma Compute
- Deploying an existing TypeScript app to Prisma Compute
- Creating or updating a typed `prisma.compute.ts` deploy config
- Deciding whether a framework is Compute-ready
- Debugging `create-prisma --deploy`, `compute:deploy`, or `app deploy`
- Managing Compute app logs, deployments, environment variables, and domains, and listing platform branches (`branch list`; there are no branch create/remove commands)
- Inspecting GitHub/Console build logs and GitHub push-to-deploy status
- Running non-interactive deploys with browser auth, multiple stored workspaces, or Prisma service tokens
- Switching, selecting, listing, or logging out local Prisma Platform workspaces for `@prisma/cli`
- Installing or updating Prisma skills with `@prisma/cli agent install|update|status`
- Sending feedback or reporting unresolvable CLI failures with `@prisma/cli feedback`
- Programmatic deployments with `@prisma/compute-sdk` or Management API integrations
## Decision Tree
1. Existing project deployment or redeploy:
Read [`references/app-deploy-cli.md`](references/app-deploy-cli.md).
2. Typed Compute config, monorepos, deploy targets, app roots, or build/env defaults:
Read [`references/compute-config.md`](references/compute-config.md).
3. Framework-specific build/runtime work:
Read [`references/frameworks.md`](references/frameworks.md).
4. New project from a scaffold:
Read [`references/create-prisma.md`](references/create-prisma.md).
5. Programmatic deployment, SDKs, APIs, or low-level App/Deployment concepts:
Read [`references/sdk-api.md`](references/sdk-api.md).
6. Build, auth, env, deploy, or runtime failures:
Read [`references/troubleshooting.md`](references/troubleshooting.md).
## Rules by Priority
| Priority | Category | Impact | Prefix |
|----------|----------|--------|--------|
| 1 | Command verification | CRITICAL | `verify-` |
| 2 | Auth and workspace selection | CRITICAL | `auth-` |
| 3 | Framework readiness | CRITICAL | `framework-` |
| 4 | Runtime host and port binding | CRITICAL | `runtime-` |
| 5 | Typed Compute config | HIGH | `config-` |
| 6 | Branch, environment, and database wiring | HIGH | `env-` |
| 7 | Deploy operations | HIGH | `deploy-` |
| 8 | SDK and API automation | MEDIUM | `sdk-` |
## Quick Rules
### 1. Command Verification
- `verify-help-first` - Use CLI help output to confirm command syntax while working.
- `verify-prisma-vs-platform-cli` - Do not assume `prisma app deploy` exists in the ORM CLI; check whether the task should use `@prisma/cli`.
- `verify-generated-scripts` - Prefer the generated `compute:deploy` script when a project already has one.
- `verify-public-url` - After a real deploy, request the public deployment URL instead of trusting local or readiness-only checks.
- `verify-config-support` - Treat `prisma.compute.ts` as the typed Compute config; inspect the project's config and generated scripts before editing or deploying.
- `verify-auth-workspace-support` - Use `@prisma/cli auth workspace` commands for local workspace list/use/logout flows.
### 2. Auth and Workspace Selection
- `auth-source-precedence` - A non-empty `PRISMA_SERVICE_TOKEN` is the active auth source for commands and local OAuth workspaces are ignored for execution. If it is set but empty, the CLI should fail instead of falling back to stored OAuth.
- `auth-multi-workspace` - `auth login` can store OAuth sessions for multiple workspaces on the same machine. The active workspace pointer selects which stored OAuth grant normal commands use.
- `auth-list-before-switch` - Use `auth workspace list --json` to inspect local sessions. Agents should prefer workspace ids from JSON over names because names can be ambiguous.
- `auth-switch-explicitly` - Use `auth workspace use <id-or-name>` for non-interactive switching. Use `auth workspace use` with no argument only for an interactive picker or when exactly one local OAuth workspace exists.
- `auth-no-fallthrough` - If the active OAuth workspace is logged out or fails refresh, the CLI should not silently fall through to another cached workspace. Run `auth workspace use <id>` to choose the next workspace.
- `auth-single-workspace-logout` - Use `auth workspace logout <id-or-name>` or `auth logout --workspace <id-or-name>` to remove one local OAuth workspace session. Plain `auth logout` clears all local OAuth workspace sessions.
- `auth-service-token-switching` - While `PRISMA_SERVICE_TOKEN` is set, `auth workspace use` is unavailable because the service token is the active auth source; unset the env var to switch local OAuth workspaces. Workspace logout still only cleans local OAuth state.
- `auth-storage-awareness` - Local OAuth credentials live in the platform auth file, with workspace metadata in a sidecar context file. Project pins live in `.prisma/local.json`, and CLI app/project state lives in `.prisma/cli/state.json` near `prisma.compute.ts` when present.
### 3. Framework Readiness
- `framework-cli-first` - Evaluate deploy readiness against `@prisma/cli app deploy`, not against what `create-prisma` can scaffold.
- `framework-supported-cli-deploy` - Compute deploy supports `nextjs`, `nuxt`, `astro`, `hono`, `nestjs`, `tanstack-start`, `custom`, and `bun`.
- `framework-create-prisma-defaults-only` - `create-prisma` can provide generated defaults and `compute:deploy`, but it is not the general deploy surface for existing apps.
- `framework-build-output` - Compute needs a server entrypoint or framework artifact, not only static output.
### 4. Runtime Host and Port Binding
- `runtime-bind-all-interfaces` - Deployed servers must bind on all interfaces (`0.0.0.0` or the framework equivalent), not hard-coded `localhost` or `127.0.0.1`.
- `runtime-match-http-port` - The app must listen on the deployed HTTP port: read `process.env.PORT` when possible, or pass the matching `--http-port`.
- `runtime-readiness-port-only` - Compute readiness watches listening ports; a loopback-only listener can look ready while public ingress cannot reach it.
### 5. Typed Compute Config
- `config-optional-simple-app` - `prisma.compute.ts` is not required to deploy a normal single app; use flags when there is no durable config.
- `config-init-formalizer` - Generate a fresh config with `bunx @prisma/cli@latest init`: it detects the framework, pins name/framework/httpPort (plus entry for Bun/Hono), and offers the Project link. `--format json` writes a dependency-free `prisma.compute.json` instead. `init` refuses when any config already exists, never scaffolds code, and never deploys.
- `config-use-prisma-compute-ts` - Put reusable deploy defaults in `prisma.compute.ts` with `defineComputeConfig`, not in `prisma.config.ts`.
- `config-app-vs-apps` - Use `app` for a single deploy target and `apps` for monorepos or multi-app repos; define exactly one.
- `config-monorepo-roots` - For monorepos, use `prisma.compute.ts` to declare app targets, roots, framework defaults, entrypoints, ports, and env inputs.
- `config-targets` - In multi-app configs, `@prisma/cli app deploy web` selects the `apps.web` target. Without `[app]`, commands can infer the target from the current directory; otherwise deploy can run all targets while build/run require one.
- `config-region-new-app-only` - A config `region` is only a default for newly created apps; deploys to existing apps keep the app's current region.
- `config-custom-artifact` - Use `framework: "custom"` with `build.outputDirectory` and `build.entrypoint` for prebuilt or custom-built artifacts.
- `config-no-project-branch-secrets` - Do not commit Workspace, Project, Branch, production intent, service tokens, or secret values in `prisma.compute.ts`; keep those in flags, `.prisma/local.json`, env storage, or CI secrets. App-level defaults such as `region`, `root`, `framework`, `entry`, `httpPort`, and non-secret env file paths belong in config.
- `config-flags-win` - Explicit deploy flags such as `--framework`, `--entry`, `--http-port`, `--region`, and `--env` override matching config values.
### 6. Branch, Environment, and Database
- `env-do-not-leak-secrets` - Never print full `DATABASE_URL`, service tokens, or secret values.
- `env-deploy-loads-dotenv` - Generated deploy scripts may load env via `prisma.compute.ts` or `--env .env`; inspect the actual script/config before redeploy.
- `env-migrations-separate` - Redeploy scripts do not run migrations or seed data. Run the appropriate Prisma database scripts separately.
- `env-cli-token-name` - `@prisma/cli` uses `PRISMA_SERVICE_TOKEN` for service-token auth.
- `env-branch-scope` - Branch deploys, branch env vars, and branch databases must use the same branch name; pass `--branch <git-name>` explicitly when targeting a preview branch.
- `env-production-vs-preview` - Use `--role production` for production env, `--role preview` for preview template env, and `--branch <git-name>` for branch-specific overrides.
- `env-db-explicit` - Keep database and env wiring explicit through database and project env commands; deploy examples should not add database setup, and deploys do not run migrations, seed data, or create one database per app automatically.
### 7. Deploy Operations
- `deploy-prod-intent` - Use `--prod --yes` only when the user intends a production deploy. The first production deploy of an App auto-promotes without `--prod`; the flag gates subsequent production-branch deploys.
- `deploy-no-promote` - Use `app deploy --no-promote` for build-then-verify: it builds a candidate reachable at its own URL without touching the live deployment, promoted later with `app promote <deployment-id>`.
- `deploy-github-default-branch` - When a Compute app is connected to GitHub push-to-deploy, a merge to the default branch is the production deploy path; check deployment records or GitHub check runs instead of telling users to redeploy the merged PR branch or run a default-branch preview deploy.
- `deploy-build-logs` - Use `@prisma/cli build logs <build-id>` for GitHub/Console build output. Use `app logs` for runtime deployment logs; the two ids are different.
- `deploy-noninteractive-auth` - Non-interactive deploys need either the correct active stored OAuth workspace or a supported service token env var; never print the token.
- `deploy-json-for-agents` - Use `--json --no-interactive` for scripts and agent-readable output.
- `deploy-create-project` - Use `--create-project <name>` only when the user wants deploy to create and link a new project; it conflicts with `--project` and `PRISMA_PROJECT_ID`.
- `deploy-ops-targets` - App show/open/logs/list-deploys/promote/rollback/remove and domain commands can also accept `[app]` targets from `prisma.compute.ts`.
- `deploy-report-cli-bugs` - On `UNEXPECTED_ERROR` or an unresolvable failure, report it with the feedback command; see "Send Feedback and Report CLI Issues" above.
### 8. SDK and API
- `sdk-use-cli-first` - Prefer `@prisma/cli app deploy` for app workflows; use `create-prisma` only to scaffold a new app unless the user is building lower-level automation.
- `sdk-result-handling` - `@prisma/compute-sdk` returns `Result` values; check `isOk()`/`isErr()` instead of relying on exceptions.
## Preferred Workflow
1. Inspect the project: package manager, template/framework, `package.json` scripts, Prisma version, Prisma client location, `prisma.compute.ts`, and existing `compute:deploy`.
2. Verify CLI help output for the package actually being used.
3. Verify auth context before project/app mutations: `auth whoami --json`, and when multiple local sessions may exist, `auth workspace list --json`.
4. Choose the path:
- existing app deploy: config-backed target when present, generated `compute:deploy`, or `@prisma/cli app build/run/deploy` flags
- new app scaffold: `create-prisma`, then generated `compute:deploy` or `@prisma/cli app deploy`
- low-level automation: `@prisma/compute-sdk` or Management API
5. Check framework readiness plus host/port/env/runtime requirements, including project and branch scope.
6. Run a local build or `app build` before deploying when feasible.
7. Deploy with JSON output when automating, then request the public URL and summarize app URL, app id, deployment id, project id, workspace id, and follow-up steps.
8. For GitHub/Console builds, inspect the `Prisma Compute Deploy` check run or `build logs <build-id>` before guessing why a build failed.
## Avoid
- Do not bury Compute deployment guidance in the generic `prisma-cli` skill.
- Do not run `create-prisma` inside an existing app just to deploy it; use the generated `compute:deploy` script or `@prisma/cli app deploy`.
- Do not tell users that every `create-prisma` template can auto-deploy.
- Do not deploy with placeholder `DATABASE_URL` values.
- Do not assume `next start` is the Compute runtime path; Next.js deploys need standalone output.
@@ -0,0 +1,403 @@
# Prisma Platform CLI App Deploy
Use this reference for existing projects and for generated `compute:deploy` scripts.
## Package and Command
Compute app workflows are exposed through the Prisma Platform CLI package:
```bash
bunx @prisma/cli@latest --help
bunx @prisma/cli@latest app --help
bunx @prisma/cli@latest app deploy --help
bunx @prisma/cli@latest build logs --help
```
The examples in help output may call the binary `prisma-cli`. When using package runners, prefer:
```bash
bunx @prisma/cli@latest app deploy
npx @prisma/cli@latest app deploy
pnpm dlx @prisma/cli@latest app deploy
```
## Agent Skill Installation
`@prisma/cli` can install and refresh Prisma skills for local AI coding agents:
```bash
bunx @prisma/cli@latest agent install
bunx @prisma/cli@latest agent install --skill prisma-compute
bunx @prisma/cli@latest agent update
bunx @prisma/cli@latest agent status --json
```
`agent install` and `agent update` shell out to `skills@latest add prisma/skills` through the detected package runner. Use them when the user wants Prisma's agent context installed or refreshed; they are not a deployment command.
## Typed Compute Config
`prisma.compute.ts` is optional for normal single-app deploys and useful for reusable defaults or multi-app targets. Read [`compute-config.md`](compute-config.md) for config shapes, target selection, precedence, and monorepo rules. This reference only shows how deploy commands consume those settings.
## Auth and Project Binding
Useful commands:
```bash
bunx @prisma/cli@latest auth login
bunx @prisma/cli@latest auth whoami
bunx @prisma/cli@latest project list --json
bunx @prisma/cli@latest project show
bunx @prisma/cli@latest project link <project-id-or-name>
```
`@prisma/cli` can keep multiple local browser-login workspace sessions. Running `auth login` again for a different workspace should add/update that workspace session and make it active; it should not delete the existing workspace session. The active workspace pointer decides which stored OAuth workspace normal commands use.
For agents, prefer this flow before project/app mutations:
```bash
bunx @prisma/cli@latest auth whoami --json
bunx @prisma/cli@latest auth workspace list --json
bunx @prisma/cli@latest auth workspace use <workspace-id>
```
Use workspace ids from `auth workspace list --json` when possible. Names are friendlier for humans but can be ambiguous. Use `auth workspace use` with no argument for a human interactive picker; headless scripts should pass an id because no-argument `use` fails non-interactively when multiple local OAuth workspaces exist.
If the active workspace is logged out or its refresh fails, the CLI intentionally does not auto-select another cached workspace. Choose the next workspace explicitly:
Use `auth workspace list --json`, then `auth workspace use <workspace-id>`.
To clean up one local OAuth workspace without clearing every stored workspace session:
```bash
bunx @prisma/cli@latest auth workspace logout <workspace-id-or-name>
# equivalent:
bunx @prisma/cli@latest auth logout --workspace <workspace-id-or-name>
```
Plain `auth logout` clears all local OAuth workspace sessions. It does not unset `PRISMA_SERVICE_TOKEN`.
For a new linked project:
```bash
bunx @prisma/cli@latest project create my-app --json
```
For non-interactive or CI work, `@prisma/cli` accepts a workspace service token through `PRISMA_SERVICE_TOKEN`. A non-empty service token takes precedence over stored browser-login credentials, so local OAuth workspace switching does not affect command execution while the env var is set. `auth workspace list --json` may still show local OAuth sessions, but they are not switchable until the service-token env var is unset. Verify auth with `auth whoami` and never print the token value.
If `PRISMA_SERVICE_TOKEN` is set but empty, unset it or provide a real token. The CLI should fail instead of silently falling back to local OAuth credentials.
Local auth storage is useful for debugging but should not be printed verbatim:
- `PRISMA_COMPUTE_AUTH_FILE` can override the auth file path.
- On macOS, the default OAuth credentials file is `~/Library/Application Support/prisma/auth.json`.
- Workspace metadata and the active workspace pointer live beside it as `auth.context.json`.
- Project pins live in `.prisma/local.json`.
- Local CLI state such as selected app and known live deployment lives in `.prisma/cli/state.json`, rooted near `prisma.compute.ts` when a config is discovered.
## Project, Branch, Database, and Env Scope
Compute deploys resolve a target project, app, and branch. Be explicit when the user's intent is not the already linked default project/app:
```bash
bunx @prisma/cli@latest project show --json
bunx @prisma/cli@latest app deploy --project proj_123 --app my-api --branch feature/login --json
```
If `prisma.compute.ts` defines a `name` or an `apps` key, that config can provide the app name. `--app` and `PRISMA_APP_ID` rank above the config value. `[app]` selects a target from `apps`:
```bash
bunx @prisma/cli@latest app deploy api --project proj_123 --branch feature/login --json
```
See [`compute-config.md`](compute-config.md) for no-argument target inference, deploy-all, and build/run target rules.
Branch scope must line up across deploys, databases, and env vars:
- `app deploy --branch <git-name>` creates a deployment for that branch.
- `database create <name> --branch <git-name>` creates a Prisma Postgres database for that branch scope.
- `project env add/update/list/remove --branch <git-name>` manages branch-specific env overrides.
- `project env add/update/list/remove --role production` manages production env.
- `project env add/update/list/remove --role preview` manages preview-template env.
Do not assume a local Git branch was used by the CLI unless the generated script or command output says so. If a user asks for `feature/login`, pass `--branch feature/login` consistently to app, database, and env commands.
Promotion is a separate production action: `app promote <deployment-id>` rebuilds a deployment with production env vars. Do not treat a preview branch deploy as production promotion.
## Deployment Story: GitHub vs CLI
When a Compute app is connected to GitHub push-to-deploy, the default branch is the production deploy path. If a PR has been merged into `main` or another configured default branch, the natural answer is that the changes should appear in production after the production deployment completes; use CLI deploys for explicit manual deploys, local-source deploys, or repositories that are not using GitHub push-to-deploy.
`app show`, `app list-deploys`, and `app logs` expose `--app`, `--project`, and for logs `--deployment`, not `--branch`. For branch debugging, capture the deployment id from deploy JSON and inspect that deployment or its logs.
`app deploy --create-project <name>` creates and links a new Project before deploying. Use it only when the user wants a new Project. It conflicts with `--project` and `PRISMA_PROJECT_ID`, and `--yes` alone does not choose Project scope.
`app deploy --region <region>` only applies when deploy creates a new app. Existing apps keep their current region. Use `prisma.compute.ts` `region` for a durable default, and use the flag only for one-off new-app placement.
## Database and Env
Create a Prisma Postgres database for the linked project:
```bash
bunx @prisma/cli@latest database create main --branch main --json
```
Manage project env vars:
```bash
bunx @prisma/cli@latest project env list
bunx @prisma/cli@latest project env add --file .env --role production
bunx @prisma/cli@latest project env add --file .env.preview --role preview
bunx @prisma/cli@latest project env add DATABASE_URL=postgresql://... --branch feature/foo
bunx @prisma/cli@latest project env update --file .env --role production
bunx @prisma/cli@latest project env update DATABASE_URL=postgresql://... --branch feature/foo
bunx @prisma/cli@latest project env list --branch feature/foo
bunx @prisma/cli@latest project env remove STRIPE_KEY --role preview
```
`app deploy --env .env` loads environment variables from a file for the deployment. A config-backed deploy can instead load env through `prisma.compute.ts` `env`. Neither path is a migration command or seed command.
Database setup is not part of `prisma.compute.ts`. Keep database intent explicit with `database create` and project env commands. Do not add database setup to deploy examples. Treat any generated connection URL as a one-time secret.
Database and env guardrails:
- Deploys do not run migrations, seed data, or schema push. Run the app's own Prisma database command after deploy setup when needed.
- In deploy-all, every target on the same branch shares branch-scoped project env unless you assign app-specific env values yourself.
- Existing database env values supplied through `--env DATABASE_URL=...`, `--env DIRECT_URL=...`, an env file, or project env should be treated as the source of truth.
- Known non-PostgreSQL Prisma schema sources should not be wired to Prisma Postgres automatically.
## Project Git, Branch, and Database Operations
These commands are part of the same Platform CLI surface and often matter while preparing Compute deploys:
```bash
bunx @prisma/cli@latest branch list --json
bunx @prisma/cli@latest git connect git@github.com:org/repo.git --project proj_123
bunx @prisma/cli@latest git disconnect --project proj_123
bunx @prisma/cli@latest database list --branch feature/foo --json
bunx @prisma/cli@latest database show db_123 --json
bunx @prisma/cli@latest database remove db_123 --confirm db_123
bunx @prisma/cli@latest database connection list db_123 --json
bunx @prisma/cli@latest database connection create db_123 --name readonly
bunx @prisma/cli@latest database connection remove conn_123 --confirm conn_123
bunx @prisma/cli@latest database connection rotate conn_123 --confirm conn_123
bunx @prisma/cli@latest database usage db_123 --json
bunx @prisma/cli@latest database backup list db_123 --json
bunx @prisma/cli@latest database restore db_123 --backup bkp_123 --confirm db_123
bunx @prisma/cli@latest project rename new-name --project proj_123
bunx @prisma/cli@latest project transfer proj_123 --to-workspace wksp_456 --confirm proj_123
bunx @prisma/cli@latest project remove proj_123 --confirm proj_123
```
Destructive and ownership-changing commands (`remove`, `restore`, `transfer`, `connection rotate`) require exact `--confirm <id>`; `--yes` is not enough.
Git integration connects a Project to a GitHub repository. Console-side GitHub import can create a Compute app and trigger push-to-deploy for the connected repository, including default-branch production deploys. The CLI `git connect` command is setup, not a local deploy command; use `app deploy` for explicit CLI deploys.
For GitHub-driven deploys, inspect the Console/build-runner state, deployment records, build logs, or the `Prisma Compute Deploy` GitHub check run instead of assuming local CLI output exists. The build runner can perform branch-aware database/env wiring: a preview branch with a Prisma schema and no `DATABASE_URL` can get a branch-scoped preview database, while production can wire a missing `DATABASE_URL` template from an existing ready database. GitHub check runs are the guided feedback path; do not promise Vercel-style PR comments.
Database and database-connection commands never print stored secret values in list/show output. `database create` and `database connection create` return a one-time connection URL; treat it as a secret, store it immediately in env if needed, and do not echo it back in summaries. Removal requires exact `--confirm <id>`; `--yes` is not enough.
## Build and Run Locally
Before deploy, verify that the app can produce a Compute artifact:
```bash
bunx @prisma/cli@latest app build --build-type auto
bunx @prisma/cli@latest app run --build-type auto --port 3000
```
For Bun/server entrypoints:
```bash
bunx @prisma/cli@latest app build --build-type bun --entry src/index.ts
bunx @prisma/cli@latest app run --build-type bun --entry src/index.ts --port 8080
```
For NestJS, use `app build` to validate the Compute artifact and run the framework's own dev command locally:
```bash
bunx @prisma/cli@latest app build --build-type nestjs
bun run dev
```
With a compute config, pass the target name instead of repeating framework/entry/port flags:
```bash
bunx @prisma/cli@latest app build api
bunx @prisma/cli@latest app run api --port 8080
```
`app run --port` sets `PORT` for local development. It does not rewrite an app's explicit host binding, so a local run is not enough to prove the deployed server is reachable from ingress.
`app run --build-type nestjs` is not supported. If a config-backed NestJS target is selected, run the Nest dev server directly instead.
## Deploy
Deploy with prompts:
```bash
bunx @prisma/cli@latest app deploy
```
Agent/script-friendly deploy (do not assume production; add `--prod --yes` only when the user intends a production deploy, and note the first production deploy of an App auto-promotes without `--prod`):
```bash
bunx @prisma/cli@latest app deploy \
--json \
--no-interactive \
--env .env
```
Build-then-verify path for CI: `--no-promote` builds a candidate deployment without changing the live one; it is reachable at its own candidate URL and promoted later with `app promote <deployment-id>`:
```bash
bunx @prisma/cli@latest app deploy --no-promote --json --no-interactive
```
For preview branches, omit `--prod` unless the user explicitly intends a production deploy:
```bash
bunx @prisma/cli@latest app deploy \
--branch feature/foo \
--json \
--no-interactive \
--env .env.preview
```
After a real deploy, verify the public deployment URL. Do not stop at "deploy succeeded" or a local `app run` check:
```bash
curl -i https://<deployment-url>
```
If the deploy command returns JSON, parse the URL from the result and request that exact public URL. Do not accidentally test `localhost` or `127.0.0.1` instead of public ingress.
Create/link a project during deploy:
```bash
bunx @prisma/cli@latest app deploy \
--create-project my-app \
--prod \
--yes \
--env .env
```
Deploy with framework and port:
```bash
bunx @prisma/cli@latest app deploy \
--framework hono \
--http-port 8080 \
--prod \
--yes \
--env .env
```
Deploy a newly created app in a specific region:
```bash
bunx @prisma/cli@latest app deploy \
--app my-api \
--region us-west-1 \
--prod \
--yes \
--env .env
```
`--region` is a new-app placement hint. It does not move an existing app.
Deploy a preview branch with framework and port:
```bash
bunx @prisma/cli@latest app deploy \
--framework hono \
--branch feature/foo \
--http-port 8080 \
--json \
--no-interactive \
--env .env.preview
```
Bun-style app with explicit entrypoint:
```bash
bunx @prisma/cli@latest app deploy \
--framework bun \
--entry src/index.ts \
--http-port 8080 \
--prod \
--yes \
--env .env
```
`--entry <path>` without `--framework` is treated as a Bun app deploy.
Config-backed Bun-style app:
```bash
bunx @prisma/cli@latest app deploy api --prod --yes --env .env
```
Use config for stable app defaults, and flags for one-off project, branch, region, env, and production choices. Keep database setup in explicit database and project-env commands.
## Operations
Inspect and open:
```bash
bunx @prisma/cli@latest app show --json
bunx @prisma/cli@latest app open
```
Deployments:
```bash
bunx @prisma/cli@latest app list-deploys --json
bunx @prisma/cli@latest app show-deploy <deployment-id> --json
bunx @prisma/cli@latest app promote <deployment-id> --yes
bunx @prisma/cli@latest app rollback --to <deployment-id> --yes
bunx @prisma/cli@latest app remove --app my-api --yes
```
Logs:
```bash
bunx @prisma/cli@latest app logs
bunx @prisma/cli@latest app logs --deployment <deployment-id>
bunx @prisma/cli@latest app logs --json
```
Build logs for GitHub/Console builds:
```bash
bunx @prisma/cli@latest build logs <build-id>
bunx @prisma/cli@latest build logs <build-id> --follow
bunx @prisma/cli@latest build logs <build-id> --json
```
`build logs` streams build output keyed by a Build id from a GitHub/Console build or check run. It is separate from runtime `app logs`, which are keyed by the current app deployment or a deployment id.
Domains:
```bash
bunx @prisma/cli@latest app domain add shop.example.com
bunx @prisma/cli@latest app domain show shop.example.com
bunx @prisma/cli@latest app domain wait shop.example.com --timeout 15m
bunx @prisma/cli@latest app domain retry shop.example.com
bunx @prisma/cli@latest app domain remove shop.example.com
```
Custom domain commands target production branch runtime. Do not use a preview branch for production domain setup.
## Output Handling
When `--json` is available, parse the JSON and summarize:
- project id/name
- branch name
- app id/name
- deployment id/status
- build id when present
- deployment URL
- database id/name if one was created
Do not print secret env var values.
@@ -0,0 +1,222 @@
# Prisma Compute Config
Use this reference when creating or updating `prisma.compute.ts`, especially for monorepos, multi-app deploys, reusable framework defaults, env inputs, ports, entrypoints, or build settings.
`prisma.compute.ts` is not required for every deploy. A simple app can deploy with `@prisma/cli app deploy --framework ... --entry ... --http-port ... --env ...`. The config file exists to make those app-level defaults typed and repeatable.
For monorepos or multi-app repositories, use `prisma.compute.ts`: it is the practical way to tell Compute which app target lives at which `root` and which framework/entry/env defaults belong to each target.
## Generating a Config with `init`
Prefer `bunx @prisma/cli@latest init` over hand-writing a fresh single-app config. It detects the framework from the same registry deploy uses, pins `name`, `framework`, and `httpPort` (plus `entry` for Bun and Hono), previews every value with its source, offers the `@prisma/compute-sdk` devDependency for editor types, and offers the Project link. Useful flags: `--framework`, `--entry`, `--http-port`, `--name`, `--no-link`, `--json`.
`--format json` writes a dependency-free static `prisma.compute.json` instead of the TypeScript config; a later explicit `init --format ts` converts it in place when the config needs to become programmatic. `init` fails with `INIT_CONFIG_EXISTS` when any compute config already exists, never scaffolds application code, and never deploys. Multi-app monorepo configs are still written by hand.
## File Names and Discovery
The canonical file is `prisma.compute.ts`. The loader also accepts:
```text
prisma.compute.mts
prisma.compute.js
prisma.compute.mjs
prisma.compute.cjs
prisma.compute.json
```
`prisma.compute.json` is the static, dependency-free variant of the same config; it is discovered and loaded like the others.
Keep exactly one compute config file in a directory. If multiple names exist together, the CLI reports `COMPUTE_CONFIG_INVALID`.
The CLI searches from the invocation directory up to the repository or workspace boundary. Boundaries include `.git`, `pnpm-workspace.yaml`, `bun.lock`, `bun.lockb`, or `package.json#workspaces`. Config-relative paths such as `root` and `env.file` resolve from the config file directory. `--env` flag paths still resolve from the invocation directory.
When a config is discovered, its directory becomes the Compute project directory for local state: `.prisma/local.json` and `.prisma/cli/state.json` live beside that config, not necessarily inside the app root.
## Basic Shape
Import `defineComputeConfig` from `@prisma/compute-sdk/config`. The CLI aliases this helper when loading the config, so the command can evaluate the config without a local SDK install solely for runtime loading.
```typescript
import { defineComputeConfig } from "@prisma/compute-sdk/config";
export default defineComputeConfig({
app: {
name: "api",
framework: "hono",
httpPort: 8080,
env: ".env",
},
});
```
JavaScript configs can default-export a plain object, but prefer `prisma.compute.ts` for type checking.
Define exactly one of:
- `app` for a single deploy target
- `apps` for a monorepo or multi-app repository
Do not define both. Besides `app`/`apps`, the only other allowed top-level key is `region`: a project-level default region applied when deploy creates new apps, overridable per app and by `--region`.
## App Fields
Each app target accepts:
| Field | Meaning |
|-------|---------|
| `name` | Deployed app name. Defaults to the `apps` key, then CLI inference. |
| `region` | Compute region id used only when deploy creates a new app. Existing apps keep their current region. |
| `root` | App directory relative to the config file. Defaults to the config directory. |
| `framework` | Deploy framework: `nextjs`, `nuxt`, `astro`, `hono`, `nestjs`, `tanstack-start`, `custom`, or `bun`. |
| `entry` | Entrypoint path for Bun/Hono-style deploys, relative to the app root. |
| `httpPort` | Deployed HTTP port. Use this for fixed-port apps. |
| `env` | Dotenv file path string, or `{ file, vars }`. Paths resolve from the config directory. |
| `build` | `{ command, outputDirectory, entrypoint }`. Present means the config owns build settings for that target. |
`env` examples:
```typescript
export default defineComputeConfig({
app: {
framework: "nextjs",
env: {
file: [".env", ".env.production"],
vars: {
NODE_ENV: "production",
},
},
},
});
```
Do not put secrets directly in committed `vars`. Keep secret values in platform env, CI secrets, or dotenv files that are intentionally managed outside version control.
`build` examples:
```typescript
export default defineComputeConfig({
app: {
framework: "nextjs",
build: {
command: "pnpm build",
outputDirectory: ".next/standalone",
},
},
});
```
Use `command: null` to skip the build step only when the app root already contains the deployable artifact.
For a custom or prebuilt artifact, make the deploy target explicit:
```typescript
export default defineComputeConfig({
app: {
framework: "custom",
build: {
command: "npm run build",
outputDirectory: "build",
entrypoint: "handler.js",
},
},
});
```
`build.entrypoint` is relative to `build.outputDirectory` when an output directory is set. For Bun/Hono configs without an output directory, an entrypoint-backed build can supply the source entrypoint. Do not set both `entry` and `build.entrypoint` unless they describe the same file.
A config `build` block is accepted for every supported framework: the config-backed build types are `nextjs`, `nuxt`, `astro`, `nestjs`, `tanstack-start`, `custom`, and `bun` (`hono` builds through the `bun` strategy). Only `custom` requires one (`build.outputDirectory` and `build.entrypoint`); for the others it overrides inferred build settings.
## Monorepos and Multi-App Repos
For monorepos, put `prisma.compute.ts` at the repo or workspace root and use `apps`. This keeps project binding and local `.prisma/` state at the repo root while each app builds from its own `root`.
```typescript
import { defineComputeConfig } from "@prisma/compute-sdk/config";
export default defineComputeConfig({
apps: {
web: {
root: "apps/web",
framework: "nextjs",
env: "apps/web/.env",
},
api: {
root: "apps/api",
framework: "hono",
entry: "src/index.ts",
httpPort: 8080,
env: {
file: "apps/api/.env",
vars: {
LOG_LEVEL: "info",
},
},
},
frontend: {
root: "apps/frontend",
framework: "custom",
build: {
command: "pnpm --filter frontend build",
outputDirectory: "dist/server",
entrypoint: "index.mjs",
},
},
},
});
```
Target selection:
```bash
bunx @prisma/cli@latest app deploy web
bunx @prisma/cli@latest app deploy api
bunx @prisma/cli@latest app build api
bunx @prisma/cli@latest app run api --port 8080
```
If no `[app]` argument is passed, commands can infer the target from the invocation directory when it is inside a configured `root`. The deepest matching root wins. If no target is inferred from a multi-app config, a bare deploy can deploy all targets in declaration order:
```bash
bunx @prisma/cli@latest app deploy --branch feature/foo --json --no-interactive
```
Deploy-all rejects per-app overrides such as `--app`, `--framework`, `--entry`, `--http-port`, `--region`, `--env`, and `PRISMA_APP_ID`. Project, branch, production, and confirmation flags still apply to the whole run. Keep database setup in explicit database and project-env commands.
`app build` and `app run` still need one target in multi-app configs because a local build/run command cannot operate N apps at once.
Additional target rules:
- A single-entry `apps` map can deploy its only target without an argument.
- With a single `app` config, `[app]` is accepted only when it equals the configured `name`.
- `[app]` without any compute config file is a usage error.
## Precedence
Explicit flags win over config values:
- `--framework` overrides `framework`
- `--entry` overrides `entry`
- `--http-port` overrides `httpPort`
- `--region` overrides `region`
- any `--env` flag replaces all config env inputs
- `--app` and `PRISMA_APP_ID` rank above config app names
`region` is not an app selector. Config `region` and `--region` are only used when deploy creates a new app. If the selected app already exists, deploy keeps that app's existing region.
`prisma.compute.ts` never selects Workspace, Project, Branch, or production intent. Keep those in CLI flags, environment variables, `.prisma/local.json`, or CI configuration:
```bash
bunx @prisma/cli@latest app deploy api \
--project proj_123 \
--branch feature/foo \
--prod \
--yes
```
## Database Scope
The config does not declare databases. Keep database intent in `database create`, project env commands, or external automation. Read [`app-deploy-cli.md`](app-deploy-cli.md) for deploy-all, migration, and env-var guardrails.
## Relationship to `prisma.config.ts`
Do not put Compute deploy defaults in `prisma.config.ts`. Prisma ORM uses `prisma.config.ts`, while Compute uses `prisma.compute.ts`.
@@ -0,0 +1,117 @@
# create-prisma Compute Flow
Use this reference when creating a new app with Prisma and optionally deploying it to Prisma Compute.
Do not use `create-prisma` as the deploy path for an existing app. For existing projects, use the generated `compute:deploy` script when present, or call `bunx @prisma/cli@latest app deploy` directly.
## Reference
Useful scaffold checks:
```bash
bunx create-prisma@latest --help
bunx create-prisma@latest --version
```
Use `create-prisma@latest` for new-project scaffolding.
## Supported Templates
`create-prisma@latest` scaffolds `hono`, `elysia`, `nest`, `next`, `svelte`, `astro`, `nuxt`, `tanstack-start`, and `turborepo`.
Integrated `--deploy` support applies to `hono`, `elysia`, `nest`, `next`, `astro`, `nuxt`, `tanstack-start`, and `turborepo`. For `turborepo`, the generated config target is usually `api`.
The scaffold template name is `nest`, but the Compute deploy framework/config key is `nestjs`.
`svelte` is scaffold-only for Compute because `@prisma/cli app deploy --framework` has no `svelte` key.
## Basic Commands
Interactive creation:
```bash
bunx create-prisma@latest
```
Non-interactive scaffold only:
```bash
bunx create-prisma@latest \
--name my-api \
--template hono \
--provider postgresql \
--no-install \
--no-generate \
--no-migrate-and-seed \
--no-deploy
```
Create and deploy a supported template:
```bash
bunx create-prisma@latest \
--name my-api \
--template hono \
--provider postgresql \
--deploy
```
## PostgreSQL and Database Behavior
With PostgreSQL, no explicit `--database-url`, and no `--no-prisma-postgres`, the Compute flow can create:
- a Prisma Compute project
- a `main` Prisma Postgres database on the `main` branch
- a `.env` file containing `DATABASE_URL`
- an initial Compute deployment with env vars loaded from `.env`
`create-prisma` is the new-project path. If the user needs a later preview branch deploy, use the generated `compute:deploy` script or `@prisma/cli app deploy --branch <git-name>` after the app exists. Keep branch names aligned across `app deploy --branch`, `database create --branch`, and `project env ... --branch`.
For unattended local tests, pass `--no-prisma-postgres` unless you intentionally want provisioning:
```bash
bunx create-prisma@latest \
--name smoke-app \
--template hono \
--provider postgresql \
--no-prisma-postgres \
--database-url "postgresql://USER:PASSWORD@HOST:PORT/DB" \
--no-deploy
```
Do not deploy placeholder database URLs. If `DATABASE_URL` came from a placeholder default, omit it from deploy env and ask the user for a real production database.
## Generated Deploy Script
When the deploy flow is selected, `create-prisma` can add:
```json
{
"scripts": {
"compute:deploy": "bunx @prisma/cli@latest app deploy --prod --yes ..."
}
}
```
Use the actual generated script from `package.json`; do not reconstruct it from memory. The script redeploys app code using generated flags and/or `prisma.compute.ts`. It does not create a new project, create a new database, run migrations, or seed data. If a scaffolded project does not have `compute:deploy`, use `@prisma/cli app deploy` directly.
Inspect the generated `package.json`, `prisma.compute.ts`, and README before editing deploy behavior.
## Generated Files to Preserve
Preserve generated framework runtime files and `prisma.compute.ts` unless you are intentionally changing the deploy target. For framework-specific deploy/runtime details, read [`frameworks.md`](frameworks.md).
All Prisma 7 scaffolds:
- use `prisma.config.ts`
- load `dotenv/config` where the runtime supports it
- generate Prisma Client into a template-local path such as `src/generated/prisma`
- use `@prisma/adapter-pg` with a `DATABASE_URL` connection string for PostgreSQL
## Addon Notes
`create-prisma` supports `--skills`, `--mcp`, and `--extension`. Those are separate from Compute deployment. Do not imply that enabling skills or MCP deploys the app.
## Failure Handling
If `--deploy` is explicit and setup cannot authenticate, cannot run the Platform CLI, or cannot complete the integrated deploy, report that deploy failed and keep the scaffolded project. Do not delete the user's files.
@@ -0,0 +1,382 @@
# Prisma Compute Framework Readiness
Use this reference when deciding whether and how an app can deploy to Prisma Compute.
## CLI-First Model
Treat `@prisma/cli app deploy` as the deployment surface. Treat `create-prisma` as a new-project scaffold that can generate useful defaults and, for some templates, a `compute:deploy` script.
Compute deploy supports these framework keys:
```text
nextjs
nuxt
astro
hono
nestjs
tanstack-start
custom
bun
```
Auto-detection:
- Next.js: `next.config.*` or `next` dependency
- Nuxt: `nuxt.config.*` or `nuxt` dependency
- Astro: `astro.config.*` or `astro` dependency
- Hono: `hono` dependency
- NestJS: `nest-cli.json` or `@nestjs/core` dependency
- TanStack Start: `@tanstack/react-start` or `@tanstack/solid-start`
- Custom artifact: explicit `framework: "custom"` plus `build.outputDirectory` and `build.entrypoint` in `prisma.compute.ts`
- Bun: explicit `--entry <path>` or `--framework bun`
If detection is ambiguous, set `framework` in `prisma.compute.ts` or pass a supported `--framework` value. If the app is a source-level plain server, use `framework: "bun"` plus `entry`, or pass `--framework bun --entry <path>`, after verifying the server entrypoint. If the app already produces a runnable Node artifact, use `framework: "custom"` with `build.outputDirectory` and `build.entrypoint`.
## CLI Matrix
| App shape | Deploy command shape | Auto-detected | Required output/entry | Notes |
|-----------|----------------------|---------------|-----------------------|-------|
| Next.js | `--framework nextjs` | Yes | standalone `server.js` output | Requires `output: "standalone"` |
| Nuxt | `--framework nuxt` | Yes | `.output/server/index.mjs` | Framework strategy supplies build defaults; a config `build` block is optional |
| Astro | `--framework astro` | Yes | standalone Node server artifact | Framework strategy supplies build defaults; a config `build` block is optional |
| Hono | `--framework hono` | Yes | Bun entry from `main`, `module`, `--entry`, or `src/index.ts` | Usually fixed port `8080` in generated config/scripts |
| NestJS | `--framework nestjs` | Yes | NestJS server artifact | Omit host or bind to `0.0.0.0`; a config `build` block is optional |
| TanStack Start | `--framework tanstack-start` | Yes | `.output/server/index.mjs` | Requires Nitro node output |
| Custom artifact | config-backed `framework: "custom"` | No | configured `build.outputDirectory` and `build.entrypoint` | Use for prebuilt/custom-built Node artifacts |
| Bun / plain server | `--framework bun --entry <path>` | With explicit entry | server entrypoint | Use for Elysia and custom HTTP servers |
| Elysia | `--framework bun --entry src/index.ts` | No dedicated deploy key | Bun entrypoint | Preserve port/host handling |
| SvelteKit | No deploy framework key | No | Node adapter/prebuilt artifact | Do not deploy `vite preview` |
| Turborepo | Deploy concrete app targets | No | app-specific entry/output | Prefer `prisma.compute.ts` with `apps` |
`app build --build-type` uses the framework build type. Build types include `auto`, `nextjs`, `nuxt`, `astro`, `nestjs`, `tanstack-start`, `custom`, and `bun`.
`app run --build-type` is local-dev oriented and supports `auto`, `bun`, and `nextjs`. It streams the local dev server and is not proof that the deployed app is reachable through public ingress.
`prisma.compute.ts` can set framework, entrypoint, HTTP port, env inputs, app root, region, and build settings. A config `build` block is accepted for every supported framework; all build types are config-backed (`nextjs`, `nuxt`, `astro`, `nestjs`, `tanstack-start`, `custom`, `bun`; `hono` builds through the `bun` strategy). For Nuxt, Astro, and NestJS the framework strategy supplies the default build command and output, so a `build` block is optional and normally unnecessary, but it overrides those defaults when present. Only `custom` requires one.
Config snippets below assume:
```typescript
import { defineComputeConfig } from "@prisma/compute-sdk/config";
```
## Universal Runtime Requirements
Compute needs a server process:
- It must listen on the deployed HTTP port. `@prisma/cli app deploy` defaults to the framework's default HTTP port (3000 for most frameworks, 4321 for Astro) unless `--http-port` is passed.
- It must bind on all interfaces. Do not hard-code `localhost` or `127.0.0.1` for a deployed server; use `0.0.0.0`, `server.host: true`, or the framework equivalent.
- It must have a deployable entrypoint or recognized framework output.
- It must not rely on a preview-only command such as `vite preview`.
- It must receive env vars through `--env`, project env, branch env, or external automation.
Check host and port together. A listener on the right port but bound to loopback can appear ready while public ingress cannot reach it.
## Next.js
Deploy shape:
```bash
bunx @prisma/cli@latest app deploy --framework nextjs --env .env
```
`next.config.ts` must include standalone output:
```typescript
import type { NextConfig } from "next"
const nextConfig: NextConfig = {
output: "standalone",
}
export default nextConfig
```
Do not pass `--entry` with `nextjs`; the CLI derives the runtime entrypoint from framework build output.
Do not set `HOSTNAME=localhost` or `HOSTNAME=127.0.0.1` in deploy env. If the standalone server host is overridden, use `0.0.0.0`.
## Hono
Deploy shape:
```bash
bunx @prisma/cli@latest app deploy \
--framework hono \
--http-port 8080 \
--env .env
```
Config shape:
```typescript
export default defineComputeConfig({
app: {
framework: "hono",
entry: "src/index.ts",
httpPort: 8080,
env: ".env",
},
});
```
Project expectations:
- `package.json` has `main` or `module` pointing at the entrypoint, or deploy passes `--entry src/index.ts`
- server uses `@hono/node-server`
- code reads `process.env.PORT` and defaults to the same port used by `--http-port`
- code does not set `hostname` to `localhost` or `127.0.0.1`; if hostname is set explicitly, use `0.0.0.0`
Example runtime shape:
```typescript
const rawPort = (process.env.PORT ?? "").trim()
const parsedPort = rawPort.length > 0 ? Number(rawPort) : Number.NaN
const port = Number.isInteger(parsedPort) ? parsedPort : 8080
serve({ fetch: app.fetch, port })
```
## NestJS
Deploy shape:
```bash
bunx @prisma/cli@latest app deploy --framework nestjs --env .env
```
Config shape:
```typescript
export default defineComputeConfig({
app: {
framework: "nestjs",
env: ".env",
},
});
```
Project expectations:
- detection uses `nest-cli.json` or the `@nestjs/core` dependency; pass `--framework nestjs` when neither signal is present
- `src/main.ts` or the compiled runtime must start an HTTP server
- read `process.env.PORT` and default to the same port used by `--http-port`
- omit the host argument in `app.listen(port)` or pass `"0.0.0.0"`; do not pass `"localhost"` or `"127.0.0.1"`
- use `app build --build-type nestjs` for a Compute artifact check; `app run --build-type nestjs` is not supported, so use the Nest dev server locally
Example runtime shape:
```typescript
const port = Number(process.env.PORT ?? "3000")
await app.listen(port)
```
## TanStack Start
Deploy shape:
```bash
bunx @prisma/cli@latest app deploy --framework tanstack-start --env .env
```
Expected `vite.config.ts` shape:
```typescript
import { defineConfig } from "vite"
import viteReact from "@vitejs/plugin-react"
import { tanstackStart } from "@tanstack/react-start/plugin/vite"
import { nitro } from "nitro/vite"
export default defineConfig({
plugins: [tanstackStart(), nitro(), viteReact()],
})
```
Preserve these details:
- keep `nitro` in `dependencies`
- keep `import { nitro } from "nitro/vite"`
- keep `nitro()` in the Vite plugin list
- keep the React Vite plugin after `tanstackStart()`
- keep Nitro on its default node server preset; do not switch to edge, static, Cloudflare, or another non-Node preset for Compute
The build command is `vite build`. The build must produce `.output/server/index.mjs`, and the production start shape is:
```json
{
"scripts": {
"build": "vite build",
"start": "node .output/server/index.mjs"
}
}
```
Do not deploy TanStack Start as a Bun entrypoint such as `src/router.tsx`. If `.output/server/index.mjs` is missing, fix the TanStack/Nitro build path.
Make sure Nitro does not bind only to localhost in deployment. If host env/config is customized, use the framework's all-interface host setting rather than `localhost`.
## Nuxt
Deploy shape:
```bash
bunx @prisma/cli@latest app deploy --framework nuxt --env .env
```
Config shape:
```typescript
export default defineComputeConfig({
app: {
framework: "nuxt",
env: ".env",
},
});
```
Nuxt uses Nitro output at `.output/server/index.mjs`. Keep the Nitro preset compatible with a Node server runtime.
## Astro
Deploy shape:
```bash
bunx @prisma/cli@latest app deploy --framework astro --env .env
```
Config shape:
```typescript
export default defineComputeConfig({
app: {
framework: "astro",
httpPort: 4321,
env: ".env",
},
});
```
Astro Compute-style server output usually needs:
```javascript
import { defineConfig } from "astro/config"
import node from "@astrojs/node"
export default defineConfig({
output: "server",
adapter: node({ mode: "standalone" }),
server: { host: true },
})
```
## Bun, Elysia, and Plain Source Servers
Use the Bun deploy key for app shapes without a dedicated `--framework` value:
```bash
bunx @prisma/cli@latest app deploy \
--framework bun \
--entry src/index.ts \
--http-port 8080 \
--env .env
```
`app deploy` also treats `--entry <path>` without `--framework` as a Bun app deploy.
Requirements:
- pass `--entry` unless `package.json` `main` or `module` points at the runtime entrypoint
- ensure the entrypoint starts an HTTP server, not only exports handlers
- read `process.env.PORT` or align `--http-port` with the fixed listener port
- bind on all interfaces
Elysia example:
```typescript
const port = Number(process.env.PORT ?? "8080")
app.listen({ port, hostname: "0.0.0.0" })
```
## Custom Build Artifacts
Use `framework: "custom"` when the app is already built, or when a custom command produces a runnable Node artifact that Compute should stage as-is:
```typescript
export default defineComputeConfig({
app: {
framework: "custom",
build: {
command: "npm run build",
outputDirectory: "build",
entrypoint: "handler.js",
},
httpPort: 3000,
env: ".env",
},
});
```
Requirements:
- set both `build.outputDirectory` and `build.entrypoint`
- make `build.entrypoint` relative to `build.outputDirectory`
- ensure the artifact starts an HTTP server and binds on all interfaces
- use `command: null` only when the output directory already contains the deployable artifact
## SvelteKit and Other Frameworks
`@prisma/cli app deploy --framework` has no `svelte` framework key. Do not claim SvelteKit is directly deployable with that name.
For frameworks without a dedicated deploy key, use one of these paths:
- produce a Node server artifact and deploy with config-backed `framework: "custom"`, or through a supported prebuilt/SDK flow
- if the app has a plain Node/Bun server entrypoint, deploy that entrypoint through `--framework bun --entry <path>`
SvelteKit should use a Node adapter or another production server artifact. Do not use `vite preview` as the deployed runtime.
## Turborepo
Deploy concrete app packages, not the monorepo root by default. Prefer `prisma.compute.ts` at the repo root with one `apps` entry per deploy target.
Checklist:
- choose the app directory, such as `apps/api`
- run the workspace build from the correct root/package
- pass the app package's runtime entrypoint or framework
- pass the correct env file, which may live outside the app package
- keep branch env/database scope aligned with the deployed app
Example config:
```typescript
export default defineComputeConfig({
apps: {
web: { root: "apps/web", framework: "nextjs" },
api: {
root: "apps/api",
framework: "bun",
entry: "src/index.ts",
httpPort: 3000,
env: "packages/db/.env",
},
},
});
```
Deploy one target:
```bash
bunx @prisma/cli@latest app deploy api --branch feature/foo --json
```
Flag-only shape after confirming output paths:
```bash
bun run build
bunx @prisma/cli@latest app deploy \
--framework bun \
--entry apps/api/dist/src/index.js \
--http-port 3000 \
--env packages/db/.env
```
Verify the actual output path before using this command.
@@ -0,0 +1,143 @@
# SDK and API Automation
Use this reference when building automation rather than using `create-prisma` or `@prisma/cli app deploy`.
## Prefer the CLI for App Workflows
For normal app deployment:
1. Use generated `compute:deploy` when present.
2. Otherwise use `@prisma/cli app build/run/deploy`.
3. Use SDK/API only for custom automation, platform integrations, or tool builders.
## Compute SDK
Install:
```bash
npm install @prisma/compute-sdk @prisma/management-api-sdk
```
Config helper:
```typescript
import { defineComputeConfig } from "@prisma/compute-sdk/config";
```
Use this import in `prisma.compute.ts` for type checking. The helper is an identity function; the CLI loader aliases the import when it evaluates config files, so a user project does not need the SDK solely to load a Compute config.
Create an authenticated Management API client:
```typescript
import { createManagementApiClient } from "@prisma/management-api-sdk"
const apiClient = createManagementApiClient({
token: process.env.PRISMA_API_TOKEN,
})
```
Token naming differs by surface. `@prisma/cli app ...` uses `PRISMA_SERVICE_TOKEN` for non-interactive service-token auth. The SDK examples here use `PRISMA_API_TOKEN` as an application convention for passing a token into `createManagementApiClient`; the SDK itself only receives the `token` string.
Deploy a prebuilt artifact:
```typescript
import { ComputeClient, PreBuilt } from "@prisma/compute-sdk"
const compute = new ComputeClient(apiClient)
const databaseUrl = process.env.DATABASE_URL
if (!databaseUrl) throw new Error("DATABASE_URL is required")
const result = await compute.deploy({
strategy: new PreBuilt({
appPath: "./dist",
entrypoint: "index.js",
}),
projectId: "proj_abc",
appName: "my-app",
region: "us-east-1",
envVars: { DATABASE_URL: databaseUrl },
portMapping: { http: 3000 },
})
if (result.isOk()) {
console.log(result.value.deploymentEndpointDomain)
} else {
console.error(result.error.message)
}
```
SDK methods return `Result<T, E>`. Check `isOk()` or `isErr()` instead of assuming errors throw. Deploy results expose app/deployment vocabulary including `appId`, `appName`, `projectId`, `region`, `deploymentId`, `deploymentEndpointDomain`, `appEndpointDomain`, `promoted`, `previousDeploymentId`, `previousDeploymentAction`, and `resolvedConfig`.
## SDK Build Strategies
Project Compute SDK strategies:
- `AutoBuild`: tries supported framework strategies such as Next.js, Nuxt, Astro, NestJS, TanStack Start, then Bun
- `NextjsBuild`: requires standalone output and returns `server.js`
- `NuxtBuild`: expects `.output/server/index.mjs`
- `AstroBuild`: expects `dist/server/entry.mjs`
- `NestjsBuild`: builds a NestJS HTTP server artifact
- `TanstackStartBuild`: runs `vite build` and expects a Nitro node server at `.output/server/index.mjs`; keep `tanstackStart()` and `nitro()` in Vite config
- `CustomBuild`: runs optional configured build settings and stages a configured artifact entrypoint
- `BunBuild`: runs `bun build` and needs an explicit entrypoint or `package.json` `main`
- `PreBuilt`: uses an existing artifact directory and relative entrypoint
## Regions
Known SDK region ids:
```text
us-east-1
us-west-1
eu-west-3
eu-central-1
ap-northeast-1
ap-southeast-1
```
Use `--region` in `@prisma/cli app deploy` or `region` in SDK deploy input only when creating a new Compute app. Existing apps keep their current region.
## Management API Concepts
Compute resources map roughly to:
- Project: parent container
- Branch: production or preview scope for env resolution and database/env attachment
- App: stable app endpoint and branch attachment
- Deployment: build artifact plus runtime status and preview URL
Low-level public routes use App/Deployment names:
- list/create apps under a project with `/v1/apps`
- get/update/delete an app
- create/list deployments for an app
- get/start/stop/delete deployments with `/v1/deployments/:deploymentId`
- promote or roll back an app using `deploymentId`
- stream logs with `/v1/deployments/:deploymentId/logs`
- manage custom domains
Internal compatibility aliases may still appear in code. Prefer App/Deployment names in new docs, skills, and automation.
Environment variables are not embedded directly in the low-level deployment create payload. The attached branch's role selects their scope: a preview branch resolves branch-scoped vars, while a production branch (or no branch) resolves project-scoped production vars. Use project/environment-variable APIs or CLI env commands to write env vars first, and keep the branch name consistent across app creation, database creation, and env writes.
When using the CLI alongside SDK automation:
```bash
bunx @prisma/cli@latest project env add --file .env.preview --branch feature/foo
bunx @prisma/cli@latest database create preview-db --branch feature/foo --json
bunx @prisma/cli@latest app deploy --branch feature/foo --json --no-interactive
```
Production promotion is not just "the same branch with another label"; `app promote <deployment-id>` rebuilds with production env vars.
## Secrets and Redaction
Management API deployment inspection exposes env var names with redacted values. Treat any value like `[redacted]` as a marker, not as the deployed value.
Do not log:
- service tokens
- OAuth tokens
- full database URLs
- env var values
- pre-signed upload URLs
@@ -0,0 +1,435 @@
# Troubleshooting Prisma Compute
Use this reference when setup, build, deploy, env, or runtime behavior fails.
## First Checks
Run:
```bash
bunx @prisma/cli@latest --help
bunx @prisma/cli@latest app deploy --help
bunx @prisma/cli@latest auth whoami
bunx @prisma/cli@latest auth workspace list --json
```
Then inspect:
```bash
pwd
cat package.json
find .. -maxdepth 3 \( -name 'prisma.compute.ts' -o -name 'prisma.compute.mts' -o -name 'prisma.compute.js' -o -name 'prisma.compute.mjs' -o -name 'prisma.compute.cjs' \) -print
test -f .env && sed -n 's/=.*/=<redacted>/p' .env
```
Do not print unredacted secrets.
## `prisma.compute.ts` Not Picked Up
This only matters when the project is supposed to use a config-backed deploy. A simple app without `prisma.compute.ts` can still deploy with explicit `app deploy` flags.
Symptoms:
- deploy ignores the expected framework, entrypoint, port, env file, or app root
- a monorepo target such as `api` is not recognized
- local state appears in the wrong `.prisma/` directory
Check:
```bash
pwd
find .. -maxdepth 4 \( -name 'prisma.compute.ts' -o -name 'prisma.compute.mts' -o -name 'prisma.compute.js' -o -name 'prisma.compute.mjs' -o -name 'prisma.compute.cjs' \) -print
bunx @prisma/cli@latest app deploy --help
```
Fix:
- keep exactly one compute config file in the directory where it lives
- put repo-wide or monorepo config at the repository/workspace root
- run commands from inside the repo or workspace boundary so discovery can walk up to the config
- use `[app]` targets from the `apps` keys, such as `bunx @prisma/cli@latest app deploy api`
- remember that config-relative paths such as `root` and `env.file` resolve from the config file directory
## Compute Config Invalid
Symptoms:
- `COMPUTE_CONFIG_INVALID`
- `COMPUTE_CONFIG_TARGET_REQUIRED`
- `COMPUTE_CONFIG_TARGET_UNKNOWN`
- "Multiple compute config files found"
Fix:
- export `defineComputeConfig({ app: ... })` or `defineComputeConfig({ apps: ... })`
- define exactly one of `app` or `apps`
- remove unknown top-level keys
- pass a target for multi-app build/run commands, such as `app build web`
- pass an existing `apps` key for multi-app deploys, such as `app deploy api`
- remove config `build` blocks from `nuxt`, `astro`, and `nestjs` targets
- for `framework: "custom"`, set both `build.outputDirectory` and `build.entrypoint`
- when `build.outputDirectory` is set for a configurable framework, also set `build.entrypoint` if the framework needs a configured runtime entrypoint
Minimal recovery config:
```typescript
import { defineComputeConfig } from "@prisma/compute-sdk/config";
export default defineComputeConfig({
app: {
framework: "hono",
entry: "src/index.ts",
httpPort: 8080,
},
});
```
## `create-prisma --yes` Did Not Deploy
`--yes` skips prompts and does not opt into deploy. Pass `--deploy` explicitly:
```bash
bunx create-prisma@latest --name my-api --template hono --provider postgresql --deploy
```
If the integrated deploy cannot complete, scaffold succeeds but deploy should be reported as failed.
## Accidental Prisma Postgres Provisioning
With PostgreSQL, no `--database-url`, and no `--no-prisma-postgres`, setup can provision Prisma Postgres. For local smoke tests, pass:
```bash
--no-prisma-postgres --database-url "postgresql://USER:PASSWORD@HOST:PORT/DB"
```
Use a disposable real database URL if Prisma commands need to run.
## Auth Fails
Symptoms:
- `project list` fails
- `auth whoami` fails
- browser login was not completed
- commands use the wrong workspace after a second login
- another workspace is stored locally but commands behave signed out
- `PRISMA_SERVICE_TOKEN` is missing, empty, expired, or lacks workspace/project permissions
Fix:
```bash
bunx @prisma/cli@latest auth login
bunx @prisma/cli@latest auth whoami
bunx @prisma/cli@latest auth workspace list --json
```
If multiple local OAuth workspaces exist, switch explicitly. Prefer ids from JSON:
```bash
bunx @prisma/cli@latest auth workspace use <workspace-id>
bunx @prisma/cli@latest auth whoami --json
bunx @prisma/cli@latest project list --json
```
For a human terminal, `auth workspace use` with no argument opens an interactive picker or selects the only local OAuth workspace without prompting. In non-interactive or `--json` mode, use `auth workspace use <id-or-name>` instead.
If the active workspace was logged out or its token refresh failed, the CLI intentionally stays signed out for OAuth commands rather than falling through to another cached workspace. Recover by running `auth workspace list --json` and then `auth workspace use <workspace-id>`.
To remove only one local OAuth workspace session:
```bash
bunx @prisma/cli@latest auth workspace logout <workspace-id-or-name>
# or:
bunx @prisma/cli@latest auth logout --workspace <workspace-id-or-name>
```
Use plain `auth logout` only when you want to clear all local OAuth workspace sessions.
For CI, `@prisma/cli` can authenticate with `PRISMA_SERVICE_TOKEN`:
```bash
test -n "${PRISMA_SERVICE_TOKEN:-}" && echo "PRISMA_SERVICE_TOKEN is set"
bunx @prisma/cli@latest auth whoami
bunx @prisma/cli@latest app deploy --json --no-interactive --prod --yes --env .env
```
If `PRISMA_SERVICE_TOKEN` is set and non-empty, it is the active auth source and local OAuth workspace switching is unavailable for command execution. Unset `PRISMA_SERVICE_TOKEN` before using `auth workspace use` to change local OAuth workspace context.
If `PRISMA_SERVICE_TOKEN` is set but empty, the CLI errors before trying browser-login credentials. Unset it or provide a valid workspace service token. Never echo, log, or paste the token value; only check whether it is present.
Local storage hints for debugging:
- Override auth storage with `PRISMA_COMPUTE_AUTH_FILE` when isolating tests.
- Default macOS OAuth credential file: `~/Library/Application Support/prisma/auth.json`.
- Active workspace metadata sidecar: `~/Library/Application Support/prisma/auth.context.json`.
- Project binding: `.prisma/local.json`.
- Local app/project state: `.prisma/cli/state.json`, usually next to the discovered `prisma.compute.ts`.
Do not print credential files or token values into logs.
## Project Setup Fails
Symptoms:
- `PROJECT_SETUP_REQUIRED`
- non-interactive deploy cannot choose a Project
- deploy was expected to create a Project but did not
Fix:
```bash
bunx @prisma/cli@latest app deploy --project <id-or-name> --json --no-interactive
bunx @prisma/cli@latest app deploy --create-project <name> --yes
```
Do not rely on `--yes` alone to choose Project scope. `--project`, `--create-project`, and `PRISMA_PROJECT_ID` are mutually exclusive.
## Missing or Placeholder `DATABASE_URL`
Symptoms:
- Prisma Client throws `DATABASE_URL is required`
- migration scripts fail immediately
- deploy runs but app fails on database access
Fix:
1. Put a real production-ready `DATABASE_URL` in `.env` or project env.
2. Run `prisma generate`.
3. Run migrations with the project's `db:migrate` or production migration command.
4. Redeploy with `--env .env` or project env configured.
If Prisma Client generation or runtime env loading is the concrete failure, then inspect Prisma-specific config:
```bash
test -f prisma.config.ts && sed -n '1,160p' prisma.config.ts
test -f prisma/schema.prisma && sed -n '1,220p' prisma/schema.prisma
```
Never deploy `postgresql://USER:PASSWORD@HOST:PORT/DATABASE` placeholder values.
## Wrong Branch, Env, or Database
Symptoms:
- preview deploy reads production env
- branch deploy cannot find `DATABASE_URL`
- app is deployed to the expected branch but points at the wrong database
- logs are inspected for the current app while the failing URL belongs to a different deployment id
Check:
```bash
bunx @prisma/cli@latest project show --json
bunx @prisma/cli@latest project env list --role production --json
bunx @prisma/cli@latest project env list --role preview --json
bunx @prisma/cli@latest project env list --branch feature/foo --json
bunx @prisma/cli@latest app list-deploys --json
bunx @prisma/cli@latest app logs --deployment <deployment-id> --json
```
Fix:
- pass the same `--branch <git-name>` to `app deploy`, `database create`, and branch-specific `project env` commands
- use `--role production` for production env and `--role preview` for preview-template env
- capture the deployment id and URL from deploy JSON, then inspect logs with `app logs --deployment <deployment-id>`
- `app show`, `app list-deploys`, and `app logs` do not filter by branch; capture and use the deployment id
- treat `app promote <deployment-id>` as a production action because it rebuilds with production env vars
- do not expect `prisma.compute.ts` to select Project, Branch, production, or database scope; it only supplies app deploy defaults
## Database Wiring or Schema Did Not Apply
Symptoms:
- deploy runs but the app cannot find `DATABASE_URL`
- database env vars exist but the database is empty
- a deploy-all run points multiple apps at the same branch database
Fix:
- read [`app-deploy-cli.md`](app-deploy-cli.md) `Database and Env` for the database/env guardrails
- create and assign database env vars explicitly for the intended branch/app scope
- run migrations, seed, or schema push yourself after database setup; Compute never applies schema changes for you
- for multi-app deploy-all with app-specific database isolation, create and assign those database env vars explicitly before deploy
## Next.js Standalone Missing
Error shape:
```text
Next.js build did not produce standalone output
```
Fix `next.config.ts`:
```typescript
const nextConfig = {
output: "standalone",
}
export default nextConfig
```
Then reinstall/build if needed and deploy again.
## Nitro Entry Missing
Nuxt or TanStack Start error shape:
```text
.output/server/index.mjs
```
General fix:
- ensure the correct framework plugins are installed
- run the framework build locally
- avoid custom Nitro presets that produce a non-Node target
- use the default Nitro node server preset
For TanStack Start specifically:
- keep `nitro` in `dependencies`
- keep `import { nitro } from "nitro/vite"` in `vite.config.ts`
- keep `plugins: [tanstackStart(), nitro(), viteReact()]` or the framework-equivalent plugin order
- run `bun run build` and verify `.output/server/index.mjs` exists
- do not replace the production server with `vite preview`
Compute detection selects TanStack Start when it sees `@tanstack/react-start` or `@tanstack/solid-start`. If the Nitro entrypoint is missing after that, fix the TanStack/Nitro build output; do not assume Compute will silently use a Bun deployment.
## Bun Entrypoint Missing
Error shape:
```text
Entrypoint is required
Entrypoint file does not exist
```
Fix either:
```json
{
"main": "src/index.ts"
}
```
or deploy with:
```bash
bunx @prisma/cli@latest app deploy --framework bun --entry src/index.ts
```
## Port Mismatch
Symptoms:
- deploy succeeds but the app is unreachable
- health checks fail
- logs show the server listening on a different port
Fix:
- read `process.env.PORT`
- pass `--http-port <port>` when the app has a fixed port
- use the generated `compute:deploy` script when it exists
- remember the `@prisma/cli app deploy` default is HTTP `3000`; generated Hono/Elysia projects usually configure `8080` through `prisma.compute.ts` or flag-backed `--http-port 8080` scripts
- use the template defaults: Hono/Elysia `8080`, Next/TanStack/Nuxt `3000`, Astro `4321`
## Public URL Smoke Test Fails
Symptoms:
- deploy command completed
- `app show` or deploy output has a URL
- the public URL times out, returns 5xx, or returns an unexpected page
Check:
```bash
curl -i https://<deployment-url>
curl -i https://<deployment-url>/health
bunx @prisma/cli@latest app logs --json
```
Fix by following the first concrete failure:
- connection timeout or 5xx: check logs, host binding, and port mapping
- unexpected status or body: verify the route path and app framework output
- local URL tested by mistake: rerun against the public deployment URL, not `localhost` or `127.0.0.1`
## Localhost Binding
Symptoms:
- deploy says the app started or the port was observed, but the public URL is unreachable
- logs show a server listening on `localhost` or `127.0.0.1`
- `app run` works locally, but the deployed app cannot receive external traffic
Why this happens:
Compute's boot watcher polls `/proc/net/tcp` and `/proc/net/tcp6` for configured ports entering `LISTEN`. That readiness signal tracks the port, not whether the app bound `127.0.0.1` or all interfaces. A loopback-only listener can therefore look ready while public ingress still cannot reach it.
Fix:
- remove hard-coded `localhost` or `127.0.0.1` server host settings
- bind on `0.0.0.0` or the framework equivalent, such as Astro `server.host: true`
- for Next.js standalone, do not deploy with `HOSTNAME=localhost`; use `HOSTNAME=0.0.0.0` if the host is overridden
- keep port and host fixes together: `0.0.0.0:<deployed-http-port>`
## Env Changes Did Not Apply
Generated `compute:deploy` scripts redeploy using the generated flags and/or `prisma.compute.ts`; they do not run migrations or seed data.
After env changes:
```bash
bunx @prisma/cli@latest project env list
bunx @prisma/cli@latest project env list --branch feature/foo
bunx @prisma/cli@latest app deploy --prod --yes --env .env
bunx @prisma/cli@latest app deploy --branch feature/foo --env .env.preview
```
If using branch-specific env, confirm the branch name and role.
## Need Logs
Runtime logs for the current app:
```bash
bunx @prisma/cli@latest app logs
```
Specific deployment:
```bash
bunx @prisma/cli@latest app logs --deployment <deployment-id>
```
Machine-readable:
```bash
bunx @prisma/cli@latest app logs --json
```
Build logs for GitHub/Console builds:
```bash
bunx @prisma/cli@latest build logs <build-id>
bunx @prisma/cli@latest build logs <build-id> --follow
bunx @prisma/cli@latest build logs <build-id> --json
```
Use `build logs` for build output keyed by a Build id from a GitHub check run, Console build page, or Management API build record. Use `app logs` for runtime logs keyed by the current app deployment or a deployment id.
Summarize relevant errors. Do not paste secrets.
## Report Unresolved CLI Issues
When a CLI failure survives the checks above, or a command crashes with `UNEXPECTED_ERROR`, report it to the Prisma team:
```bash
bunx @prisma/cli@latest feedback "app deploy crashed: <first error line>"
```
Prefer the pre-filled command from a `--json` crash envelope's `nextActions` verbatim. Anonymous; never put secrets, connection URLs, or tokens in the message.
@@ -0,0 +1,192 @@
---
name: prisma-database-setup
description: Guides for configuring Prisma with different database providers (PostgreSQL, MySQL, SQLite, MongoDB, etc.). Use when setting up a new project, changing databases, or troubleshooting connection issues. Triggers on "configure postgres", "connect to mysql", "setup mongodb", "sqlite setup".
license: MIT
metadata:
author: prisma
version: "7.6.0"
---
# Prisma Database Setup
Comprehensive guides for configuring Prisma ORM with various database providers.
## When to Apply
Reference this skill when:
- Initializing a new Prisma project
- Switching database providers
- Configuring connection strings and environment variables
- Troubleshooting database connection issues
- Setting up database-specific features
- Generating and instantiating Prisma Client
## Rule Categories by Priority
| Priority | Category | Impact | Prefix |
|----------|----------|--------|--------|
| 1 | Provider Guides | CRITICAL | provider names |
| 2 | Prisma Postgres | HIGH | `prisma-postgres` |
| 3 | Client Setup | CRITICAL | `prisma-client-setup` |
## System Prerequisites
- **Node.js 20.19.0+**
- **TypeScript 5.4.0+**
## Bun Runtime
If you're using Bun, run Prisma CLI commands with `bunx --bun prisma ...` so Prisma uses the Bun runtime instead of falling back to Node.js.
## Supported Databases
| Database | Provider String | Notes |
|----------|-----------------|-------|
| PostgreSQL | `postgresql` | Default, full feature support |
| MySQL | `mysql` | Widespread support, some JSON diffs |
| SQLite | `sqlite` | Local file-based, no enum/scalar lists |
| MongoDB | `mongodb` | Mongo-specific workflow; do not apply SQL driver-adapter guidance |
| SQL Server | `sqlserver` | Microsoft ecosystem |
| CockroachDB | `cockroachdb` | Distributed SQL, Postgres-compatible |
| Prisma Postgres | `postgresql` | Managed serverless database |
## Configuration Files
Your configuration shape depends on the provider and Prisma major version:
1. **All providers** use **`prisma/schema.prisma`**.
2. **Prisma 7 SQL setups** typically use **`prisma.config.ts`** for datasource URLs.
3. **MongoDB projects should stay on Prisma 6.x**, keep `url = env("DATABASE_URL")` in the schema, and continue using the classic MongoDB setup.
## Driver Adapters
The standard SQL workflow uses a driver adapter. Choose the adapter and driver for your database and pass the adapter to `PrismaClient`.
| Database | Adapter | JS Driver |
|----------|---------|-----------|
| PostgreSQL | `@prisma/adapter-pg` | `pg` |
| CockroachDB | `@prisma/adapter-pg` | `pg` |
| Prisma Postgres (Node.js) | `@prisma/adapter-pg` | `pg` |
| Prisma Postgres (edge/serverless) | `@prisma/adapter-ppg` | `@prisma/ppg` |
| MySQL / MariaDB | `@prisma/adapter-mariadb` | `mariadb` |
| SQLite | `@prisma/adapter-better-sqlite3` | `better-sqlite3` |
| SQLite (Turso/LibSQL) | `@prisma/adapter-libsql` | `@libsql/client` |
| SQL Server | `@prisma/adapter-mssql` | `node-mssql` |
MongoDB should not follow the Prisma 7 SQL adapter workflow. Use the latest Prisma 6.x release for MongoDB projects and do not install a SQL `@prisma/adapter-*` package for it.
Example (PostgreSQL):
```ts
import 'dotenv/config'
import { PrismaClient } from '../generated/client'
import { PrismaPg } from '@prisma/adapter-pg'
const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL })
const prisma = new PrismaClient({ adapter })
```
## Prisma Client Setup (Required)
Prisma Client must be installed and generated for any database.
1. Install Prisma CLI and Prisma Client:
```bash
npm install prisma --save-dev
npm install @prisma/client
```
1. Add a generator block (`prisma-client` requires an explicit output path):
```prisma
generator client {
provider = "prisma-client"
output = "../generated"
}
```
1. Generate Prisma Client:
```bash
npx prisma generate
```
1. For SQL providers, instantiate Prisma Client with the database-specific driver adapter:
```typescript
import { PrismaClient } from '../generated/client'
import { PrismaPg } from '@prisma/adapter-pg'
const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL })
const prisma = new PrismaClient({ adapter })
```
1. Re-run `prisma generate` after every schema change.
## Quick Reference
### PostgreSQL
```prisma
datasource db {
provider = "postgresql"
}
generator client {
provider = "prisma-client"
output = "../generated"
}
```
### MySQL
```prisma
datasource db {
provider = "mysql"
}
generator client {
provider = "prisma-client"
output = "../generated"
}
```
### SQLite
```prisma
datasource db {
provider = "sqlite"
}
generator client {
provider = "prisma-client"
output = "../generated"
}
```
### MongoDB
```prisma
datasource db {
provider = "mongodb"
url = env("DATABASE_URL")
}
generator client {
provider = "prisma-client-js"
}
```
For MongoDB, stay on the latest Prisma 6.x line and keep the connection URL in `schema.prisma`. Do not move a MongoDB project to the Prisma 7 SQL adapter setup. If a MongoDB project asks about upgrading Prisma versions, route to the `prisma-mongodb-upgrade` skill (stay-on-v6 vs Prisma Next is the real decision; Prisma 7 is not an option).
## Rule Files
See individual rule files for detailed setup instructions:
```
references/postgresql.md
references/mysql.md
references/sqlite.md
references/mongodb.md
references/sqlserver.md
references/cockroachdb.md
references/prisma-postgres.md
references/prisma-client-setup.md
```
## How to Use
Choose the provider reference file for your database, then apply `references/prisma-client-setup.md` to complete client generation and adapter setup. For MongoDB, use `references/mongodb.md` instead of copying the SQL adapter examples or Prisma 7 config pattern.
@@ -0,0 +1,89 @@
# CockroachDB Setup
Configure Prisma with CockroachDB.
## Prerequisites
- CockroachDB cluster
## 1. Schema Configuration
In `prisma/schema.prisma`:
```prisma
datasource db {
provider = "cockroachdb"
}
generator client {
provider = "prisma-client"
output = "../generated"
}
```
## 2. Config Configuration
In `prisma.config.ts`:
```typescript
import { defineConfig, env } from 'prisma/config'
export default defineConfig({
schema: 'prisma/schema.prisma',
datasource: {
url: env('DATABASE_URL'),
},
})
```
## 3. Environment Variable
In `.env`:
```env
DATABASE_URL="postgresql://user:password@host:26257/db?sslmode=verify-full"
```
Note: CockroachDB uses the PostgreSQL wire protocol, so the URL often looks like postgresql, but the provider **MUST** be `cockroachdb` in the schema to handle specific CRDB features correctly.
## Driver Adapter
Use a driver adapter for the standard SQL workflow. CockroachDB is PostgreSQL-compatible, so use the PostgreSQL adapter.
1. Install adapter and driver:
```bash
npm install @prisma/adapter-pg pg
```
2. Instantiate Prisma Client with the adapter:
```typescript
import 'dotenv/config'
import { PrismaClient } from '../generated/client'
import { PrismaPg } from '@prisma/adapter-pg'
const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL })
const prisma = new PrismaClient({ adapter })
```
## ID Generation
CockroachDB uses `BigInt` or `UUID` for IDs efficiently.
```prisma
model User {
id BigInt @id @default(autoincrement()) // Uses unique_rowid()
}
```
Or using string UUIDs:
```prisma
model User {
id String @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid
}
```
## Common Issues
### Schema Introspection
Always use `provider = "cockroachdb"` to ensure correct type mapping during `db pull`.
@@ -0,0 +1,90 @@
# MongoDB Setup
MongoDB projects should stay on the latest Prisma 6.x release. Do not upgrade a MongoDB app to Prisma 7's SQL client path.
## Prerequisites
- MongoDB 4.2+
- Replica Set configured (required for transactions)
- Latest Prisma 6.x release, or your team's pinned Prisma 6 version
- Node.js 20.19.0+
- TypeScript 5.4.0+
## 1. Schema Configuration
Use the standard Prisma 6 MongoDB setup with `prisma-client-js`.
In `prisma/schema.prisma`:
```prisma
datasource db {
provider = "mongodb"
url = env("DATABASE_URL")
}
generator client {
provider = "prisma-client-js"
}
```
### Driver Adapters
Do **not** apply the Prisma 7 SQL adapter setup here. MongoDB does not use a SQL `@prisma/adapter-*` package.
### ID Field Requirement
MongoDB models **must** have a mapped `_id` field using `@id` and `@map("_id")`, usually of type `String` with `auto()` and `db.ObjectId`.
```prisma
model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
email String @unique
name String?
}
```
### Relations
Relations in MongoDB expect IDs to be `db.ObjectId` type.
```prisma
model Post {
id String @id @default(auto()) @map("_id") @db.ObjectId
author User @relation(fields: [authorId], references: [id])
authorId String @db.ObjectId
}
```
## 2. Environment Variable
In `.env`:
```env
DATABASE_URL="mongodb+srv://user:password@cluster.mongodb.net/mydb?retryWrites=true&w=majority"
```
## Migrations vs Introspection
- **No Migrations**: MongoDB is schema-less. `prisma migrate` commands **do not work**.
- **db push**: Use `prisma db push` to sync indexes and constraints.
- **db pull**: Use `prisma db pull` to generate schema from existing data (sampling).
## Current Verification Notes
- `prisma init --datasource-provider mongodb` is still implemented in Prisma's CLI source.
- Prisma's upstream repo still contains MongoDB fixtures and tests.
- Local verification shows Prisma 7 can still recognize MongoDB inputs, but the generated client path does not provide a supported MongoDB upgrade path.
- Local verification shows Prisma 6.x works end to end with `prisma-client-js`, `prisma db push`, and `new PrismaClient()` against a MongoDB replica set.
## Version Guidance
- For MongoDB, stay on the latest available Prisma 6.x release.
- Treat Prisma 7 MongoDB migration attempts as unsupported until Prisma ships a real MongoDB upgrade path.
## Common Issues
### "Transactions not supported"
Ensure your MongoDB instance is a **Replica Set**. Standalone instances do not support transactions. Atlas clusters are replica sets by default.
### "Invalid ObjectID"
Ensure fields referencing IDs are decorated with `@db.ObjectId` if the target is an ObjectID.
@@ -0,0 +1,126 @@
# MySQL Setup
Configure Prisma with MySQL (or MariaDB).
## Prerequisites
- MySQL or MariaDB database
- Connection string
## 1. Schema Configuration
In `prisma/schema.prisma`:
```prisma
datasource db {
provider = "mysql"
}
generator client {
provider = "prisma-client"
output = "../generated"
}
```
## 2. Config Configuration
In `prisma.config.ts`:
```typescript
import { defineConfig, env } from 'prisma/config'
export default defineConfig({
schema: 'prisma/schema.prisma',
datasource: {
url: env('DATABASE_URL'),
},
})
```
## 3. Environment Variable
In `.env`:
```env
DATABASE_URL="mysql://user:password@localhost:3306/mydb"
```
### Connection String Format
```
mysql://USER:PASSWORD@HOST:PORT/DATABASE
```
- **USER**: Database user
- **PASSWORD**: Password
- **HOST**: Hostname
- **PORT**: Port (default 3306)
- **DATABASE**: Database name
## Driver Adapter
Use a driver adapter for the standard SQL workflow.
1. Install adapter and driver:
```bash
npm install @prisma/adapter-mariadb mariadb
```
2. Instantiate Prisma Client with the adapter:
```typescript
import 'dotenv/config'
import { PrismaClient } from '../generated/client'
import { PrismaMariaDb } from '@prisma/adapter-mariadb'
const adapter = new PrismaMariaDb({
host: 'localhost',
port: 3306,
connectionLimit: 5,
user: process.env.MYSQL_USER,
password: process.env.MYSQL_PASSWORD,
database: process.env.MYSQL_DATABASE,
})
const prisma = new PrismaClient({ adapter })
```
### Text protocol option
If you need the MariaDB driver's text protocol instead of the default binary `execute()` path, enable `useTextProtocol` explicitly:
```typescript
import { PrismaClient } from '../generated/client'
import { PrismaMariaDb } from '@prisma/adapter-mariadb'
const adapter = new PrismaMariaDb(process.env.DATABASE_URL!, {
useTextProtocol: true,
})
const prisma = new PrismaClient({ adapter })
```
Use this only when you specifically need text-protocol compatibility for your MariaDB setup.
## PlanetScale Setup
PlanetScale uses MySQL but requires specific settings because it doesn't support foreign key constraints.
In `prisma/schema.prisma`:
```prisma
datasource db {
provider = "mysql"
relationMode = "prisma" // Emulate foreign keys in Prisma
}
```
## Common Issues
### "Too many connections"
MySQL has a connection limit. Adjust connection pool size in URL:
```env
DATABASE_URL="mysql://...?connection_limit=5"
```
### JSON Support
MySQL 5.7+ supports JSON. MariaDB 10.2+ supports JSON (as an alias for LONGTEXT with check constraints). Prisma handles this, but verify your version.
@@ -0,0 +1,92 @@
# PostgreSQL Setup
Configure Prisma with PostgreSQL.
## Prerequisites
- PostgreSQL database (local or cloud)
- Connection string
## 1. Schema Configuration
In `prisma/schema.prisma`:
```prisma
datasource db {
provider = "postgresql"
}
generator client {
provider = "prisma-client"
output = "../generated"
}
```
## 2. Config Configuration
In `prisma.config.ts`:
```typescript
import { defineConfig, env } from 'prisma/config'
export default defineConfig({
schema: 'prisma/schema.prisma',
datasource: {
url: env('DATABASE_URL'),
},
})
```
## 3. Environment Variable
In `.env`:
```env
DATABASE_URL="postgresql://user:password@localhost:5432/mydb?schema=public"
```
### Connection String Format
```
postgresql://USER:PASSWORD@HOST:PORT/DATABASE?schema=SCHEMA
```
- **USER**: Database user
- **PASSWORD**: Password (URL encoded if special chars)
- **HOST**: Hostname (localhost, IP, or domain)
- **PORT**: Port (default 5432)
- **DATABASE**: Database name
- **SCHEMA**: Schema name (default `public`)
## Driver Adapter
Use a driver adapter for the standard SQL workflow.
1. Install adapter and driver:
```bash
npm install @prisma/adapter-pg pg
```
2. Instantiate Prisma Client with the adapter:
```typescript
import 'dotenv/config'
import { PrismaClient } from '../generated/client'
import { PrismaPg } from '@prisma/adapter-pg'
const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL })
const prisma = new PrismaClient({ adapter })
```
## Common Issues
### "Can't reach database server"
- Check host and port
- Check firewall settings
- Ensure database is running
### "Authentication failed"
- Check user/password
- Special characters in password must be URL-encoded
### "Schema does not exist"
- Ensure `?schema=public` (or your schema) is in the URL
@@ -0,0 +1,47 @@
# Prisma Client Setup
Generate and instantiate Prisma Client for Prisma's standard SQL provider workflow. For MongoDB, follow the provider-specific notes in `references/mongodb.md` instead of copying the SQL adapter example below.
## 1. Install dependencies
```bash
npm install prisma --save-dev
npm install @prisma/client
```
## 2. Add generator block
In `prisma/schema.prisma`:
```prisma
generator client {
provider = "prisma-client"
output = "../generated"
}
```
`prisma-client` requires an explicit `output` path and does not generate into `node_modules` by default.
## 3. Generate Prisma Client
```bash
npx prisma generate
```
Re-run `prisma generate` after every schema change to keep the client in sync.
## 4. Instantiate Prisma Client
```typescript
import { PrismaClient } from '../generated/client'
import { PrismaPg } from '@prisma/adapter-pg'
const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL })
const prisma = new PrismaClient({ adapter })
```
If you change the generator `output`, update the import path to match. For the SQL provider workflow, replace `PrismaPg` with the adapter for your database.
## 5. Use a single instance
Each `PrismaClient` instance creates a connection pool. Reuse a single instance per app process to avoid exhausting database connections.
@@ -0,0 +1,130 @@
# Prisma Postgres Setup
Configure Prisma with Prisma Postgres (Managed).
## Overview
Prisma Postgres is a serverless, managed PostgreSQL database optimized for Prisma.
## Setup via CLI
You can provision a Prisma Postgres instance directly via the CLI:
```bash
prisma init --db
```
This will:
1. Log you into Prisma Data Platform.
2. Create a new project and database instance.
3. Update your `.env` with the connection string.
## Connection String
For Prisma CLI flows and Accelerate-style usage, you may see a `prisma+postgres://` URL.
For Prisma Client with a driver adapter in Node.js, prefer the direct TCP connection string from the Prisma Postgres dashboard:
```env
DATABASE_URL="postgres://identifier:key@db.prisma.io:5432/postgres?sslmode=require"
```
## 1. Schema Configuration
In `prisma/schema.prisma`:
```prisma
datasource db {
provider = "postgresql" // Use postgresql provider
}
generator client {
provider = "prisma-client"
output = "../generated"
}
```
## 2. Config Configuration
In `prisma.config.ts`:
```typescript
import { defineConfig, env } from 'prisma/config'
export default defineConfig({
schema: 'prisma/schema.prisma',
datasource: {
url: env('DATABASE_URL'),
},
})
```
## Driver Adapter
Use a driver adapter for Prisma Postgres in the standard SQL workflow.
### Recommended for standard Node.js apps
1. Install adapter and driver:
```bash
npm install @prisma/adapter-pg pg
```
2. Use the direct TCP connection string from Prisma Console:
```typescript
import 'dotenv/config'
import { PrismaClient } from '../generated/client'
import { PrismaPg } from '@prisma/adapter-pg'
const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL })
const prisma = new PrismaClient({ adapter })
```
`PrismaPg` also accepts the connection string directly:
```typescript
const adapter = new PrismaPg(process.env.DATABASE_URL!)
const prisma = new PrismaClient({ adapter })
```
For PostgreSQL prepared statement naming, pass adapter options as the second argument:
```typescript
import { createHash } from 'node:crypto'
const adapter = new PrismaPg(process.env.DATABASE_URL!, {
statementNameGenerator: ({ sql }) =>
`prisma_${createHash('sha1').update(sql).digest('hex').slice(0, 16)}`,
})
```
### Edge/serverless option
Use the Prisma Postgres serverless driver only when you need HTTP/WebSocket transport in environments like Workers or Edge Functions:
```bash
npm install @prisma/adapter-ppg @prisma/ppg
```
```typescript
import { PrismaClient } from '../generated/client'
import { PrismaPostgresAdapter } from '@prisma/adapter-ppg'
const prisma = new PrismaClient({
adapter: new PrismaPostgresAdapter({
connectionString: process.env.PRISMA_DIRECT_TCP_URL,
}),
})
```
This serverless driver is the specialized path for HTTP/WebSocket-based edge and serverless runtimes, not the default recommendation for standard Node.js apps.
## Features
- **Serverless**: Scales to zero.
- **Caching**: Integrated query caching (Accelerate).
- **Real-time**: Database events (Pulse).
## Using with Prisma Client
Use the Prisma Postgres adapter shown above when instantiating Prisma Client.
@@ -0,0 +1,106 @@
# SQLite Setup
Configure Prisma with SQLite.
## Prerequisites
- None (file-based)
## 1. Schema Configuration
In `prisma/schema.prisma`:
```prisma
datasource db {
provider = "sqlite"
}
generator client {
provider = "prisma-client"
output = "../generated"
}
```
## 2. Config Configuration
In `prisma.config.ts`:
```typescript
import { defineConfig, env } from 'prisma/config'
export default defineConfig({
schema: 'prisma/schema.prisma',
datasource: {
url: env('DATABASE_URL'),
},
})
```
## 3. Environment Variable
In `.env`:
```env
DATABASE_URL="file:./dev.db"
```
### Connection String Format
```
file:PATH
```
- **PATH**: Relative path to the database file. Check `prisma.config.ts` if you need to confirm how your app resolves it.
## Driver Adapter
Use a driver adapter for the standard SQL workflow.
1. Install adapter and driver:
```bash
npm install @prisma/adapter-better-sqlite3 better-sqlite3
```
2. Instantiate Prisma Client with the adapter:
```typescript
import { PrismaClient } from '../generated/client'
import { PrismaBetterSqlite3 } from '@prisma/adapter-better-sqlite3'
const adapter = new PrismaBetterSqlite3({
url: process.env.DATABASE_URL ?? 'file:./dev.db',
})
const prisma = new PrismaClient({ adapter })
```
## Using Driver Adapter (LibSQL / Turso)
For edge compatibility or Turso:
1. Install:
```bash
npm install @prisma/adapter-libsql @libsql/client
```
2. Instantiate:
```typescript
import { PrismaClient } from '../generated/client'
import { PrismaLibSql } from '@prisma/adapter-libsql'
const adapter = new PrismaLibSql({
url: process.env.TURSO_DATABASE_URL,
authToken: process.env.TURSO_AUTH_TOKEN,
})
const prisma = new PrismaClient({ adapter })
```
## Limitations
- **No Enums**: SQLite doesn't support enums (Prisma polyfills them or treats as String).
- **No Scalar Lists**: `String[]` is not supported directly.
- **Concurrency**: Write operations lock the file.
## Common Issues
### "Database file not found"
Ensure the path in `DATABASE_URL` is correct relative to where Prisma is running or the schema file. `file:./dev.db` creates it next to schema.
@@ -0,0 +1,94 @@
# SQL Server Setup
Configure Prisma with Microsoft SQL Server.
## Prerequisites
- SQL Server 2017, 2019, 2022, or Azure SQL
- TCP/IP enabled
## 1. Schema Configuration
In `prisma/schema.prisma`:
```prisma
datasource db {
provider = "sqlserver"
}
generator client {
provider = "prisma-client"
output = "../generated"
}
```
## 2. Config Configuration
In `prisma.config.ts`:
```typescript
import { defineConfig, env } from 'prisma/config'
export default defineConfig({
schema: 'prisma/schema.prisma',
datasource: {
url: env('DATABASE_URL'),
},
})
```
## 3. Environment Variable
In `.env`:
```env
DATABASE_URL="sqlserver://localhost:1433;database=mydb;user=sa;password=Password123;encrypt=true;trustServerCertificate=true"
```
### Connection String Format
```
sqlserver://HOST:PORT;database=DB;user=USER;password=PASS;encrypt=true;trustServerCertificate=true
```
- **encrypt**: Required for Azure (true).
- **trustServerCertificate**: True for self-signed certs (local dev).
## Driver Adapter
Use a driver adapter for the standard SQL workflow.
1. Install adapter and driver:
```bash
npm install @prisma/adapter-mssql mssql
```
2. Instantiate Prisma Client with the adapter:
```typescript
import 'dotenv/config'
import { PrismaClient } from '../generated/client'
import { PrismaMssql } from '@prisma/adapter-mssql'
const adapter = new PrismaMssql({
server: 'localhost',
port: 1433,
database: 'mydb',
user: process.env.SQLSERVER_USER,
password: process.env.SQLSERVER_PASSWORD,
options: {
encrypt: true,
trustServerCertificate: true,
},
})
const prisma = new PrismaClient({ adapter })
```
## Common Issues
### "Login failed for user"
- SQL Server auth vs Windows auth. Prisma typically uses SQL Server authentication (username/password).
- Ensure TCP/IP is enabled in SQL Server Configuration Manager.
### "Table not found" (dbo schema)
Prisma assumes `dbo` schema by default. If using another schema, update the model or connection string? SQL Server provider mostly sticks to default schema.
@@ -0,0 +1,638 @@
---
name: prisma-driver-adapter-implementation
description: Required reference for Prisma v7 driver adapter work. Use when implementing or modifying adapters, adding database drivers, or touching SqlDriverAdapter/Transaction interfaces. Contains critical contract details not inferable from code examples — including the transaction lifecycle protocol, error mapping requirements, and verification checklist. Existing implementations do not replace this skill.
license: MIT
metadata:
author: Tyler Benfield
version: "7.6.0"
---
# Prisma 7 Driver Adapter Implementation Guide
This skill provides everything needed to implement a Prisma ORM v7 driver adapter for any database.
## Architecture Overview
```
┌─────────────────────────────────────────────────────────────────┐
│ PrismaClient │
│ (requires adapter factory) │
└─────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ SqlMigrationAwareDriverAdapterFactory │
│ ┌─────────────────────┐ ┌─────────────────────────────┐ │
│ │ connect() │ │ connectToShadowDb() │ │
│ │ → SqlDriverAdapter │ │ → SqlDriverAdapter │ │
│ └─────────────────────┘ └─────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ SqlDriverAdapter │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────────────────┐ │
│ │ queryRaw() │ │ executeRaw() │ │ startTransaction() │ │
│ │ → ResultSet │ │ → number │ │ → Transaction │ │
│ └──────────────┘ └──────────────┘ └──────────────────────────┘ │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────────────────┐ │
│ │executeScript │ │ dispose() │ │ getConnectionInfo() │ │
│ └──────────────┘ └──────────────┘ └──────────────────────────┘ │
└─────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ Transaction │
│ Extends SqlQueryable + commit() + rollback() + options │
│ (lifecycle hooks only — Prisma sends SQL via executeRaw) │
└─────────────────────────────────────────────────────────────────┘
```
## Required Interfaces
Import from `@prisma/driver-adapter-utils`:
```typescript
import type {
ColumnType,
IsolationLevel,
SqlDriverAdapter,
SqlMigrationAwareDriverAdapterFactory,
SqlQuery,
SqlQueryable,
SqlResultSet,
Transaction,
TransactionOptions,
ArgType,
ConnectionInfo,
MappedError,
} from "@prisma/driver-adapter-utils";
import {
ColumnTypeEnum,
DriverAdapterError,
} from "@prisma/driver-adapter-utils";
```
## Interface Definitions
### SqlQuery (input to queryRaw/executeRaw)
```typescript
type SqlQuery = {
sql: string; // Parameterized SQL with placeholders
args: Array<unknown>; // Bound parameter values
argTypes: Array<ArgType>; // Type hints for each argument
};
type ArgType = {
scalarType: ArgScalarType; // 'string' | 'int' | 'bigint' | 'float' | 'decimal' | 'boolean' | 'enum' | 'uuid' | 'json' | 'datetime' | 'bytes' | 'unknown'
dbType?: string;
arity: "scalar" | "list";
};
```
### SqlResultSet (output from queryRaw)
```typescript
interface SqlResultSet {
columnNames: Array<string>; // Column names in order
columnTypes: Array<ColumnType>; // Column types matching columnNames
rows: Array<Array<unknown>>; // Row data as arrays
lastInsertId?: string; // For INSERT without RETURNING
}
```
### ColumnTypeEnum values
```typescript
const ColumnTypeEnum = {
Int32: 0,
Int64: 1,
Float: 2,
Double: 3,
Numeric: 4,
Boolean: 5,
Character: 6,
Text: 7,
Date: 8,
Time: 9,
DateTime: 10,
Json: 11,
Enum: 12,
Bytes: 13,
Set: 14,
Uuid: 15,
Int32Array: 64,
Int64Array: 65,
FloatArray: 66,
DoubleArray: 67,
NumericArray: 68,
BooleanArray: 69,
CharacterArray: 70,
TextArray: 71,
DateArray: 72,
TimeArray: 73,
DateTimeArray: 74,
JsonArray: 75,
EnumArray: 76,
BytesArray: 77,
UuidArray: 78,
UnknownNumber: 128,
} as const;
```
### SqlDriverAdapter
```typescript
interface SqlDriverAdapter extends SqlQueryable {
executeScript(script: string): Promise<void>;
startTransaction(isolationLevel?: IsolationLevel): Promise<Transaction>;
getConnectionInfo?(): ConnectionInfo;
dispose(): Promise<void>;
}
```
### Transaction
```typescript
interface Transaction extends SqlQueryable {
readonly options: TransactionOptions;
commit(): Promise<void>;
rollback(): Promise<void>;
}
type TransactionOptions = { usePhantomQuery: boolean };
```
### SqlMigrationAwareDriverAdapterFactory
```typescript
interface SqlMigrationAwareDriverAdapterFactory {
readonly provider: "mysql" | "postgres" | "sqlite" | "sqlserver";
readonly adapterName: string;
connect(): Promise<SqlDriverAdapter>;
connectToShadowDb(): Promise<SqlDriverAdapter>;
}
```
## Implementation Steps
### Step 1: Create the Queryable base class
```typescript
class MyQueryable<TClient> implements SqlQueryable {
readonly provider = "postgres" as const; // or 'sqlite' | 'mysql' | 'sqlserver'
readonly adapterName = "@my-org/adapter-mydb" as const;
constructor(protected readonly client: TClient) {}
async queryRaw(query: SqlQuery): Promise<SqlResultSet> {
try {
const args = query.args.map((arg, i) =>
mapArg(arg, query.argTypes[i] ?? { scalarType: "unknown", arity: "scalar" })
);
// Execute query with your driver
const result = await this.client.query(query.sql, args);
// Extract column metadata
const columnNames = /* get from result */;
const columnTypes = /* map to ColumnTypeEnum */;
// Map rows to ResultValue arrays
const rows = result.map(row => mapRow(row, columnTypes));
return { columnNames, columnTypes, rows };
} catch (e) {
this.onError(e);
}
}
async executeRaw(query: SqlQuery): Promise<number> {
try {
const args = query.args.map((arg, i) =>
mapArg(arg, query.argTypes[i] ?? { scalarType: "unknown", arity: "scalar" })
);
const result = await this.client.query(query.sql, args);
return result.affectedRows ?? 0;
} catch (e) {
this.onError(e);
}
}
protected onError(error: unknown): never {
throw new DriverAdapterError(convertDriverError(error));
}
}
```
### Step 2: Create the Transaction class
**Critical**: `commit()` and `rollback()` are **lifecycle hooks only**. They must NOT issue SQL. Prisma sends `COMMIT`/`ROLLBACK` via `executeRaw` on the transaction object.
```typescript
class MyTransaction extends MyQueryable<TClient> implements Transaction {
readonly options: TransactionOptions;
readonly #release: () => void;
constructor(
client: TClient,
options: TransactionOptions,
release: () => void,
) {
super(client);
this.options = options;
this.#release = release;
}
commit(): Promise<void> {
// DO NOT issue COMMIT SQL here — Prisma does it via executeRaw
this.#release(); // Release connection/resources
return Promise.resolve();
}
rollback(): Promise<void> {
// DO NOT issue ROLLBACK SQL here — Prisma does it via executeRaw
this.#release();
return Promise.resolve();
}
}
```
### Step 3: Create the Adapter class
```typescript
class MyAdapter extends MyQueryable<TClient> implements SqlDriverAdapter {
#transactionDepth = 0;
constructor(client: TClient) {
super(client);
}
async executeScript(script: string): Promise<void> {
// For SQLite: split on ';' and run each statement
// For Postgres: use multi-statement execution
try {
// Implementation depends on driver capabilities
} catch (e) {
this.onError(e);
}
}
async startTransaction(
isolationLevel?: IsolationLevel,
): Promise<Transaction> {
// Validate isolation level for your database
const validLevels = new Set<IsolationLevel>([
"READ UNCOMMITTED",
"READ COMMITTED",
"REPEATABLE READ",
"SERIALIZABLE",
]);
if (isolationLevel !== undefined && !validLevels.has(isolationLevel)) {
throw new DriverAdapterError({
kind: "InvalidIsolationLevel",
level: isolationLevel,
});
}
const options: TransactionOptions = { usePhantomQuery: false };
this.#transactionDepth += 1;
const depth = this.#transactionDepth;
try {
if (depth === 1) {
// Issue BEGIN (with isolation level if specified)
const beginSql = isolationLevel
? `BEGIN ISOLATION LEVEL ${isolationLevel}`
: "BEGIN";
await this.client.query(beginSql);
} else {
// Nested: use savepoints
await this.client.query(`SAVEPOINT sp_${depth}`);
}
} catch (e) {
this.#transactionDepth -= 1;
this.onError(e);
}
const release = () => {
this.#transactionDepth -= 1;
};
return new MyTransaction(this.client, options, release);
}
getConnectionInfo(): ConnectionInfo {
return { supportsRelationJoins: true };
}
async dispose(): Promise<void> {
await this.client.close();
}
}
```
### Step 4: Create the Factory class
```typescript
export type MyAdapterConfig = {
url: string;
};
export type MyAdapterOptions = {
shadowDatabaseUrl?: string;
};
export class MyAdapterFactory implements SqlMigrationAwareDriverAdapterFactory {
readonly provider = "postgres" as const;
readonly adapterName = "@my-org/adapter-mydb" as const;
constructor(
private readonly config: MyAdapterConfig,
private readonly options?: MyAdapterOptions,
) {}
connect(): Promise<SqlDriverAdapter> {
return Promise.resolve(new MyAdapter(openConnection(this.config.url)));
}
connectToShadowDb(): Promise<SqlDriverAdapter> {
const url = this.options?.shadowDatabaseUrl ?? this.config.url;
return Promise.resolve(new MyAdapter(openConnection(url)));
}
}
```
## Conversion Helpers
### Argument Mapping (input)
Convert Prisma argument values to driver-native types:
```typescript
function mapArg(arg: unknown, argType: ArgType): unknown {
if (arg === null || arg === undefined) return null;
// String → number for int columns
if (typeof arg === "string" && argType.scalarType === "int")
return Number.parseInt(arg, 10);
// String → number for float columns
if (typeof arg === "string" && argType.scalarType === "float")
return Number.parseFloat(arg);
// String → BigInt for bigint columns
if (typeof arg === "string" && argType.scalarType === "bigint")
return BigInt(arg);
// Base64 string → Buffer for bytes columns
if (typeof arg === "string" && argType.scalarType === "bytes")
return Buffer.from(arg, "base64");
// Boolean → 0/1 for SQLite
if (typeof arg === "boolean" && /* SQLite */)
return arg ? 1 : 0;
return arg;
}
```
### Row Mapping (output)
Convert driver result values to Prisma-expected types:
```typescript
function mapRow(row: unknown[], columnTypes: ColumnType[]): ResultValue[] {
const result: ResultValue[] = [];
for (let i = 0; i < row.length; i++) {
const value = row[i] ?? null;
const colType = columnTypes[i];
if (value === null) {
result.push(null);
continue;
}
// bigint → string for Int64 (JSON-safe)
if (typeof value === "bigint") {
result.push(value.toString());
continue;
}
// Date → ISO 8601 string for DateTime
if (value instanceof Date) {
result.push(value.toISOString());
continue;
}
// JSON objects → stringified
if (colType === ColumnTypeEnum.Json && typeof value === "object") {
result.push(JSON.stringify(value));
continue;
}
result.push(value as ResultValue);
}
return result;
}
```
### Column Type Inference
When the driver doesn't provide type metadata, infer from JS values:
```typescript
function inferColumnType(value: NonNullable<unknown>): ColumnType {
if (typeof value === "boolean") return ColumnTypeEnum.Boolean;
if (typeof value === "bigint") return ColumnTypeEnum.Int64;
if (value instanceof Uint8Array) return ColumnTypeEnum.Bytes;
if (value instanceof Date) return ColumnTypeEnum.DateTime;
if (Array.isArray(value)) return ColumnTypeEnum.Text; // fallback
if (typeof value === "object") return ColumnTypeEnum.Json;
if (typeof value === "number") return ColumnTypeEnum.UnknownNumber;
return ColumnTypeEnum.Text;
}
```
## Error Handling
Map driver errors to `MappedError` for Prisma to handle correctly:
```typescript
function convertDriverError(error: unknown): MappedError {
if (error instanceof Error) {
// Database-specific error mapping
const dbError = error as Error & { code?: string; errno?: number };
// PostgreSQL example
if (dbError.code === "23505") {
return { kind: "UniqueConstraintViolation" };
}
if (dbError.code === "23502") {
return { kind: "NullConstraintViolation" };
}
if (dbError.code === "23503") {
return { kind: "ForeignKeyConstraintViolation" };
}
if (dbError.code === "42P01") {
return { kind: "TableDoesNotExist" };
}
// SQLite example
if (error.name === "SQLiteError") {
return {
kind: "sqlite",
extendedCode: dbError.errno ?? 1,
message: error.message,
};
}
// PostgreSQL raw error
if (dbError.code) {
return {
kind: "postgres",
code: dbError.code,
severity: "ERROR",
message: error.message,
detail: undefined,
column: undefined,
hint: undefined,
};
}
}
return { kind: "GenericJs", id: 0 };
}
```
## Database-Specific Notes
### SQLite
- Set `safeIntegers: true` when opening the database to get `bigint` for large integers
- Only `SERIALIZABLE` isolation level is valid
- `executeScript`: split on `;` and run each statement individually
- Boolean values: store as 0/1, return as boolean
### PostgreSQL
- All standard isolation levels are valid
- For connection pooling (PgBouncer), use `prepare: false`
- Transactions require a dedicated connection (`reserve()` pattern)
- `executeScript`: use multi-statement execution (`.simple()` in some drivers)
- `int8` columns may return as string (already stringified by driver)
- `numeric` columns return as string to preserve precision
### MySQL/MariaDB
- Supports `READ UNCOMMITTED`, `READ COMMITTED`, `REPEATABLE READ`, `SERIALIZABLE`
- Use `?` placeholders for parameters
- Handle `BIGINT` as string for large values
## Testing Strategy
### Unit Tests (no PrismaClient)
Test the adapter directly with the raw database driver:
```typescript
describe("queryRaw", () => {
test("returns column names and types", async () => {
const adapter = new MyAdapter(createTestConnection());
const result = await adapter.queryRaw({
sql: "SELECT id, name FROM users",
args: [],
argTypes: [],
});
expect(result.columnNames).toEqual(["id", "name"]);
expect(result.columnTypes[0]).toBe(ColumnTypeEnum.Int32);
});
});
describe("startTransaction", () => {
test("commit persists changes", async () => {
const adapter = new MyAdapter(createTestConnection());
const tx = await adapter.startTransaction();
await tx.executeRaw({
sql: "INSERT INTO users (name) VALUES (?)",
args: ["Alice"],
argTypes: [],
});
// Prisma sends COMMIT via executeRaw
await tx.executeRaw({ sql: "COMMIT", args: [], argTypes: [] });
await tx.commit(); // lifecycle hook only
// Verify data persisted
});
});
```
### E2E Tests (with PrismaClient)
Test the full integration:
```typescript
describe("E2E", () => {
let prisma: PrismaClient;
beforeEach(async () => {
const factory = new MyAdapterFactory({ url: TEST_DB_URL });
prisma = new PrismaClient({ adapter: factory });
});
test("CRUD operations", async () => {
const user = await prisma.user.create({ data: { name: "Alice" } });
expect(user.id).toBeGreaterThan(0);
const found = await prisma.user.findUnique({ where: { id: user.id } });
expect(found?.name).toBe("Alice");
});
test("transactions roll back on error", async () => {
await expect(
prisma.$transaction(async (tx) => {
await tx.user.create({ data: { name: "Bob" } });
throw new Error("Rollback!");
}),
).rejects.toThrow();
expect(await prisma.user.count()).toBe(0);
});
});
```
## Usage Example
```typescript
import { PrismaClient } from "./generated/prisma/client";
import { MyAdapterFactory } from "@my-org/adapter-mydb";
const factory = new MyAdapterFactory({
url: process.env.DATABASE_URL!,
});
const prisma = new PrismaClient({ adapter: factory });
// Use prisma normally
const users = await prisma.user.findMany();
```
## Checklist
Before considering the adapter complete:
- [ ] `SqlMigrationAwareDriverAdapterFactory` implemented with `connect()` and `connectToShadowDb()`
- [ ] `SqlDriverAdapter` implements `queryRaw`, `executeRaw`, `executeScript`, `startTransaction`, `dispose`
- [ ] `Transaction` implements `queryRaw`, `executeRaw`, `commit`, `rollback` with `options: { usePhantomQuery: false }`
- [ ] `commit()` and `rollback()` are lifecycle hooks only (no SQL issued)
- [ ] `startTransaction` issues `BEGIN` (depth 1) or `SAVEPOINT sp_N` (nested)
- [ ] Argument mapping handles: string→int, string→bigint, string→float, base64→bytes
- [ ] Row mapping handles: bigint→string, Date→ISO string, JSON→string
- [ ] Column types correctly mapped to `ColumnTypeEnum`
- [ ] Errors wrapped in `DriverAdapterError` with proper `MappedError` kind
- [ ] Isolation level validation for the target database
- [ ] Unit tests pass for queryRaw, executeRaw, executeScript, transactions
- [ ] E2E tests pass with real PrismaClient
@@ -0,0 +1,92 @@
---
name: prisma-mongodb-upgrade
description: Decision and migration guide for Prisma ORM MongoDB projects on v6, which have no upgrade path to v7. Use when a MongoDB project asks about upgrading Prisma, when "upgrade to prisma 7" comes up in a project with provider = "mongodb", or when evaluating a move to Prisma Next. Triggers on "upgrade prisma mongodb", "prisma 7 mongodb", "mongodb prisma migration", "prisma next mongodb".
license: MIT
metadata:
author: prisma
version: "0.1.0"
---
# Prisma MongoDB Upgrade Path
MongoDB projects are the one Prisma cohort with no road into Prisma 7: **v6 is the terminal
classic-ORM major for MongoDB, and v7 never ships a MongoDB connector**. The successor path
is [Prisma Next](https://github.com/prisma/prisma-next), where MongoDB support is in Early
Access with GA planned after Postgres. This skill frames the real decision — migrate to
Prisma Next (the encouraged path), or stay on v6 where a hard blocker applies — and carries
the migration mechanics.
**Never do either of these:**
- Never advise a MongoDB project to "upgrade to Prisma 7". The connector does not exist
there. The `prisma-upgrade-v7` guide does not apply to MongoDB projects.
- Never solve the version question by rewriting the app onto a SQL database. Changing the
database engine is a separate, much larger decision that is not yours to make implicitly.
## The version landscape
| Version | MongoDB status |
|---------|----------------|
| Prisma ORM v6 | Fully supported (`mongodb` provider); latest 6.x is the current stable path; maintenance line |
| Prisma ORM v7 | **No MongoDB connector — not an option, ever** |
| Prisma Next | MongoDB support in **Early Access**, actively developed, GA planned after Postgres — the successor path for MongoDB projects |
## The decision, up front
**Migrating to Prisma Next is the encouraged path.** MongoDB support in Prisma Next is Early
Access: functional and moving quickly, with GA planned after Postgres — and the Prisma team
wants MongoDB users to migrate early and share feedback. The migration mechanics are
detailed in the references.
**Staying on the latest v6 remains a legitimate choice where a hard blocker applies** —
stated plainly: the Next Mongo façade does not wrap transactions yet (the underlying driver
is available directly; this is expected to change soon), and pre-1.0 minors can carry
breaking changes with published upgrade recipes.
### Decision table
| Signal | Direction |
|--------|-----------|
| No blockers below apply | Migrate to Next; run the `verify-cutover-checklist` and share feedback with the Prisma team |
| Greenfield / prototype / internal tool | Migrate to Next |
| Codebase uses multi-document transactions (`$transaction`) — check with grep, do not ask | Plan raw-driver session equivalents first (see `client-api-mapping`), or stay on v6 until the façade wrapper lands |
| Team cannot absorb pre-1.0 breaking upgrades between minors | Stay on v6 until GA |
| Risk-averse but interested | Run a staged Next round-trip on a copy (see `verify-cutover-checklist`), then migrate |
Note: the transactions gap is expected to close soon — this section will be updated when
façade transactions merge in Prisma Next.
### If staying on v6: hygiene (a deliberate stay, not neglect)
- Pin the Prisma packages to the latest 6.x line and keep taking 6.x patch releases.
- Track Prisma release notes and security advisories for the 6.x line.
- Keep the classic v6 MongoDB setup: `url = env("DATABASE_URL")` in the schema, `db push`
workflow, no SQL driver adapters (see `prisma-database-setup` for the v6 MongoDB shape).
- Re-evaluate when Prisma Next's MongoDB is GA, or when blockers for trying EA are resolved.
## Reference files
| Reference | What it covers |
|-----------|----------------|
| `references/decision-stay-or-migrate.md` | The full decision framing, blocker checks, and stay-hygiene detail |
| `references/schema-contract-mapping.md` | v6 schema (`mongodb` provider, `@db.ObjectId`, composite types) → Next contract concepts |
| `references/client-api-mapping.md` | v6 client calls → Next equivalents, incl. raw escape hatches and transactions — names map, parity does not |
| `references/migrations-mapping.md` | v6 `db push`-only story → Next's plan/migrate/verify/sign flow |
| `references/verify-cutover-checklist.md` | No-data-moves verification: same DB, index parity, staged round-trip before cutover |
## Verified against
Behavioral claims about Prisma Next in this skill were verified against
[prisma/prisma-next](https://github.com/prisma/prisma-next) at commit
`a2791c5dd59d579b4b3052942ae7f8fe5e2ee852` (pre-1.0, ~v0.14/0.15 line). Prisma Next moves
quickly in Early Access: **before acting on any Next-side claim, verify it against the
version actually installed** (check the project's `@prisma-next/*` versions and the
prisma-next skills installed with it). Next's Mongo target requires MongoDB 8.0+ and expects
`mongodb@^7` as a user-supplied peer dependency.
## Hand-off rule
This skill is the **discovery bridge**, not a replacement for Prisma Next's own
documentation. After a project switches to Prisma Next, run Prisma Next's `init`/skill
installation and follow its own skills (quickstart, contract, queries, migrations, runtime)
for day-to-day work — do not keep working from this skill's summaries.
@@ -0,0 +1,61 @@
# client-api-mapping
How v6 Prisma Client calls map to Prisma Next's Mongo client — names map, parity does not.
## Priority
CRITICAL
## Why It Matters
The v6 and Next client APIs look superficially similar, but none of the v6 MongoDB raw
methods exist under their old names, aggregation moved to a different lane entirely, and
transactions go through the driver rather than a façade wrapper. Assuming parity produces
code that does not compile — or, in the transactions case, code that silently loses
atomicity.
## The mapping
| v6 call | Prisma Next equivalent | Notes |
|---------|------------------------|-------|
| `prisma.user.findMany(...)` | `db.orm.users.where(...).all()` | Fluent ORM lane; storage-name keys (see `schema-contract-mapping.md`) |
| `prisma.user.findFirst(...)` | `db.orm.users.where(...).first()` | |
| `create` / `update` / `upsert` / `delete` / `updateMany` / `deleteMany` | `create` / `update` / `upsert` / `delete` / `updateAll` / `deleteAll` on `db.orm.<collection>` | See Prisma Next's `prisma-next-queries` skill |
| `prisma.user.aggregate(...)`, `groupBy(...)` | **No ORM equivalent.** Use the typed aggregation-pipeline builder: `db.query.from(...).match(...).group(...).build()` | Prisma Next's `prisma-next-queries` skill covers the builder lane |
| `$runCommandRaw(...)` ([v6 docs](https://www.prisma.io/docs/orm/prisma-client/using-raw-sql/raw-queries#runcommandraw)) | **Name does not exist in Next.** Raw lane is `mongoRaw(...)` → a raw collection with `aggregate`, `insertOne/Many`, `updateOne/Many`, `deleteOne/Many`, `findOneAndUpdate/Delete`. For arbitrary database commands, use the underlying `mongodb` driver directly — it is a user-supplied peer dependency and fully accessible | Check the installed version's raw surface |
| `<model>.findRaw(...)` ([v6 docs](https://www.prisma.io/docs/orm/prisma-client/using-raw-sql/raw-queries#findraw)) | `mongoRaw(...)` collection reads (e.g. `aggregate` with a `$match` stage) | No direct `findRaw` name |
| `<model>.aggregateRaw(...)` ([v6 docs](https://www.prisma.io/docs/orm/prisma-client/using-raw-sql/raw-queries#aggregateraw)) | `mongoRaw(...).aggregate(...)` or the typed pipeline builder | |
| `$transaction(...)` — works on v6 with a replica set ([v6 docs](https://www.prisma.io/docs/orm/overview/databases/mongodb#replica-set-configuration)) | The façade does not wrap `db.transaction(...)` yet, **but the underlying `mongodb` driver is directly available** (user-supplied peer dependency): multi-document atomicity works today via driver sessions (`client.startSession()` / `session.withTransaction(...)`) on a replica set | A façade wrapper is expected soon; this row will be updated when it merges |
| `$connect` / `$disconnect` | `connect()` / `close()` on the Mongo façade client | |
## Bad
```typescript
// Assuming v6 names exist in Prisma Next:
await db.user.$runCommandRaw({ collStats: 'users' }); // no such method
await db.transaction(async (tx) => { ... }); // no such method on the Mongo façade
```
## Good
```typescript
// Raw lane under its Next name:
const raw = mongoRaw(db);
await raw.users.aggregate([{ $match: { status: 'active' } }]);
// Aggregation through the typed pipeline builder:
const stats = await db.query.from('users').group({ _id: '$role', n: { $count: {} } }).build();
// Multi-document atomicity today: the mongodb driver (a direct dependency of the
// project) exposes sessions and transactions as usual:
const session = mongoClient.startSession();
await session.withTransaction(async () => {
// ...writes...
});
```
## References
- [v6 MongoDB raw queries](https://www.prisma.io/docs/orm/prisma-client/using-raw-sql/raw-queries#raw-queries-with-mongodb)
- [v6 replica set requirement for transactions](https://www.prisma.io/docs/orm/overview/databases/mongodb#replica-set-configuration)
- Prisma Next queries + runtime skills (`skills/prisma-next-queries`, incl. its dedicated `mongo.md`; `skills/prisma-next-runtime`) — authoritative for the Next side; verified @ `a2791c5dd59d579b4b3052942ae7f8fe5e2ee852`
@@ -0,0 +1,87 @@
# decision-stay-or-migrate
How to decide between migrating a MongoDB project to Prisma Next and staying on Prisma v6.
## Priority
CRITICAL
## Why It Matters
MongoDB projects cannot follow the general "upgrade Prisma" advice: Prisma 7 has no MongoDB
connector, so the forward path is Prisma Next. Advising an impossible v7 upgrade, or
silently rewriting the app onto SQL, are both serious failure modes. The encouraged path is
migrating to Prisma Next — its MongoDB support is Early Access and the Prisma team wants
early adopters' feedback — with a deliberate stay on v6 where a hard blocker applies.
## The facts the decision rests on
Prisma Next side (verified against prisma/prisma-next @ `a2791c5dd59d579b4b3052942ae7f8fe5e2ee852`;
status confirmed by the Prisma team 2026-07):
- **MongoDB support is Early Access**, actively developed, with GA planned after Postgres.
- The implementation is deep, not a stub: a full package family (ORM, typed
aggregation-pipeline builder, raw lane, driver over the official `mongodb` package),
first-class contract-driven migrations, and extensive tests against real in-memory MongoDB.
- **The Mongo client façade does not wrap `db.transaction(...)` yet** — multi-document
atomicity is done through the MongoDB driver's session API, which is directly available
(the `mongodb` package is a user-supplied peer dependency). A façade wrapper is expected;
this skill will be updated when it merges.
- Early Access means pre-1.0 minors can carry breaking changes, with published upgrade
recipes (e.g. 0.11→0.12 changed Mongo validator emission and made `mongodb` a
user-supplied peer dependency). Floor: MongoDB 8.0 and `mongodb@^7`.
Prisma v6 side:
- v6 fully supports MongoDB, including transactions on replica sets — "MongoDB only allows
you to start a transaction on a replica set. Prisma ORM uses transactions internally"
([replica set configuration](https://www.prisma.io/docs/orm/overview/databases/mongodb#replica-set-configuration)).
- v6 MongoDB has no Prisma Migrate; the workflow is `db push`
([no support for Prisma Migrate](https://www.prisma.io/docs/orm/overview/databases/mongodb#no-support-for-prisma-migrate)).
## Blocker checks before migrating
Run these checks yourself — from the codebase, not by asking the user:
- **Search the codebase for `$transaction` usage** (grep for `$transaction`). If present,
plan the raw-driver session equivalents before migrating (see `client-api-mapping.md`) —
or stay on v6 until the façade wrapper lands.
- **Check the MongoDB server version** (must be 8.0+ for Next; v6 tolerated older).
- **Confirm the team can absorb pre-1.0 upgrades.** Next publishes versioned upgrade recipes
between minors; someone has to run them. For a production app, confirm the user accepts
Early Access status before migrating.
## Bad
```text
User: "We're on Prisma 6 with MongoDB. Should we upgrade to Prisma 7?"
Agent: "Yes — here's the v7 upgrade guide. Step 1: install a driver adapter..."
```
Prisma 7 has no MongoDB connector; this migration is impossible and the SQL driver-adapter
steps corrupt a working v6 setup.
## Good
```text
User: "We're on Prisma 6 with MongoDB. Should we upgrade to Prisma 7?"
Agent: "Prisma 7 does not support MongoDB — v6 is the last classic-ORM
major for MongoDB. The path forward is Prisma Next, the successor: its MongoDB support is
Early Access and migrating is encouraged. Let me check the codebase for blockers first —
searching for $transaction usage and checking the MongoDB server version..."
```
## Stay-on-v6 hygiene
Staying is a decision, not a default-by-neglect:
- Pin `prisma` and `@prisma/client` to the latest 6.x and keep taking 6.x patches.
- Watch Prisma release notes and security advisories for the 6.x maintenance line.
- Keep the classic setup (`url = env("DATABASE_URL")` in the schema; `db push`; no SQL
driver adapters).
- Re-evaluate when Prisma Next's MongoDB is GA, or when blockers for trying EA are resolved.
## References
- [Prisma Next repository](https://github.com/prisma/prisma-next)
- [Prisma v6 MongoDB documentation](https://www.prisma.io/docs/orm/overview/databases/mongodb)
@@ -0,0 +1,65 @@
# migrations-mapping
How the v6 MongoDB "no migrations" story maps onto Prisma Next's first-class migration flow.
## Priority
HIGH
## Why It Matters
This is the largest workflow change in the migration — in v6, MongoDB explicitly has no
Prisma Migrate, while in Prisma Next MongoDB participates in the full migration lifecycle.
Teams porting a `db push` habit into Next without understanding the plan/verify/sign flow
will fight the tooling or bypass its safety rails.
## v6: `db push` only
MongoDB on v6 has no Prisma Migrate and no plans to add it — "MongoDB projects do not rely
on internal schemas" ([no support for Prisma Migrate](https://www.prisma.io/docs/orm/overview/databases/mongodb#no-support-for-prisma-migrate)).
The workflow is `prisma db push` to sync indexes and unique constraints, with no migration
history on disk.
## Prisma Next: first-class, contract-driven migrations (Mongo included)
Migration authoring in Next is first-class for Postgres **and Mongo** (prisma-next
`skills/prisma-next-migrations/SKILL.md`) — MongoDB is not a push-only special case:
- **Flow:** contract *emit* → diff → *plan* (writes a content-hashed migration package) →
*migrate* (apply in graph order) → *verify* (live schema vs destination contract) →
*sign* (advance the marker after a verify pass).
- **Mongo migration ops** come from dedicated factories: `createCollection`,
`dropCollection`, `validatedCollection`, `setValidation`, `createIndex`, `dropIndex`,
`collMod`, and `dataTransform` for data backfills.
- **Marker storage:** Next records migration state in a document in the
`_prisma_migrations` collection (per space) — the same collection name family v6 users
know from SQL, repurposed for Mongo state.
- **DDL is not transactional on Mongo:** the runner applies operations, verifies the live
schema against the destination contract, and only advances the marker on a verify pass —
making interrupted runs resumable rather than atomic (see Prisma Next's
`prisma-next-migrations` skill).
- **Push-style alternative still exists:** `db update` diffs the live database against the
contract and applies directly without writing a migration directory — the closest
analogue to the v6 `db push` habit, at the cost of no history.
- Validators: Next emits closed `$jsonSchema` validators by default since 0.12 (prisma-next
`CHANGELOG.md`) — collections gain schema enforcement v6 never applied.
## Bad
```text
Porting the v6 habit: run the Next equivalent of `db push` for every change in production,
accumulating no migration history, and hand-editing collections when verification fails.
```
## Good
```text
Adopt the Next lifecycle: emit the contract, plan a migration package, apply it with
migrate, let verify gate the marker, and sign. Reserve `db update` for local prototyping,
mirroring how `db push` was used on v6.
```
## References
- [v6: no Prisma Migrate for MongoDB](https://www.prisma.io/docs/orm/overview/databases/mongodb#no-support-for-prisma-migrate)
- Prisma Next migrations skill (`skills/prisma-next-migrations`) — authoritative for the Next side; verified @ `a2791c5dd59d579b4b3052942ae7f8fe5e2ee852`
@@ -0,0 +1,52 @@
# schema-contract-mapping
How v6 MongoDB schema concepts map onto Prisma Next's contract model.
## Priority
HIGH
## Why It Matters
Prisma Next does not consume the v6 `schema.prisma` as-is: the schema becomes a *contract*
(authored in PSL or TypeScript via the contract builder), and several v6 MongoDB idioms have
different — or deliberately absent — equivalents. Translating mechanically without knowing
the mapping produces contracts that fail verification or, worse, silently change collection
addressing.
## The mapping
| v6 concept | Prisma Next equivalent | Notes |
|------------|------------------------|-------|
| `datasource db { provider = "mongodb" }` + `url = env(...)` ([v6 docs](https://www.prisma.io/docs/orm/overview/databases/mongodb#example)) | `defineConfig` from `@prisma-next/mongo/config` wiring the mongo family/target/adapter/driver descriptors | Next selects MongoDB by importing the `@prisma-next/mongo` façade, not by a provider string in the schema; `prisma-next init` accepts `mongodb` as a target name |
| `@id @default(auto()) @map("_id") @db.ObjectId` ([using ObjectId](https://www.prisma.io/docs/orm/overview/databases/mongodb#using-objectid)) | ObjectId-typed id field in the Next contract (PSL or TS builder) | Verify the exact attribute surface against the installed Next version's `prisma-next-contract` skill — the contract builder also exposes `index` and `valueObject` |
| Composite (embedded) types — MongoDB-only in v6 ([composite types](https://www.prisma.io/docs/orm/prisma-client/special-fields-and-types/composite-types)) | Value objects / embedded shapes in the Next contract (`valueObject` in the Mongo contract builder) | Same conceptual role: documents embedded in a parent document |
| Model names address the client (`prisma.user`) | **Collection storage names** address the ORM: `db.orm.users`, i.e. the `@@map(...)` name or the lowercased model name — not `db.orm.User` | prisma-next `skills/prisma-next/SKILL.md`, `skills/prisma-next-quickstart/SKILL.md`; the most common porting mistake |
| Indexes declared in schema, applied by `db push` | Indexes are contract-declared and applied through migrations (`createIndex`/`dropIndex` factories) | See `migrations-mapping.md` |
| No native polymorphism | No schema-layer polymorphism on Mongo either: `@@base`/`@@discriminator` are SQL-only in Next; model an explicit `discriminator` field | prisma-next `skills/prisma-next-contract/SKILL.md` |
## Bad
```typescript
// Ported from v6 and addressed by model name:
const user = await db.orm.User.first(); // undefined — Mongo ORM keys are storage names
```
## Good
```typescript
// Mongo ORM keys are collection storage names (@@map or lowercased model name):
const user = await db.orm.users.first();
```
## Environment requirements
Prisma Next's Mongo target requires MongoDB 8.0+ and `mongodb@^7` installed by the user as a
peer dependency (prisma-next `CHANGELOG.md`, 0.11→0.12). v6 supports older MongoDB servers,
so check the server version before planning a migration.
## References
- [v6 MongoDB schema documentation](https://www.prisma.io/docs/orm/overview/databases/mongodb)
- [v6 composite types (MongoDB-only)](https://www.prisma.io/docs/orm/prisma-client/special-fields-and-types/composite-types)
- Prisma Next contract skill (`skills/prisma-next-contract`) in the prisma-next repository — authoritative for the Next side
@@ -0,0 +1,60 @@
# verify-cutover-checklist
Verification checklist for a v6 → Prisma Next cutover: the data never moves — only the code does.
## Priority
CRITICAL
## Why It Matters
A v6 → Next migration is a *client and workflow* migration against the **same MongoDB
database** — there is no data export/import step, and introducing one (or pointing the new
stack at a fresh database) turns a code migration into an outage. The checklist below keeps
the cutover observable and reversible.
## Ground rules
- **No data moves.** The Next contract is authored to describe the existing collections;
both stacks read the same database during the staged phase.
- **v6 stays runnable until cutover is verified.** Do not delete the v6 client, schema, or
dependencies until the checklist passes.
## Checklist
1. **Same database, verified:** the Next config points at the same connection string /
database name the v6 app uses (minus v6-specific URL parameters that the `mongodb@^7`
driver rejects — validate the URL with the driver first).
2. **Server floor:** MongoDB server is 8.0+ (Next's requirement; v6 tolerated older).
Confirm before authoring any contract.
3. **Contract round-trip on a copy:** on a staging copy (or `mongodb-memory-server`), emit
the contract, run plan → migrate → verify → sign, and confirm `verify` passes against
data copied from production shape. Verification failures here are contract-mapping bugs,
not database problems.
4. **Index parity:** enumerate indexes on every collection (`db.collection.getIndexes()`)
and confirm the Next contract declares the same set — v6 `db push` may have created
indexes the new contract must re-declare, or verification and query performance will
diverge.
5. **Validator impact assessed:** Next emits closed `$jsonSchema` validators by default;
confirm legacy documents (extra fields, drifted shapes) pass them on the staging copy
before applying to production.
6. **Storage-name addressing audited:** every ported call site uses collection storage
names (`db.orm.users`), not model names (see `schema-contract-mapping.md`).
7. **Transaction inventory mapped:** grep the v6 app for `$transaction`; each hit gets a
driver-session equivalent (the `mongodb` driver is directly available; the façade wrapper
is expected soon — see `client-api-mapping.md`).
8. **Raw call inventory mapped:** every `$runCommandRaw` / `findRaw` / `aggregateRaw` call
has an explicit Next-side replacement (`mongoRaw(...)` lane or pipeline builder).
9. **Staged read-only soak:** run the Next stack read-only against staging/production data
alongside v6 and compare outputs before allowing writes.
10. **Cutover + rollback:** switch writes to Next only after the soak; keep the v6 branch
deployable as the rollback path. Rolling back is a code rollback — the data was never
moved.
After cutover, install and follow Prisma Next's own skills for ongoing work (see the
hand-off rule in `SKILL.md`).
## References
- [v6 MongoDB documentation](https://www.prisma.io/docs/orm/overview/databases/mongodb)
- Prisma Next migrations + queries skills — authoritative for the Next side; verified @ `a2791c5dd59d579b4b3052942ae7f8fe5e2ee852`
@@ -0,0 +1,263 @@
---
name: prisma-postgres-setup
description: Set up a new Prisma Postgres database and connect it to a local project using the Management API. Use when asked to "set up a database", "create a Prisma Postgres project", "get a connection string", "connect my app to Prisma Postgres", or "provision a database".
license: MIT
metadata:
author: prisma
version: "1.1.0"
---
# Prisma Postgres Setup
Procedural skill that guides you through provisioning a new Prisma Postgres database via the Management API and connecting it to a local project.
## When to Apply
Use this skill when:
- Setting up a new Prisma Postgres database for a project
- Creating a Prisma Postgres project and connecting it locally
- Obtaining a connection string for Prisma Postgres
- Provisioning a database via the Management API (not the Console UI)
Do **not** use this skill when:
- Setting up CI/CD preview databases — use `prisma-postgres-cicd`
- Building multi-tenant database provisioning into an app — use `prisma-postgres-integrator`
- Working with a database that already exists and is connected (schema/migration tasks are standard Prisma CLI)
## Prerequisites
- Node.js 18+
- A Prisma Postgres workspace (create one at https://console.prisma.io if needed)
- A workspace service token (see `references/auth.md`)
## UX Guidelines
When presenting choices to the user (region selection, project deletion, etc.), **use your platform's interactive selection mechanism** (e.g., `ask` tool in Claude Code, structured prompts in other agents). Do not print static tables and ask the user to type a value — present selectable options so the user can pick with minimal effort.
## Workflow
Follow these steps in order. Each step includes the API call to make and how to handle the response.
### Step 1: Authenticate
You need a service token. Try these methods in order:
**1a. Token in the user's prompt**
Check if the user included a service token in their initial message (e.g., "Set up Prisma Postgres with token eyJ..."). If so, use it **exactly as provided** — do not truncate, re-encode, or round-trip it through a file. Store it in a shell variable for subsequent calls.
**1b. Token in the environment**
Check for `PRISMA_SERVICE_TOKEN` in the environment or `.env` file.
**1c. Ask the user to create one**
If no token is available, instruct the user:
> Create a service token in Prisma Console → Workspace Settings → Service Tokens.
> Copy the token and paste it here.
Read `references/auth.md` for details on service token creation.
Once you have a token, store it in a shell variable (`PRISMA_SERVICE_TOKEN`) and use it for all subsequent API calls.
### Step 2: List available regions
Fetch the list of available Prisma Postgres regions to let the user choose where to deploy.
```bash
curl -s -H "Authorization: Bearer $PRISMA_SERVICE_TOKEN" \
https://api.prisma.io/v1/regions/postgres
```
The response contains an array of regions with `id`, `name`, and `status`. Only present regions where `status` is `available`.
**Present the regions as an interactive menu** — let the user pick from options rather than typing a region ID manually.
Read `references/endpoints.md` for the full response shape.
### Step 3: Create a project with a database
```bash
curl -s -X POST https://api.prisma.io/v1/projects \
-H "Authorization: Bearer $PRISMA_SERVICE_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"name": "<project-name>",
"region": "<region-id>",
"createDatabase": true
}'
```
Use the current directory name as the project name by default.
The response is wrapped in `{ "data": { ... } }`. Extract:
- `data.id` — the project ID (prefixed with `proj_`)
- `data.database.id` — the database ID (prefixed with `db_`)
- `data.database.connections[0].endpoints.direct.connectionString` — the direct PostgreSQL connection string
Use the **direct** connection string (`endpoints.direct.connectionString`). Do not use the pooled or accelerate endpoints — those are for legacy Accelerate setups and not needed for new projects.
If the response status is `provisioning`, wait a few seconds and poll `GET /v1/databases/<database-id>` until `status` is `ready`.
**If creation fails due to a database limit**, list the user's existing projects and present them as an interactive menu for deletion. After the user picks one, delete it and retry.
Read `references/endpoints.md` for the full request/response shapes.
### Step 4: Create a named connection (optional)
If you need a dedicated connection (e.g., per-developer or per-environment), create one:
```bash
curl -s -X POST https://api.prisma.io/v1/databases/<database-id>/connections \
-H "Authorization: Bearer $PRISMA_SERVICE_TOKEN" \
-H "Content-Type: application/json" \
-d '{ "name": "dev" }'
```
Extract the direct connection string from `data.endpoints.direct.connectionString`.
### Step 5: Configure the local project
1. Install dependencies:
```bash
npm install prisma @prisma/client @prisma/adapter-pg pg dotenv
```
All five packages are required:
- `prisma` — CLI for migrations, schema push, client generation
- `@prisma/client` — the generated query client
- `@prisma/adapter-pg` — Prisma 7 driver adapter for direct PostgreSQL connections
- `pg` — Node.js PostgreSQL driver (used by the adapter)
- `dotenv` — loads `.env` variables for `prisma.config.ts`
2. Write the direct connection string to `.env`. **Append** to the file if it already exists — do not overwrite existing entries:
```
DATABASE_URL="<direct-connection-string>"
```
3. Verify `.gitignore` includes `.env`. Create `.gitignore` if it does not exist. Warn the user if `.env` is not gitignored.
4. Ensure `package.json` has `"type": "module"` set (Prisma 7 generates ESM output).
5. If `prisma/schema.prisma` does not exist, run `npx prisma init` to scaffold the project. This creates both `prisma/schema.prisma` and `prisma.config.ts`.
6. Ensure `schema.prisma` has the `postgresql` provider and **no** `url` or `directUrl` in the datasource block (Prisma 7 manages connection URLs in `prisma.config.ts`, not in the schema):
```prisma
datasource db {
provider = "postgresql"
}
```
7. Ensure `prisma.config.ts` loads the connection URL from the environment:
```typescript
import path from 'node:path'
import { defineConfig } from 'prisma/config'
import 'dotenv/config'
export default defineConfig({
earlyAccess: true,
schema: path.join(import.meta.dirname, 'prisma', 'schema.prisma'),
datasource: {
url: process.env.DATABASE_URL!,
},
})
```
**Important Prisma 7 notes:**
- Connection URLs go in `prisma.config.ts`, never in `schema.prisma`
- The provider in `schema.prisma` must be `"postgresql"` (not `"prismaPostgres"`)
- `dotenv/config` must be imported in `prisma.config.ts` to load `.env` variables
### Step 6: Define schema and push
If the schema already has models, skip to pushing. Otherwise, **present these options as an interactive menu**:
1. **"I'll define my schema manually"** — Tell the user to edit `prisma/schema.prisma` and come back when ready. Wait for them before proceeding.
2. **"Give me a starter schema"** — Add a Blog starter schema (User, Post, Comment with relations) to `prisma/schema.prisma`. Show the user what was added and ask if they want to adjust it before pushing.
3. **"I'll describe what I need"** — Ask the user to describe their data model in natural language (e.g., "I'm building a task manager with projects, tasks, and team members"). Generate a schema from the description, show it, and ask for confirmation before pushing.
Once the schema has models and the user is ready, create a migration and generate the client:
```bash
npx prisma migrate dev --name init
```
This creates migration files in `prisma/migrations/` **and** generates the client in one step. Migration history is essential for CI/CD workflows (`prisma migrate deploy`) and production deployments.
Only use `npx prisma db push` if the user explicitly asks for prototyping-only mode (no migration history). In that case, follow it with `npx prisma generate`.
### Step 7: Verify the connection
After generating the client, create and run a quick verification script to confirm everything works end-to-end. This is **critical** — do not skip this step.
Create a file named `test-connection.ts`:
```typescript
import 'dotenv/config'
import pg from 'pg'
import { PrismaPg } from '@prisma/adapter-pg'
import { PrismaClient } from './generated/prisma/client.js'
const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL })
const adapter = new PrismaPg(pool)
const prisma = new PrismaClient({ adapter })
const result = await prisma.$queryRawUnsafe('SELECT 1 as connected')
console.log('Connected to Prisma Postgres:', result)
await prisma.$disconnect()
await pool.end()
```
Run it:
```bash
npx tsx test-connection.ts
```
**Prisma 7 client instantiation rules:**
- Import from `./generated/prisma/client.js` (not `./generated/prisma`)
- Create a `pg.Pool` with the `DATABASE_URL` connection string
- Wrap it in a `PrismaPg` adapter
- Pass `{ adapter }` to the `PrismaClient` constructor
- Do **not** use `datasourceUrl` — that option does not exist in Prisma 7
- Do **not** use `new PrismaClient()` with no arguments — it will throw
After verification succeeds, delete `test-connection.ts`.
Then share links for the user to explore their database:
- **Prisma Studio (CLI):** `npx prisma studio` — opens a visual data browser locally
- **Console:** `https://console.prisma.io/<workspaceId>/<projectId>/<databaseId>/dashboard` — strip the prefixes (`wksp_`, `proj_`, `db_`) from the IDs returned in Step 3 to build this URL
Read `references/prisma7-client.md` for the full client instantiation reference.
## Error Handling
Read `references/api-basics.md` for the full error reference. Key self-correction patterns:
| HTTP Status | Error Code | Action |
|---|---|---|
| 401 | `authentication-failed` | Service token is invalid or expired. Ask the user to create a new one in Console → Workspace Settings → Service Tokens. |
| 404 | `resource-not-found` | Check that the resource ID includes the correct prefix (`proj_`, `db_`, `con_`). |
| 422 | `validation-error` | Check request body against the endpoint schema. Common: missing `name`, invalid `region`. |
| 429 | `rate-limit-exceeded` | Back off and retry after a few seconds. |
## Reference Files
Detailed API and usage information is in:
```
references/auth.md — Service token creation and usage
references/api-basics.md — Base URL, envelope, IDs, errors, pagination
references/endpoints.md — Endpoint details for projects, databases, connections, regions
references/prisma7-client.md — Prisma 7 client instantiation and usage patterns
```
@@ -0,0 +1,102 @@
# api-basics
Core conventions for the Prisma Management API. All three `prisma-postgres-*` skills share these patterns.
## Base URL
```
https://api.prisma.io/v1
```
API documentation: https://api.prisma.io/v1/doc
## Response Envelope
### Single resource
```json
{
"data": {
"id": "proj_clx7abc123def456",
"type": "project",
"name": "My Project",
"createdAt": "2025-06-15T10:30:00.000Z"
}
}
```
### Collection
```json
{
"data": [
{ "id": "proj_aaa", "type": "project", "name": "Alpha" },
{ "id": "proj_bbb", "type": "project", "name": "Beta" }
],
"pagination": {
"hasMore": true,
"nextCursor": "clx7cursor123"
}
}
```
## Resource ID Prefixes
Every resource ID carries a type prefix:
| Prefix | Resource |
|---|---|
| `proj_` | Project |
| `db_` | Database |
| `con_` | Connection |
| `wksp_` | Workspace |
Always include the prefix when sending IDs in API requests.
## Pagination
Collection endpoints use cursor-based pagination:
```
GET /v1/projects?limit=10
GET /v1/projects?cursor=clx7abc123&limit=10
```
| Parameter | Type | Default | Description |
|---|---|---|---|
| `cursor` | string | — | Opaque cursor from `nextCursor` |
| `limit` | number | 100 | Maximum items per page |
Continue fetching while `pagination.hasMore` is `true`, using `pagination.nextCursor` as the `cursor` parameter.
## Error Responses
All errors follow this shape:
```json
{
"error": {
"code": "resource-not-found",
"message": "database with id db_abc not found"
}
}
```
### Error codes by HTTP status
| HTTP Status | Error Code | Meaning |
|---|---|---|
| 400 | `client-error` | Malformed request |
| 401 | `authentication-failed` | Missing or invalid token |
| 403 | `permission-denied` | Token lacks required access |
| 404 | `resource-not-found` | Resource does not exist or is not accessible |
| 422 | `validation-error` | Request body failed validation |
| 429 | `rate-limit-exceeded` | Too many requests |
| 500 | `internal-server-error` | Server error — retry after a delay |
### Self-correction patterns
- **401**: Token is invalid or expired. Create a new service token in Console → Workspace Settings → Service Tokens.
- **404**: Verify the resource ID includes the correct prefix (`proj_`, `db_`, `con_`). Use `GET /v1/projects` or `GET /v1/databases` to list available resources.
- **422**: Check the request body against the endpoint schema. Common issues: missing required fields, invalid region ID, empty `name`.
- **429**: Wait 2–5 seconds and retry. If repeated, increase the backoff interval.
@@ -0,0 +1,46 @@
# auth
How to authenticate with the Prisma Management API using service tokens.
## Service Tokens
Service tokens authenticate server-to-server requests. They are scoped to a workspace and grant access to all resources within it.
### Creating a service token
1. Open https://console.prisma.io
2. Navigate to **Workspace Settings** → **Service Tokens**
3. Click **Create Token**
4. Copy the token immediately — it is only shown once
### Using a service token
Set the token as an environment variable:
```bash
export PRISMA_SERVICE_TOKEN="eyJ..."
```
Include it in the `Authorization` header of every API request:
```bash
curl -H "Authorization: Bearer $PRISMA_SERVICE_TOKEN" \
https://api.prisma.io/v1/projects
```
### Token scope
Service tokens are workspace-scoped. A single token grants access to all projects, databases, and connections within the workspace. There are no project-scoped tokens at this time.
### Security practices
- Store tokens in environment variables or secret managers, never in source code
- Add `.env` to `.gitignore` to prevent accidental commits
- Rotate tokens periodically via Console → Workspace Settings → Service Tokens
- In CI/CD, store tokens as encrypted secrets (e.g., GitHub Secrets)
## OAuth 2.0 (for user-scoped access)
OAuth is used when acting on behalf of a user, typically in partner/integrator flows. See the `prisma-postgres-integrator` skill for OAuth details.
For standard database setup, service tokens are the recommended authentication method.
@@ -0,0 +1,223 @@
# endpoints
Management API endpoint details for database setup workflows.
## List regions
```
GET /v1/regions/postgres
```
No request body. Returns available Prisma Postgres regions.
**Response:**
```json
{
"data": [
{
"id": "us-east-1",
"type": "region",
"name": "US East (N. Virginia)",
"status": "available"
},
{
"id": "eu-west-1",
"type": "region",
"name": "EU West (Ireland)",
"status": "available"
}
]
}
```
Only use regions where `status` is `available`.
## Create project (with database)
```
POST /v1/projects
```
**Request body:**
```json
{
"name": "my-project",
"region": "us-east-1",
"createDatabase": true
}
```
| Field | Type | Required | Default | Description |
|---|---|---|---|---|
| `name` | string | No | Auto-generated | Project display name |
| `region` | string | No | `us-east-1` | Region for the database |
| `createDatabase` | boolean | No | `true` | Create a default database with the project |
**Response** (with `createDatabase: true`):
```json
{
"data": {
"id": "proj_clx7abc123",
"type": "project",
"url": "https://api.prisma.io/v1/projects/proj_clx7abc123",
"name": "my-project",
"createdAt": "2025-06-15T10:30:00.000Z",
"defaultRegion": "us-east-1",
"workspace": {
"id": "wksp_xyz789",
"url": "https://api.prisma.io/v1/workspaces/wksp_xyz789",
"name": "My Workspace"
},
"database": {
"id": "db_def456",
"type": "database",
"url": "https://api.prisma.io/v1/databases/db_def456",
"name": "my-project",
"status": "ready",
"createdAt": "2025-06-15T10:30:00.000Z",
"isDefault": true,
"defaultConnectionId": "con_ghi789",
"connections": [
{
"id": "con_ghi789",
"type": "connection",
"url": "https://api.prisma.io/v1/connections/con_ghi789",
"name": "Default",
"createdAt": "2025-06-15T10:30:00.000Z",
"kind": "postgres",
"endpoints": {
"direct": {
"host": "db.prisma.io",
"port": 5432,
"connectionString": "postgres://user:pass@db.prisma.io:5432/postgres?sslmode=require"
}
}
}
],
"region": {
"id": "us-east-1",
"name": "US East (N. Virginia)"
}
}
}
}
```
Key field to extract:
- `data.database.connections[0].endpoints.direct.connectionString` → use as `DATABASE_URL`
The response also includes `pooled` and `accelerate` endpoints — ignore these for new projects. The direct connection string is all you need.
If `data.database.status` is `provisioning`, poll `GET /v1/databases/{id}` until `status` is `ready`.
## Get database
```
GET /v1/databases/{databaseId}
```
Use to check database status after creation or to retrieve database details.
**Response:**
```json
{
"data": {
"id": "db_def456",
"type": "database",
"url": "https://api.prisma.io/v1/databases/db_def456",
"name": "my-project",
"status": "ready",
"createdAt": "2025-06-15T10:30:00.000Z",
"isDefault": true,
"defaultConnectionId": "con_ghi789",
"connections": [],
"project": {
"id": "proj_clx7abc123",
"url": "https://api.prisma.io/v1/projects/proj_clx7abc123",
"name": "my-project"
},
"region": {
"id": "us-east-1",
"name": "US East (N. Virginia)"
}
}
}
```
## Create connection
```
POST /v1/databases/{databaseId}/connections
```
Creates a new named connection string for a database. Use for per-developer or per-environment connections.
**Request body:**
```json
{
"name": "dev"
}
```
| Field | Type | Required | Description |
|---|---|---|---|
| `name` | string | Yes | Display name for the connection |
**Response:**
```json
{
"data": {
"id": "con_newcon123",
"type": "connection",
"url": "https://api.prisma.io/v1/connections/con_newcon123",
"name": "dev",
"createdAt": "2025-06-15T10:31:00.000Z",
"kind": "postgres",
"endpoints": {
"direct": {
"host": "db.prisma.io",
"port": 5432,
"connectionString": "postgres://user:pass@db.prisma.io:5432/postgres?sslmode=require"
}
},
"database": {
"id": "db_def456",
"url": "https://api.prisma.io/v1/databases/db_def456",
"name": "my-project"
}
}
}
```
Extract: `data.endpoints.direct.connectionString` → use as `DATABASE_URL`.
## Delete database
```
DELETE /v1/databases/{databaseId}
```
Permanently deletes a database and all its connections. Returns `204 No Content` on success.
## List projects
```
GET /v1/projects
```
Returns all projects in the workspace. Supports cursor-based pagination (`?cursor=...&limit=...`).
## Delete project
```
DELETE /v1/projects/{projectId}
```
Permanently deletes a project and all its databases. Returns `204 No Content` on success.
@@ -0,0 +1,82 @@
# Prisma 7 Client Instantiation
Prisma 7 changed how PrismaClient connects to databases. The CLI (`prisma db push`, `prisma migrate`) reads the URL from `prisma.config.ts`. But at **runtime**, you must provide a driver adapter to PrismaClient explicitly.
## Required packages
```bash
npm install @prisma/client @prisma/adapter-pg pg
```
- `@prisma/adapter-pg` — the Prisma adapter for the `pg` PostgreSQL driver
- `pg` — the underlying Node.js PostgreSQL driver
## Basic instantiation
```typescript
import 'dotenv/config'
import pg from 'pg'
import { PrismaPg } from '@prisma/adapter-pg'
import { PrismaClient } from './generated/prisma/client.js'
const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL })
const adapter = new PrismaPg(pool)
const prisma = new PrismaClient({ adapter })
```
## Key rules
1. **Import path**: Always `./generated/prisma/client.js` — not `./generated/prisma` and not `@prisma/client`.
2. **Adapter is mandatory**: `new PrismaClient()` with no arguments throws. `new PrismaClient({ datasourceUrl: '...' })` also throws — `datasourceUrl` does not exist in Prisma 7.
3. **ESM required**: The generated client uses ESM. Ensure `package.json` has `"type": "module"`.
4. **Pool lifecycle**: Call `await pool.end()` when shutting down (after `prisma.$disconnect()`).
## Usage in application code
```typescript
import 'dotenv/config'
import pg from 'pg'
import { PrismaPg } from '@prisma/adapter-pg'
import { PrismaClient } from './generated/prisma/client.js'
const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL })
const adapter = new PrismaPg(pool)
const prisma = new PrismaClient({ adapter })
// Create
const user = await prisma.user.create({
data: { email: 'alice@example.com', name: 'Alice' },
})
// Read with relations
const posts = await prisma.post.findMany({
where: { published: true },
include: { author: true },
})
// Update
await prisma.post.update({
where: { id: 1 },
data: { published: true },
})
// Delete
await prisma.post.delete({ where: { id: 1 } })
// Cleanup
await prisma.$disconnect()
await pool.end()
```
## Common mistakes
| Mistake | Error | Fix |
|---|---|---|
| `import { PrismaClient } from './generated/prisma'` | `Cannot find module` | Use `./generated/prisma/client.js` |
| `new PrismaClient()` | `PrismaClient needs non-empty options` | Pass `{ adapter }` |
| `new PrismaClient({ datasourceUrl: url })` | `Unknown property datasourceUrl` | Use adapter pattern instead |
| Missing `"type": "module"` in package.json | ESM import errors | Add `"type": "module"` |
| `import { PrismaClient } from '@prisma/client'` | Wrong export | Use `./generated/prisma/client.js` |
+141
View File
@@ -0,0 +1,141 @@
---
name: prisma-postgres
description: Prisma Postgres setup and operations guidance across Console, create-db CLI, Management API, and Management API SDK. Use when creating Prisma Postgres databases, working in Prisma Console, provisioning with create-db/create-pg/create-postgres, or integrating programmatic provisioning with service tokens or OAuth.
license: MIT
metadata:
author: prisma
version: "7.7.0"
---
# Prisma Postgres
Guidance for creating, managing, and integrating Prisma Postgres across interactive and programmatic workflows.
## When to Apply
Reference this skill when:
- Setting up Prisma Postgres from Prisma Console
- Provisioning instant temporary databases with `create-db`
- Linking an existing local project with `prisma postgres link`
- Managing Prisma Postgres resources via Management API
- Using `@prisma/management-api-sdk` in TypeScript/JavaScript
- Handling claim URLs, connection strings, regions, and auth flows
## Rule Categories by Priority
| Priority | Category | Impact | Prefix |
|----------|----------|--------|--------|
| 1 | CLI Provisioning | CRITICAL | `create-db-cli` |
| 2 | Management API | CRITICAL | `management-api` |
| 3 | Management API SDK | HIGH | `management-api-sdk` |
| 4 | Console and Connections | HIGH | `console-and-connections` |
## Quick Reference
- `create-db-cli` - instant databases and current CLI flags (`--ttl`, `--copy`, `--quiet`, `--open`)
- `management-api` - service token and OAuth API workflows
- `management-api-sdk` - typed SDK usage with token storage
- `console-and-connections` - Console operations, `prisma postgres link`, direct TCP connections, and serverless-driver choices
## Core Workflows
### 1. Console-first workflow
Use Prisma Console for manual setup and operations:
- Open `https://console.prisma.io`
- Create/select workspace and project
- Use Studio in the project sidebar to view/edit data
- Retrieve direct connection details from the project UI
### 2. Quick provisioning with create-db
Use `create-db` when you need a database immediately:
```bash
npx create-db@latest
```
Aliases:
```bash
npx create-pg@latest
npx create-postgres@latest
```
For app integrations, you can also use the programmatic API (`create()` / `regions()`) from the `create-db` npm package.
Temporary databases auto-delete after ~24 hours unless claimed.
### 2b. Persistent databases with the Platform CLI
For databases that belong to a Project (not throwaway `create-db` databases), use `@prisma/cli`:
```bash
npx -y @prisma/cli@latest database create main --branch main
npx -y @prisma/cli@latest database list --json
npx -y @prisma/cli@latest database connection create db_123
npx -y @prisma/cli@latest database usage db_123
npx -y @prisma/cli@latest database backup list db_123
```
`database create` and `database connection create` print a one-time connection URL; store it immediately. Destructive commands (`remove`, `restore`) require exact `--confirm <id>`.
### 3. Link an existing local project
Use `prisma postgres link` when the database already exists and you want to wire a local project to it:
```bash
prisma postgres link
```
For CI or other non-interactive environments:
```bash
prisma postgres link --api-key "<your-api-key>" --database "db_..."
```
This flow updates your local `.env` with `DATABASE_URL`, then you can run `prisma generate` and `prisma migrate dev`.
### 4. Programmatic provisioning with Management API
Use API endpoints on:
```text
https://api.prisma.io/v1
```
Explore the schema and endpoints using:
- OpenAPI docs: `https://api.prisma.io/v1/doc`
- Swagger Editor: `https://api.prisma.io/v1/swagger-editor`
Auth options:
- Service token (workspace server-to-server)
- OAuth 2.0 (act on behalf of users)
### 5. Type-safe integration with Management API SDK
Install and use:
```bash
npm install @prisma/management-api-sdk
```
Use `createManagementApiClient` for existing tokens, or `createManagementApiSdk` for OAuth + token refresh.
## Rule Files
Detailed guidance lives in:
```
references/console-and-connections.md
references/create-db-cli.md
references/management-api.md
references/management-api-sdk.md
```
## How to Use
Start with `references/create-db-cli.md` for fast setup, then switch to `references/management-api.md` or `references/management-api-sdk.md` when you need programmatic provisioning.
@@ -0,0 +1,69 @@
# console-and-connections
Use Prisma Console workflows for project visibility, data inspection, and connection setup.
## Priority
HIGH
## Why It Matters
Many Prisma Postgres tasks are quickest in the Console: viewing Studio data, checking metrics, and retrieving connection details. This avoids unnecessary API or CLI work for simple operational tasks.
## Console workflow
1. Open `https://console.prisma.io`.
2. Select workspace and project.
3. Use dashboard metrics for usage and billing visibility.
4. Open the **Studio** tab in the sidebar to inspect and edit data.
## Local Studio
You can also inspect data locally:
```bash
npx prisma studio
```
## Linking an existing project
If the Prisma Postgres database already exists, link the local project instead of provisioning a new one:
```bash
prisma postgres link
```
For CI or non-interactive usage:
```bash
prisma postgres link --api-key "<your-api-key>" --database "db_..."
```
This command updates or creates `.env` with `DATABASE_URL`. If the project is already linked, use `--force` to re-link. After linking, run `prisma generate`, then `prisma migrate dev` if you need to apply the schema.
## Connection setup
For direct PostgreSQL tools and drivers:
- Generate/copy direct connection credentials from the project connection UI.
- Use the resulting PostgreSQL URL as `DATABASE_URL` for `pg` and `@prisma/adapter-pg`.
- For Prisma Postgres direct TCP, include `sslmode=require`.
Typical direct TCP format:
```env
DATABASE_URL="postgres://identifier:key@db.prisma.io:5432/postgres?sslmode=require"
```
Management API connection responses expose both `endpoints.direct` (`db.prisma.io:5432`) and `endpoints.pooled` (`pooled.db.prisma.io:5432`); prefer those fields over the deprecated flat `connectionString`. Connection secrets are shown once at creation (one-time view); store them immediately.
## Adapter choices
- Standard Node.js apps: prefer `@prisma/adapter-pg` with the direct TCP URL above.
- Edge/serverless runtimes: use `@prisma/adapter-ppg` with `@prisma/ppg` only when you specifically need the Prisma Postgres serverless driver.
## References
- [Prisma Postgres overview](https://www.prisma.io/docs/postgres/introduction/overview)
- [Viewing data](https://www.prisma.io/docs/postgres/integrations/viewing-data)
- [Direct connections](https://www.prisma.io/docs/postgres/database/direct-connections)
@@ -0,0 +1,136 @@
# create-db-cli
Use `create-db` for instant Prisma Postgres provisioning from the terminal.
## Priority
CRITICAL
## Why It Matters
`create-db` is the fastest way to get a working Prisma Postgres instance for development, demos, and CI previews. It can also emit machine-readable output and write env variables directly.
## Commands
```bash
npx create-db@latest
npx create-db@latest create [options]
npx create-db@latest regions
```
Aliases:
```bash
npx create-pg@latest
npx create-postgres@latest
```
## Command discovery (`--help`)
Always use `--help` first when integrating CLI commands:
```bash
npx create-db@latest --help
npx create-db@latest create --help
npx create-db@latest regions --help
```
Top-level commands currently exposed:
- `create` (default) to provision a database
- `regions` to list available regions
## `create` options
| Flag | Shorthand | Description |
|---|---|---|
| `--region [string]` | `-r` | Region choice: `ap-southeast-1`, `ap-northeast-1`, `eu-central-1`, `eu-west-3`, `us-east-1`, `us-west-1` |
| `--interactive [boolean]` | `-i` | Open region selector |
| `--json [boolean]` | `-j` | Output machine-readable JSON |
| `--env [string]` | `-e` | Write `DATABASE_URL` and `CLAIM_URL` into a target `.env` |
| `--ttl [string]` | `-t` | Auto-delete after a TTL like `30m` or `1h-24h` |
| `--copy [boolean]` | `-c` | Copy the connection string to the clipboard |
| `--quiet [boolean]` | `-q` | Only print the connection string |
| `--open [boolean]` | `-o` | Open the claim URL in your browser |
## Lifecycle and claim flow
- Databases are temporary by default.
- Unclaimed databases are auto-deleted after ~24 hours.
- Claim the database using the URL shown in command output to keep it permanently.
## Programmatic usage (library API)
You can also use `create-db` programmatically in Node.js/Bun instead of shelling out to the CLI.
Install:
```bash
npm install create-db
# or
bun add create-db
```
Create a database:
```ts
import { create, isDatabaseSuccess, isDatabaseError } from "create-db";
const result = await create({
region: "us-east-1",
userAgent: "my-app/1.0.0",
});
if (isDatabaseSuccess(result)) {
console.log(result.connectionString);
console.log(result.claimUrl);
console.log(result.deletionDate);
}
if (isDatabaseError(result)) {
console.error(result.error, result.message);
}
```
List regions programmatically:
```ts
import { regions } from "create-db";
const available = await regions();
console.log(available);
```
Programmatic `create()` defaults to `us-east-1` if no region is passed.
## Common patterns
```bash
# quick database
npx create-db@latest
# region-specific database
npx create-db@latest --region eu-central-1
# interactive region selection
npx create-db@latest --interactive
# write env vars for app bootstrap
npx create-db@latest --env .env
# auto-delete sooner
npx create-db@latest --ttl 2h
# copy connection string to clipboard
npx create-db@latest --copy
# print only the connection string
npx create-db@latest --quiet
# CI-friendly output
npx create-db@latest --json
```
## References
- [npx create-db docs](https://www.prisma.io/docs/postgres/introduction/npx-create-db)
@@ -0,0 +1,56 @@
# management-api-sdk
Use `@prisma/management-api-sdk` for typed API integration with optional OAuth and token refresh.
## Priority
HIGH
## Why It Matters
The SDK provides typed endpoint methods and removes boilerplate around auth and refresh handling, which reduces errors in production provisioning flows.
## Install
```bash
npm install @prisma/management-api-sdk
```
## Simple client (existing token)
```typescript
import { createManagementApiClient } from '@prisma/management-api-sdk'
const client = createManagementApiClient({ token: process.env.PRISMA_SERVICE_TOKEN! })
const { data: workspaces } = await client.GET('/v1/workspaces')
```
## Full SDK (OAuth + refresh)
```typescript
import { createManagementApiSdk, type TokenStorage } from '@prisma/management-api-sdk'
const tokenStorage: TokenStorage = {
async getTokens() { return null },
async setTokens(tokens) {},
async clearTokens() {},
}
const api = createManagementApiSdk({
clientId: process.env.PRISMA_CLIENT_ID!,
redirectUri: 'https://your-app.com/auth/callback',
tokenStorage,
})
```
## OAuth SDK flow
1. Call `getLoginUrl()` and persist `state` + `verifier`.
2. Redirect user to login URL.
3. Handle callback with `handleCallback()`.
4. Use `api.client` for typed endpoint calls.
5. Call `logout()` when needed.
## References
- [Management API SDK docs](https://www.prisma.io/docs/postgres/introduction/management-api-sdk)
@@ -0,0 +1,69 @@
# management-api
Use Prisma Management API for programmatic provisioning and workspace/project/database management.
## Priority
CRITICAL
## Why It Matters
When you need backend automation, multi-tenant onboarding flows, or controlled resource provisioning, the Management API is the source of truth and is more reliable than interactive workflows.
## Base URL
```text
https://api.prisma.io/v1
```
## API exploration
- OpenAPI docs: `https://api.prisma.io/v1/doc`
- Swagger Editor: `https://api.prisma.io/v1/swagger-editor`
## Authentication methods
- Service token: best for server-to-server operations in your own workspace
- OAuth 2.0: best for acting on behalf of users across workspaces
## Service token flow
1. Create token in Prisma Console workspace settings.
2. Send token as Bearer auth:
```text
Authorization: Bearer $TOKEN
```
## OAuth flow summary
1. Redirect user to `https://auth.prisma.io/authorize` with `client_id`, `redirect_uri`, `response_type=code`, and scopes.
2. Receive `code` on callback.
3. Exchange code at `https://auth.prisma.io/token`.
4. Use returned access token in Management API requests.
## Resource model
Workspace -> Project -> Branch -> Database. Branches are a first-class resource: databases attach to a Branch, and branch-scoped env/databases are how preview isolation works.
## Common endpoints
- `GET /workspaces`
- `GET /projects`
- `POST /projects`
- `GET`/`POST /projects/:projectId/branches`
- `GET`/`PATCH`/`DELETE /branches/:branchId`
- Databases at both `/databases` (flat) and `/projects/:projectId/databases`
- Connection responses return structured `endpoints.direct` and `endpoints.pooled` objects; the flat top-level `connectionString` is deprecated in favor of `endpoints.direct.connectionString`/`endpoints.pooled.connectionString`
- Connection secrets are one-time view: revealed at creation, never re-readable from later GETs
## Notes
- Management API responses may include direct connection credentials for databases.
- Build PostgreSQL `DATABASE_URL` from direct connection values when needed.
## References
- [Management API docs](https://www.prisma.io/docs/postgres/introduction/management-api)
- [OpenAPI docs](https://api.prisma.io/v1/doc)
- [Swagger Editor](https://api.prisma.io/v1/swagger-editor)
+259
View File
@@ -0,0 +1,259 @@
---
name: prisma-upgrade-v7
description: Complete migration guide from Prisma ORM v6 to v7 covering all breaking changes. Use when upgrading Prisma versions, encountering v7 errors, or migrating existing projects. Triggers on "upgrade to prisma 7", "prisma 7 migration", "prisma-client generator", "driver adapter required".
license: MIT
metadata:
author: prisma
version: "7.6.0"
---
# Upgrade to Prisma ORM 7
Complete guide for migrating from Prisma ORM v6 to v7. This upgrade introduces significant breaking changes around the new `prisma-client` generator, driver adapters, `prisma.config.ts`, explicit environment loading, and generated client entrypoints.
## When to Apply
Reference this skill when:
- Upgrading from Prisma v6 to v7
- Updating to the `prisma-client` generator
- Setting up driver adapters
- Configuring `prisma.config.ts`
- Fixing import errors after upgrade
## Rule Categories by Priority
| Priority | Category | Impact | Prefix |
|----------|----------|--------|--------|
| 1 | Schema Migration | CRITICAL | `schema-changes` |
| 2 | Database Connectivity | CRITICAL | `driver-adapters` |
| 3 | Module System | CRITICAL | `esm-support` |
| 4 | Config and Env | HIGH | `prisma-config`, `env-variables` |
| 5 | Removed Features | HIGH | `removed-features` |
| 6 | Accelerate | HIGH | `accelerate-users` |
## Quick Reference
- `schema-changes` - generator migration, required output paths, generated entrypoints, and `Prisma.validator` replacement
- `driver-adapters` - required adapter installation for SQL providers, pool differences, and Prisma Postgres adapter choices
- `esm-support` - ESM-first setup plus CommonJS fallback with `moduleFormat = "cjs"`
- `prisma-config` - creating and using `prisma.config.ts`
- `env-variables` - explicit environment loading
- `removed-features` - removed middleware, metrics, and legacy CLI behavior
- `accelerate-users` - migration notes for Accelerate users
## Using MongoDB? This guide does not apply
Prisma 7 has no MongoDB connector. Do not apply any step in this guide to a project with
`provider = "mongodb"` — see the `prisma-mongodb-upgrade` skill for the actual decision
(stay on v6 deliberately vs migrate to Prisma Next).
## Important Notes
- **MongoDB projects should stay on Prisma 6.x or migrate to Prisma Next** - do not migrate MongoDB apps to Prisma 7's SQL client path (see `prisma-mongodb-upgrade`)
- **Node.js 20.19.0+** required
- **TypeScript 5.4.0+** required
- **Latest stable Prisma ORM version**: `7.6.0`
## Upgrade Steps Overview
1. Update packages to v7
2. Choose your module format (`esm` by default, `cjs` if needed)
3. Update TypeScript configuration
4. Update the schema generator block
5. Create `prisma.config.ts`
6. Install and configure a driver adapter for SQL providers
7. Update Prisma Client imports
8. Update client instantiation
9. Replace deprecated helper patterns like `Prisma.validator`
10. Run `prisma generate` and test
## Quick Upgrade Commands
```bash
# Update packages
npm install @prisma/client@7
npm install -D prisma@7
# Install a driver adapter (PostgreSQL or Prisma Postgres via direct TCP)
npm install @prisma/adapter-pg pg
# Install dotenv for env loading
npm install dotenv
# Regenerate client
npx prisma generate
```
## Breaking Changes Summary
| Change | v6 | v7 |
|--------|----|----|
| Module format | Implicit / mixed | ESM-first, `moduleFormat = "cjs"` supported |
| Generator provider | `prisma-client-js` | `prisma-client` is the default, while `prisma-client-js` still exists for legacy setups |
| Output path | Auto (node_modules) | Required explicit |
| Driver adapters | Optional | Required for SQL providers |
| Config file | `.env` + schema | `prisma.config.ts` |
| Env loading | Automatic | Manual (dotenv) |
| Generated entrypoints | Single package export | `client`, `browser`, `models`, `enums` entrypoints |
| Type-safe query fragments | `Prisma.validator()` | TypeScript `satisfies` |
| Middleware | `$use()` | Client Extensions |
| Metrics | Preview feature | Removed |
## Rule Files
Detailed migration guides for each breaking change:
```
references/esm-support.md - ESM and CommonJS configuration
references/schema-changes.md - Generator, output, imports, and generated entrypoints
references/driver-adapters.md - Required driver adapter setup
references/prisma-config.md - New configuration file
references/env-variables.md - Environment variable loading
references/removed-features.md - Middleware, metrics, and CLI flags
references/accelerate-users.md - Special handling for Accelerate
```
## Step-by-Step Migration
### 1. Update package.json for ESM-first projects
```json
{
"type": "module"
}
```
If you need to stay on CommonJS, keep your app as CJS and set `moduleFormat = "cjs"` in the generator block instead of forcing ESM.
### 2. Update tsconfig.json
```json
{
"compilerOptions": {
"module": "ESNext",
"moduleResolution": "bundler",
"target": "ES2023",
"strict": true,
"esModuleInterop": true
}
}
```
### 3. Update schema.prisma
```prisma
// Before (v6)
generator client {
provider = "prisma-client-js"
}
// After (v7)
generator client {
provider = "prisma-client"
output = "../generated/prisma"
// Optional if you need CommonJS:
// moduleFormat = "cjs"
}
```
### 4. Create prisma.config.ts
```typescript
import 'dotenv/config'
import { defineConfig, env } from 'prisma/config'
export default defineConfig({
schema: 'prisma/schema.prisma',
migrations: {
path: 'prisma/migrations',
},
datasource: {
url: env('DATABASE_URL'),
},
})
```
### 5. Install a driver adapter (SQL providers only)
```bash
# PostgreSQL
npm install @prisma/adapter-pg pg
# MySQL
npm install @prisma/adapter-mariadb mariadb
# SQLite
npm install @prisma/adapter-better-sqlite3 better-sqlite3
# Prisma Postgres in standard Node.js apps (recommended)
npm install @prisma/adapter-pg pg
# Prisma Postgres serverless driver (edge/serverless)
npm install @prisma/adapter-ppg @prisma/ppg
# Neon
npm install @prisma/adapter-neon
```
MongoDB does not have a SQL `@prisma/adapter-*` package in the published Prisma 7.6.0 packages. If you're upgrading a MongoDB project, stop and keep that project on the latest Prisma 6.x release instead of following the standard Prisma 7 migration path.
### 6. Update client instantiation
```typescript
// Before (v6)
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
// After (v7)
import { PrismaClient } from '../generated/prisma/client'
import { PrismaPg } from '@prisma/adapter-pg'
const adapter = new PrismaPg({
connectionString: process.env.DATABASE_URL
})
const prisma = new PrismaClient({ adapter })
```
### 7. Replace Prisma.validator with satisfies
```typescript
import { Prisma } from '../generated/prisma/client'
const userSelect = {
id: true,
email: true,
name: true,
} satisfies Prisma.UserSelect
```
### 8. Run migrations and generate
```bash
npx prisma generate
npx prisma migrate dev # if needed
```
## Troubleshooting
### "Cannot find module" errors
- Check that the generator `output` path matches your import path
- Ensure `prisma generate` ran successfully
### SSL certificate errors
- Add `ssl: { rejectUnauthorized: false }` to the adapter config if you need to preserve old behavior
- Or configure your certificates properly with `NODE_EXTRA_CA_CERTS` / OpenSSL CA settings
### Connection timeout issues
- Driver adapters use the underlying driver's defaults, which differ from v6
- Configure pool settings explicitly on the adapter if needed
## Resources
- [Official v7 Upgrade Guide](https://www.prisma.io/docs/orm/more/upgrades/to-v7)
- [Driver Adapters Documentation](https://www.prisma.io/docs/orm/core-concepts/supported-databases/database-drivers)
- [Prisma Config Reference](https://www.prisma.io/docs/orm/reference/prisma-config-reference)
## How to Use
Follow `references/schema-changes.md` and `references/driver-adapters.md` first, then apply the remaining reference files based on your project setup.
@@ -0,0 +1,151 @@
# Prisma Accelerate Users
Special migration instructions for users of Prisma Accelerate or Prisma Postgres with `prisma://` or `prisma+postgres://` URLs.
## Important
**Do NOT pass Accelerate URLs to driver adapters.**
Driver adapters (like `PrismaPg`) expect direct database connection strings. They will fail with `prisma://` or `prisma+postgres://` URLs.
## Correct v7 Setup for Accelerate
### 1. Keep your Accelerate URL
```env
# .env
DATABASE_URL="prisma://accelerate.prisma-data.net/?api_key=..."
# or
DATABASE_URL="prisma+postgres://accelerate.prisma-data.net/..."
```
### 2. Install Accelerate extension
```bash
npm install @prisma/extension-accelerate
```
### 3. Configure prisma.config.ts
```typescript
import 'dotenv/config'
import { defineConfig, env } from 'prisma/config'
export default defineConfig({
schema: 'prisma/schema.prisma',
datasource: {
url: env('DATABASE_URL'), // Accelerate URL works here
},
})
```
### 4. Instantiate client with accelerateUrl
```typescript
import { PrismaClient } from '../generated/client'
import { withAccelerate } from '@prisma/extension-accelerate'
// Use accelerateUrl instead of adapter
export const prisma = new PrismaClient({
accelerateUrl: process.env.DATABASE_URL,
}).$extends(withAccelerate())
```
## What NOT to Do
```typescript
// ❌ WRONG - Don't use adapter with Accelerate URL
import { PrismaPg } from '@prisma/adapter-pg'
const adapter = new PrismaPg({
connectionString: process.env.DATABASE_URL // This will fail with prisma://
})
```
## Migrations with Accelerate
For migrations, you may need a direct database connection:
### Option 1: Use Accelerate URL for everything
Accelerate URLs work with Prisma CLI commands:
```bash
# Works with Accelerate URL
prisma migrate deploy
prisma db push
```
### Option 2: Use direct URL for migrations
```env
DATABASE_URL="prisma+postgres://..." # For app
DIRECT_DATABASE_URL="postgresql://..." # For migrations
```
```typescript
// prisma.config.ts
export default defineConfig({
datasource: {
url: env('DIRECT_DATABASE_URL'), // Direct URL for CLI
},
})
```
## Prisma Postgres (Cloud)
If using Prisma Postgres cloud database:
### Same approach
```typescript
import { PrismaClient } from '../generated/client'
import { withAccelerate } from '@prisma/extension-accelerate'
export const prisma = new PrismaClient({
accelerateUrl: process.env.DATABASE_URL, // prisma+postgres:// URL
}).$extends(withAccelerate())
```
## Switching Away from Accelerate
If you later switch to direct TCP connection:
```typescript
// Change from accelerateUrl to adapter
import { PrismaClient } from '../generated/client'
import { PrismaPg } from '@prisma/adapter-pg'
const adapter = new PrismaPg({
connectionString: process.env.DATABASE_URL // Direct postgres:// URL
})
export const prisma = new PrismaClient({ adapter })
```
## Caching with Accelerate
The extension enables caching:
```typescript
const users = await prisma.user.findMany({
cacheStrategy: {
ttl: 60, // Cache for 60 seconds
swr: 120, // Stale-while-revalidate for 120 seconds
},
})
```
## Edge Runtime
Accelerate works great in edge runtimes:
```typescript
// Works in Vercel Edge, Cloudflare Workers, etc.
import { PrismaClient } from '../generated/client'
import { withAccelerate } from '@prisma/extension-accelerate'
export const prisma = new PrismaClient({
accelerateUrl: process.env.DATABASE_URL,
}).$extends(withAccelerate())
```
@@ -0,0 +1,267 @@
# Driver Adapters
Prisma v7 requires driver adapters for SQL database connections. This is the standard SQL execution path in current Prisma releases.
MongoDB should not follow this path. There is no published MongoDB `@prisma/adapter-*` package, and MongoDB projects should remain on the latest Prisma 6.x release instead of trying to fit into the Prisma 7 SQL adapter model.
## Why Driver Adapters?
- No native engine binary in the Prisma Client SQL path
- Smaller bundle size
- Better serverless/edge compatibility
- Uses native Node.js database drivers
- More control over connection pooling
## Available Adapters
| Database | Adapter Package | Underlying Driver |
|----------|-----------------|-------------------|
| PostgreSQL | `@prisma/adapter-pg` | `pg` |
| MySQL / MariaDB | `@prisma/adapter-mariadb` | `mariadb` |
| SQLite | `@prisma/adapter-better-sqlite3` | `better-sqlite3` |
| Prisma Postgres (Node.js) | `@prisma/adapter-pg` | `pg` |
| Prisma Postgres (edge/serverless) | `@prisma/adapter-ppg` | `@prisma/ppg` |
| SQL Server | `@prisma/adapter-mssql` | `mssql` |
| Neon | `@prisma/adapter-neon` | `@neondatabase/serverless` |
| PlanetScale | `@prisma/adapter-planetscale` | `@planetscale/database` |
| Turso/libSQL | `@prisma/adapter-libsql` | `@libsql/client` |
| D1 (Cloudflare) | `@prisma/adapter-d1` | Cloudflare D1 |
## Installation
### PostgreSQL
```bash
npm install @prisma/adapter-pg
```
### MySQL
```bash
npm install @prisma/adapter-mariadb mariadb
```
### SQLite
```bash
npm install @prisma/adapter-better-sqlite3
```
### Prisma Postgres
```bash
npm install @prisma/adapter-pg pg
```
### SQL Server
```bash
npm install @prisma/adapter-mssql mssql
```
## Configuration
### PostgreSQL
```typescript
import { PrismaClient } from '../generated/client'
import { PrismaPg } from '@prisma/adapter-pg'
const adapter = new PrismaPg({
connectionString: process.env.DATABASE_URL
})
const prisma = new PrismaClient({ adapter })
```
### MySQL
```typescript
import { PrismaClient } from '../generated/client'
import { PrismaMariaDb } from '@prisma/adapter-mariadb'
const adapter = new PrismaMariaDb({
host: 'localhost',
port: 3306,
connectionLimit: 5,
user: process.env.MYSQL_USER,
password: process.env.MYSQL_PASSWORD,
database: process.env.MYSQL_DATABASE,
})
const prisma = new PrismaClient({ adapter })
```
### SQLite
```typescript
import { PrismaClient } from '../generated/client'
import { PrismaBetterSqlite3 } from '@prisma/adapter-better-sqlite3'
const adapter = new PrismaBetterSqlite3({
url: process.env.DATABASE_URL || 'file:./dev.db'
})
const prisma = new PrismaClient({ adapter })
```
### Neon (Serverless PostgreSQL)
```typescript
import { PrismaClient } from '../generated/client'
import { PrismaNeon } from '@prisma/adapter-neon'
const adapter = new PrismaNeon({
connectionString: process.env.DATABASE_URL
})
const prisma = new PrismaClient({ adapter })
```
### Prisma Postgres
```typescript
import { PrismaClient } from '../generated/client'
import { PrismaPg } from '@prisma/adapter-pg'
const adapter = new PrismaPg({
connectionString: process.env.DATABASE_URL,
})
const prisma = new PrismaClient({ adapter })
```
### Prisma Postgres serverless driver
```typescript
import { PrismaClient } from '../generated/client'
import { PrismaPostgresAdapter } from '@prisma/adapter-ppg'
const prisma = new PrismaClient({
adapter: new PrismaPostgresAdapter({
connectionString: process.env.PRISMA_DIRECT_TCP_URL,
}),
})
```
### SQL Server
```typescript
import { PrismaClient } from '../generated/client'
import { PrismaMssql } from '@prisma/adapter-mssql'
const adapter = new PrismaMssql({
server: 'localhost',
port: 1433,
database: 'mydb',
user: process.env.SQLSERVER_USER,
password: process.env.SQLSERVER_PASSWORD,
options: {
encrypt: true,
trustServerCertificate: true,
},
})
const prisma = new PrismaClient({ adapter })
```
## Connection Pool Configuration
Driver adapters use the underlying driver's pool settings, which differ from v6 defaults.
### PostgreSQL with custom pool
```typescript
import { PrismaPg } from '@prisma/adapter-pg'
const adapter = new PrismaPg({
connectionString: process.env.DATABASE_URL,
// Pool configuration
max: 10, // Maximum connections
idleTimeoutMillis: 30000, // Close idle connections after 30s
connectionTimeoutMillis: 5000, // Connection timeout (v6 default was 5s)
})
```
### Matching v6 behavior
```typescript
const adapter = new PrismaPg({
connectionString: process.env.DATABASE_URL,
connectionTimeoutMillis: 5000, // v6 used 5 second timeout
})
```
## SSL Configuration
### Accept self-signed certificates
```typescript
const adapter = new PrismaPg({
connectionString: process.env.DATABASE_URL,
ssl: {
rejectUnauthorized: false // Accept self-signed certs
}
})
```
### Proper SSL configuration
```typescript
const adapter = new PrismaPg({
connectionString: process.env.DATABASE_URL,
ssl: {
ca: fs.readFileSync('/path/to/ca-cert.pem'),
rejectUnauthorized: true
}
})
```
## Migration from v6
### Before (v6)
```typescript
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient({
datasources: {
db: { url: process.env.DATABASE_URL }
}
})
```
### After (v7)
```typescript
import { PrismaClient } from '../generated/client'
import { PrismaPg } from '@prisma/adapter-pg'
const adapter = new PrismaPg({
connectionString: process.env.DATABASE_URL
})
const prisma = new PrismaClient({ adapter })
```
## Singleton Pattern
```typescript
// lib/prisma.ts
import { PrismaClient } from '../generated/client'
import { PrismaPg } from '@prisma/adapter-pg'
const globalForPrisma = globalThis as unknown as {
prisma: PrismaClient | undefined
}
const adapter = new PrismaPg({
connectionString: process.env.DATABASE_URL!
})
export const prisma = globalForPrisma.prisma ?? new PrismaClient({ adapter })
if (process.env.NODE_ENV !== 'production') {
globalForPrisma.prisma = prisma
}
```
@@ -0,0 +1,161 @@
# Environment Variables
Prisma v7 no longer automatically loads environment variables. You must load them explicitly.
## The Change
### v6 Behavior
Prisma CLI automatically loaded `.env` files.
### v7 Behavior
You must manually load environment variables using `dotenv` or similar.
## Setup
### 1. Install dotenv
```bash
npm install dotenv
```
### 2. Import in prisma.config.ts
```typescript
import 'dotenv/config' // Must be first import
import { defineConfig, env } from 'prisma/config'
export default defineConfig({
datasource: {
url: env('DATABASE_URL'),
},
})
```
## Bun Users
Bun automatically loads `.env` files. No additional setup needed:
```typescript
// prisma.config.ts (Bun)
import { defineConfig, env } from 'prisma/config'
export default defineConfig({
datasource: {
url: env('DATABASE_URL'),
},
})
```
## Multiple .env Files
### Using dotenv-cli
```bash
npm install -D dotenv-cli
```
```json
{
"scripts": {
"db:migrate": "dotenv -e .env.local -- prisma migrate dev",
"db:push": "dotenv -e .env.development -- prisma db push"
}
}
```
### Using dotenv with path
```typescript
// prisma.config.ts
import { config } from 'dotenv'
import path from 'path'
// Load specific .env file
config({ path: path.join(__dirname, '.env.local') })
import { defineConfig, env } from 'prisma/config'
export default defineConfig({
datasource: {
url: env('DATABASE_URL'),
},
})
```
## Application Code
For your application, load env vars at startup:
### Entry point
```typescript
// index.ts
import 'dotenv/config'
import { PrismaClient } from '../generated/client'
import { PrismaPg } from '@prisma/adapter-pg'
const adapter = new PrismaPg({
connectionString: process.env.DATABASE_URL!
})
const prisma = new PrismaClient({ adapter })
```
### Or use dotenv explicitly
```typescript
import { config } from 'dotenv'
config()
// Now process.env.DATABASE_URL is available
```
## Removed Environment Variables
These Prisma-specific env vars are removed in v7:
| Removed Variable | Alternative |
|-----------------|-------------|
| `PRISMA_CLI_QUERY_ENGINE_TYPE` | Not needed (no engines) |
| `PRISMA_CLIENT_ENGINE_TYPE` | Not needed (no engines) |
| `PRISMA_QUERY_ENGINE_BINARY` | Not needed |
| `PRISMA_QUERY_ENGINE_LIBRARY` | Not needed |
| `PRISMA_GENERATE_SKIP_AUTOINSTALL` | Not needed |
| `PRISMA_SKIP_POSTINSTALL_GENERATE` | Not needed |
| `PRISMA_GENERATE_IN_POSTINSTALL` | Not needed |
| `PRISMA_GENERATE_DATAPROXY` | Migrate to `prisma-client` with driver adapters |
| `PRISMA_GENERATE_NO_ENGINE` | Migrate to `prisma-client` with driver adapters |
| `PRISMA_CLIENT_NO_RETRY` | Configure on adapter |
| `PRISMA_MIGRATE_SKIP_GENERATE` | Not needed (auto-generate removed) |
| `PRISMA_MIGRATE_SKIP_SEED` | Not needed (auto-seed removed) |
## TypeScript env() Helper
The `env()` function from `prisma/config` provides type safety:
```typescript
import { env } from 'prisma/config'
// Type-safe environment variable access
const url = env('DATABASE_URL') // string
```
Note: This only works within `prisma.config.ts`, not in your application code.
## CI/CD Considerations
Ensure environment variables are set in your CI environment:
```yaml
# GitHub Actions
env:
DATABASE_URL: ${{ secrets.DATABASE_URL }}
steps:
- run: npx prisma migrate deploy
```
No need for dotenv in CI if variables are set directly.
@@ -0,0 +1,128 @@
# ESM and CommonJS Support
Prisma ORM v7 is ESM-first, but the `prisma-client` generator can target either ESM or CommonJS. Use ESM by default, and opt into CommonJS with `moduleFormat = "cjs"` if your project still needs it.
## ESM Projects
Add `"type": "module"` to `package.json` and use an ESM-compatible `tsconfig.json`:
```json
{
"type": "module",
"scripts": {
"build": "tsc",
"start": "node dist/index.js"
}
}
```
```json
{
"compilerOptions": {
"module": "ESNext",
"moduleResolution": "bundler",
"target": "ES2023",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"outDir": "dist"
},
"include": ["src/**/*", "prisma/**/*"]
}
```
## CommonJS Projects
If the rest of your app is still CommonJS, keep that setup and make the generated Prisma Client CommonJS too:
```json
{
"compilerOptions": {
"module": "CommonJS",
"moduleResolution": "node",
"target": "ES2022",
"esModuleInterop": true
}
}
```
```prisma
generator client {
provider = "prisma-client"
output = "../generated/prisma"
moduleFormat = "cjs"
}
```
## Generator Fields That Matter
- `moduleFormat`: `esm` or `cjs`
- `runtime`: `nodejs`, `bun`, `deno`, `workerd`, `vercel-edge`, `react-native`
- `generatedFileExtension`: `ts`, `mts`, or `cts`
- `importFileExtension`: `ts`, `mts`, `cts`, `js`, `mjs`, `cjs`, or empty
Example:
```prisma
generator client {
provider = "prisma-client"
output = "../generated/prisma"
runtime = "nodejs"
moduleFormat = "esm"
generatedFileExtension = "ts"
importFileExtension = "ts"
}
```
## Import Paths
### Server Code
```typescript
import { PrismaClient } from '../generated/prisma/client'
```
### Browser-Safe Types
```typescript
import { Prisma } from '../generated/prisma/browser'
import { Role } from '../generated/prisma/enums'
import type { UserModel } from '../generated/prisma/models/User'
```
## File Extensions
With `moduleResolution: "Node16"` or `"NodeNext"`, use `.js`/`.mjs`/`.cjs` extensions that match your emitted files.
With `moduleResolution: "bundler"`, bare relative imports are usually fine.
## Minimum Versions
| Requirement | Minimum Version |
|-------------|-----------------|
| Node.js | 20.19.0 |
| TypeScript | 5.4.0 |
## Framework Considerations
### Next.js
Next.js works well with the default ESM output. If you need generated types in client components, import them from `browser`, `models`, or `enums`, not from `client`.
### Bun
Bun loads `.env` files automatically, so ESM plus `env()` is the smoothest default. You can still choose `moduleFormat = "cjs"` if the rest of your project requires it.
## Troubleshooting
### "ERR_REQUIRE_ESM"
Your generated client is ESM, but your app is requiring it as CommonJS. Either switch the project to ESM or set `moduleFormat = "cjs"` and regenerate.
### "Cannot use import statement outside a module"
Your app is still being executed as CommonJS. Add `"type": "module"` or use `moduleFormat = "cjs"` instead.
### TypeScript compilation errors
Ensure `module`, `moduleResolution`, and your generator's `moduleFormat` agree with one another.
@@ -0,0 +1,203 @@
# Prisma Config
Prisma v7 introduces `prisma.config.ts` as the central configuration file for the Prisma CLI.
## Location
Place `prisma.config.ts` at your project root (next to `package.json`).
## Basic Configuration
```typescript
import 'dotenv/config'
import { defineConfig, env } from 'prisma/config'
export default defineConfig({
schema: 'prisma/schema.prisma',
migrations: {
path: 'prisma/migrations',
},
datasource: {
url: env('DATABASE_URL'),
},
})
```
## Configuration Options
### schema
Path to your Prisma schema file:
```typescript
schema: 'prisma/schema.prisma'
```
### datasource.url
Database connection URL:
```typescript
datasource: {
url: env('DATABASE_URL'),
}
```
### datasource.directUrl
Direct connection URL (bypassing connection pooler):
```typescript
datasource: {
url: env('DATABASE_URL'),
directUrl: env('DIRECT_DATABASE_URL'),
}
```
### datasource.shadowDatabaseUrl
Shadow database for migrations:
```typescript
datasource: {
url: env('DATABASE_URL'),
shadowDatabaseUrl: env('SHADOW_DATABASE_URL'),
}
```
### migrations.path
Directory for migration files:
```typescript
migrations: {
path: 'prisma/migrations',
}
```
### migrations.seed
Seed command for `prisma db seed`:
```typescript
migrations: {
path: 'prisma/migrations',
seed: 'tsx prisma/seed.ts',
}
```
## Full Example
```typescript
import 'dotenv/config'
import { defineConfig, env } from 'prisma/config'
export default defineConfig({
// Schema location
schema: 'prisma/schema.prisma',
// Migration configuration
migrations: {
path: 'prisma/migrations',
seed: 'tsx prisma/seed.ts',
},
// Database connection
datasource: {
url: env('DATABASE_URL'),
directUrl: env('DIRECT_DATABASE_URL'),
shadowDatabaseUrl: env('SHADOW_DATABASE_URL'),
},
})
```
## Environment Variables
### The env() helper
Use `env()` to reference environment variables:
```typescript
import { env } from 'prisma/config'
datasource: {
url: env('DATABASE_URL'),
}
```
This provides type safety but does NOT load .env files automatically.
### Loading .env files
Install and import dotenv:
```bash
npm install dotenv
```
```typescript
import 'dotenv/config' // Must be first import
import { defineConfig, env } from 'prisma/config'
```
## Migrating from v6
### Before (v6) - schema.prisma
```prisma
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
directUrl = env("DIRECT_URL")
}
```
### After (v7) - prisma.config.ts
```typescript
import 'dotenv/config'
import { defineConfig, env } from 'prisma/config'
export default defineConfig({
schema: 'prisma/schema.prisma',
datasource: {
url: env('DATABASE_URL'),
directUrl: env('DIRECT_URL'),
},
})
```
And update schema.prisma:
```prisma
datasource db {
provider = "postgresql"
// URLs now in prisma.config.ts
}
```
## Custom Config Path
Use `--config` flag with CLI commands:
```bash
prisma migrate dev --config ./config/prisma.config.ts
```
## Monorepo Configuration
```typescript
import 'dotenv/config'
import { defineConfig, env } from 'prisma/config'
import path from 'path'
export default defineConfig({
schema: path.join(__dirname, 'packages/database/prisma/schema.prisma'),
migrations: {
path: path.join(__dirname, 'packages/database/prisma/migrations'),
},
datasource: {
url: env('DATABASE_URL'),
},
})
```
@@ -0,0 +1,230 @@
# Removed Features
Several features have been removed in Prisma v7. Here's how to migrate.
## Client Middleware
### Removed
```typescript
// ❌ No longer works in v7
prisma.$use(async (params, next) => {
const before = Date.now()
const result = await next(params)
const after = Date.now()
console.log(`Query took ${after - before}ms`)
return result
})
```
### Use Client Extensions Instead
```typescript
// ✅ v7 approach
const prisma = new PrismaClient({ adapter }).$extends({
query: {
$allModels: {
async $allOperations({ operation, model, args, query }) {
const before = Date.now()
const result = await query(args)
const after = Date.now()
console.log(`${model}.${operation} took ${after - before}ms`)
return result
},
},
},
})
```
### Common Middleware Patterns
#### Soft delete
```typescript
const prisma = new PrismaClient({ adapter }).$extends({
query: {
user: {
async delete({ args, query }) {
// Convert delete to soft delete
return prisma.user.update({
where: args.where,
data: { deletedAt: new Date() },
})
},
async findMany({ args, query }) {
// Filter out soft-deleted records
args.where = { ...args.where, deletedAt: null }
return query(args)
},
},
},
})
```
#### Logging
```typescript
const prisma = new PrismaClient({ adapter }).$extends({
query: {
$allModels: {
async $allOperations({ operation, model, args, query }) {
console.log(`${model}.${operation}`, JSON.stringify(args))
return query(args)
},
},
},
})
```
## Metrics
### Removed
The Metrics preview feature has been removed.
```typescript
// ❌ No longer works
const metrics = await prisma.$metrics.json()
```
### Alternatives
#### Custom counter with extensions
```typescript
let totalQueries = 0
const prisma = new PrismaClient({ adapter }).$extends({
client: {
async $totalQueries() {
return totalQueries
},
},
query: {
$allModels: {
async $allOperations({ query, args }) {
totalQueries += 1
return query(args)
},
},
},
})
// Usage
const count = await prisma.$totalQueries()
```
#### Use driver-level metrics
Access metrics from the underlying driver adapter.
## CLI Flags Removed
### --skip-generate
Removed from `migrate dev` and `db push`.
```bash
# v6
prisma migrate dev --skip-generate
# v7 - generate is not run automatically
prisma migrate dev
prisma generate # Run explicitly if needed
```
Local verification with Prisma `7.6.0` showed no generated client files emitted by `migrate dev` or `db push`, even though some CLI help text still says `migrate dev` "trigger[s] generators".
### --skip-seed
Removed from `migrate dev`. More importantly, Prisma v7 no longer auto-runs seeds during `migrate dev` or `migrate reset`, so seed explicitly when you need it.
```bash
# v6
prisma migrate dev --skip-seed
# v7 - seed is not run automatically
prisma migrate dev
prisma db seed # Run explicitly if needed
```
### --schema and --url from db execute
```bash
# v6
prisma db execute --file ./script.sql --url "$DATABASE_URL"
# v7 - configure in prisma.config.ts
prisma db execute --file ./script.sql
```
## migrate diff Options
| Removed | Replacement |
|---------|-------------|
| `--from-url` | `--from-config-datasource` |
| `--to-url` | `--to-config-datasource` |
| `--from-schema-datasource` | `--from-config-datasource` |
| `--to-schema-datasource` | `--to-config-datasource` |
| `--shadow-database-url` | Configure in `prisma.config.ts` |
### Example
```bash
# v6
prisma migrate diff --from-url "$DATABASE_URL" --to-schema schema.prisma
# v7
prisma migrate diff --from-config-datasource --to-schema schema.prisma
```
## Automatic Behaviors Removed
### Auto-generate after migrate
```bash
# v7 workflow
prisma migrate dev --name add_field
prisma generate # Must run explicitly
```
### Auto-seed after migrate
```bash
# v7 workflow
prisma migrate reset --force
prisma db seed # Must run explicitly
```
## Prisma.validator
The `prisma-client` generator no longer exposes `Prisma.validator`. Use TypeScript's `satisfies` operator instead.
```typescript
import { Prisma } from '../generated/prisma/client'
const userSelect = {
id: true,
email: true,
} satisfies Prisma.UserSelect
```
## rejectOnNotFound
Removed in v5.0.0 (already deprecated).
```typescript
// ❌ Removed
const prisma = new PrismaClient({
rejectOnNotFound: true,
})
// ✅ Use OrThrow methods
const user = await prisma.user.findUniqueOrThrow({
where: { id: 1 },
})
const user = await prisma.user.findFirstOrThrow({
where: { email: 'test@example.com' },
})
```
@@ -0,0 +1,164 @@
# Schema Changes
Prisma v7 promotes `prisma-client` to the default generator. Update your generator block, output path, and imports accordingly.
This guide is for projects that are actually migrating to Prisma 7. Do not apply these schema changes to MongoDB projects; keep those on Prisma 6.x.
## Generator Block (v7)
```prisma
generator client {
provider = "prisma-client"
output = "../generated/prisma"
}
```
## Key Changes
### 1. Provider name
Use `prisma-client` in Prisma v7. The older `prisma-client-js` generator still exists in the repo for legacy setups, but `prisma-client` is the default path for current projects.
### 2. Output is required
The `output` field is mandatory when using `prisma-client`. Prisma Client no longer generates to `node_modules` with this generator.
```prisma
generator client {
provider = "prisma-client"
output = "../generated/prisma"
}
```
### 3. engineType changed
Legacy Rust engine settings are gone. With `prisma-client`, the relevant value is `engineType = "client"` if you want to state it explicitly, although it is typically inferred and can be omitted.
```prisma
generator client {
provider = "prisma-client"
output = "../generated/prisma"
engineType = "client"
}
```
### 4. moduleFormat is explicit when needed
If you must stay on CommonJS:
```prisma
generator client {
provider = "prisma-client"
output = "../generated/prisma"
moduleFormat = "cjs"
}
```
## Example Output Paths
### Standard project
```prisma
output = "../generated/prisma"
```
Creates files like:
```text
generated/prisma/
client.ts
browser.ts
enums.ts
models.ts
models/
```
### Monorepo
```prisma
output = "../../packages/database/generated/prisma"
```
### Same directory as schema
```prisma
output = "./generated/prisma"
```
Creates: `prisma/generated/prisma/client.ts`
## Datasource Block
The `url`, `directUrl`, and `shadowDatabaseUrl` fields in the `datasource` block are deprecated in Prisma v7. Move them to `prisma.config.ts` and keep only the provider in `schema.prisma`:
```prisma
datasource db {
provider = "postgresql"
}
```
```typescript
export default defineConfig({
datasource: {
url: env('DATABASE_URL'),
directUrl: env('DIRECT_URL'),
shadowDatabaseUrl: env('SHADOW_DATABASE_URL'),
},
})
```
## After Schema Changes
1. Run `prisma generate`:
```bash
npx prisma generate
```
2. Update imports throughout your codebase:
```typescript
import { PrismaClient } from '../generated/prisma/client'
```
3. Update `.gitignore` if you manage this manually:
```
/generated/prisma
```
4. Replace `Prisma.validator()` with TypeScript `satisfies` when using `prisma-client`:
```typescript
import { Prisma } from '../generated/prisma/client'
const userSelect = {
id: true,
email: true,
} satisfies Prisma.UserSelect
```
## Generated Entrypoints
- `client` - server-side Prisma Client and Prisma namespace
- `browser` - browser-safe types and enums without a real `PrismaClient`
- `enums` - slim enum-only entrypoint
- `models` - model types and derived helper types
## Preview Features
Preview features still work as before:
```prisma
generator client {
provider = "prisma-client"
output = "../generated/prisma"
previewFeatures = ["relationJoins", "fullTextSearch"]
}
```
Recent preview-feature examples also include `partialIndexes` for PostgreSQL, SQLite, SQL Server, and CockroachDB:
```prisma
generator client {
provider = "prisma-client"
output = "../generated/prisma"
previewFeatures = ["partialIndexes"]
}
```
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/prisma-cli
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/prisma-client-api
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/prisma-compute
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/prisma-database-setup
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/prisma-driver-adapter-implementation
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/prisma-mongodb-upgrade
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/prisma-postgres
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/prisma-postgres-setup
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/prisma-upgrade-v7
+29 -19
View File
@@ -11,47 +11,57 @@ jobs:
container:
image: docker:latest
steps:
- name: Code auschecken
- name: Checkout code
run: |
apk add --no-cache curl unzip
curl -L -H "Authorization: token ${{ secrets.GITEA_TOKEN }}" \
"http://172.17.0.1:3000/api/v1/repos/${{ github.repository }}/archive/main.zip" -o repo.zip
unzip repo.zip
# Verschiebt alle Dateien aus dem Zip-Unterordner direkt hierher ins Hauptverzeichnis
mv PsalmTafel/* . 2>/dev/null || mv psalmtafel/* . 2>/dev/null || mv */* . 2>/dev/null
rm repo.zip
- name: Docker Container aktualisieren
- name: Update Docker container
run: |
# Kein 'cd' mehr! Wir sind schon im richtigen Ordner, wo dein Dockerfile liegt.
echo "Baue das neue Next.js Docker-Image..."
echo "Building new Next.js Docker image..."
docker build -t psalmtafel-app .
echo "Stoppe alten Container, falls er läuft..."
echo "Stopping old container if running..."
docker stop psalmtafel-container || true
docker rm psalmtafel-container || true
echo "Starte neuen Container..."
echo "Starting new container..."
docker run -d \
--name psalmtafel-container \
-p 8443:3000 \
--restart always \
psalmtafel-app
- name: Release in Gitea erstellen
run: |
# 1. jq installieren und Version aus package.json auslesen
apk add --no-cache jq
VERSION=$(jq -r '.version' package.json)
echo "Aktuelle Version: v$VERSION"
# 2. Prüfen, ob das Release/Tag bereits existiert
- name: Create release in Gitea
run: |
apk add --no-cache jq curl
VERSION=$(jq -r '.version' package.json)
echo "Current version: v$VERSION"
# Shell-kompatible Prüfung (funktioniert zuverlässig in Alpine/sh)
case "$VERSION" in
0.*)
IS_PRERELEASE="true"
echo "Version starts with 0. Setting prerelease to true."
;;
*)
IS_PRERELEASE="false"
echo "Setting prerelease to false."
;;
esac
# Prüfen, ob das Release bereits existiert
HTTP_STATUS=$(curl -s -o /dev/null -w "%{http_code}" \
-H "Authorization: token ${{ secrets.GITEA_TOKEN }}" \
"http://172.17.0.1:3000/api/v1/repos/${{ github.repository }}/releases/tags/v$VERSION")
# 3. Wenn Release noch nicht existiert (404), erstelle es
if [ "$HTTP_STATUS" -eq 404 ]; then
echo "Erstelle neues Release v$VERSION..."
echo "Creating new release v$VERSION..."
# Gitea erstellt bei diesem Call automatisch auch den Tag v$VERSION auf 'main'
curl -X POST \
-H "Authorization: token ${{ secrets.GITEA_TOKEN }}" \
-H "Content-Type: application/json" \
@@ -59,11 +69,11 @@ jobs:
\"tag_name\": \"v$VERSION\",
\"target_commitish\": \"main\",
\"name\": \"Release v$VERSION\",
\"body\": \"Automatisches Release für Version v$VERSION\",
\"body\": \"Automated release for version v$VERSION\",
\"draft\": false,
\"prerelease\": false
\"prerelease\": $IS_PRERELEASE
}" \
"http://172.17.0.1:3000/api/v1/repos/${{ github.repository }}/releases"
else
echo "Release v$VERSION existiert bereits. Überspringe Erstellung."
echo "Release v$VERSION already exists. Skipping creation."
fi
+3 -1
View File
@@ -42,5 +42,7 @@ next-env.d.ts
# database
songs.db
songs.sqlite
.gitignore
.gitignore
/lib/generated/prisma
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/prisma-cli
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/prisma-client-api
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/prisma-compute
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/prisma-database-setup
@@ -0,0 +1 @@
../../.agents/skills/prisma-driver-adapter-implementation
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/prisma-mongodb-upgrade
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/prisma-postgres
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/prisma-postgres-setup
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/prisma-upgrade-v7
+234
View File
@@ -0,0 +1,234 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright © 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for software and other kinds of works.
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.
Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and modification follow.
TERMS AND CONDITIONS
0. Definitions.
“This License” refers to version 3 of the GNU General Public License.
“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
“The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations.
To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work.
A “covered work” means either the unmodified Program or a work based on the Program.
To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
1. Source Code.
The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work.
A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
The Corresponding Source for a work in source code form is that same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”.
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
“Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
7. Additional Terms.
“Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
11. Patents.
A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”.
A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.
If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found.
robin.schamagusa.de
Copyright (C) 2026 Robin Schanbacher
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode:
robin.schamagusa.de
Copyright (C) 2026 Robin Schanbacher
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an “about box”.
You should also get your employer (if you work as a programmer) or school, if any, to sign a “copyright disclaimer” for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see <https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <https://www.gnu.org/philosophy/why-not-lgpl.html>.
Binary file not shown.
+46 -9
View File
@@ -1,16 +1,53 @@
# PsalmTafel
von Robin (und Rudi) Schanbacher
Developed by Robin (and Rudi) Schanbacher
> [!WARNING]
> Dieses Projekt befindet sich noch in der aktiven Entwicklungsphase. Bitte verwende es noch nicht für den produktiven Einsatz.
> This project is currently in active development. Please do not use it in production environments yet.
## Funktion
Dieses Projekt wurde entwickelt, um einem Chor die aktuelle Liednummer und das dazugehörige Liederbuch anzuzeigen. Die Chorleitung wählt ein Lied über die (kommende) App aus. Ein Tablet oder ein anderes browserfähiges Gerät kann dann verwendet werden, um den Sängern die Liednummer, das Liederbuch und den Titel anzuzeigen.
---
## Features
* **Echtzeit-Synchronisation:** Sobald die Chorleitung das Lied wechselt, aktualisiert sich die Anzeige innerhalb 5 Sekunden.
* **Flexibles Design (Responsive):** Funktioniert auf Tablets, Smartphones, Smart-TVs oder alten Laptops.
* **Unterstützung für mehrere Liederbücher:** Parallele Verwaltung verschiedener Gesangbücher möglich.
## Overview
### Purpose
PsalmTafel is a real-time display system designed for choirs. It enables the choir director to select and switch songs seamlessly via a web application or app. A tablet, TV, or any browser-capable device then displays the active song number, songbook, and title to the choir members.
### Key Features
* **Real-time Synchronization:** The display automatically updates within 5 seconds whenever a song is changed.
* **Fully Responsive:** Optimised for tablets, smartphones, desktop browsers, and Smart TVs.
* **Multi-Songbook Support:** Easily manage and switch between multiple songbooks concurrently.
* **Dark & Light Mode Support:** Modern, clean UI built for clear readability in any lighting condition.
---
## Installation & Setup
![Wiki](https://git.schamagusa.de/Schanbro/PsalmTafel/wiki/Installation)
For detailed installation guides and deployment instructions, please visit our Wiki:
* [PsalmTafel Wiki – Installation Guide](https://psalmtafel.gem.schamagusa.de/wiki/installation)
---
## Contributing
We welcome contributions of all kinds! Please take a moment to review the guidelines below before getting started.
> [!IMPORTANT]
> **Language Policy:** While the user interface (UI) is primarily in German, **all code, comments, variables, documentation, and issue descriptions must be written in English** to keep the project accessible to international contributors.
### How to Contribute
1. **Reporting Issues:**
* Before creating a new issue, please check existing issues to avoid duplicates.
* Use clear titles and provide detailed descriptions (including steps to reproduce bugs).
2. **Submitting Pull Requests (PRs):**
* Fork or branch off the main repository (e.g., `feat/my-new-feature` or `fix/issue-description`).
* Keep your commits clean using Conventional Commits (e.g., `feat:`, `fix:`, `style:`, `refactor:`).
* Open a **Draft Pull Request** early if you want feedback on work-in-progress code.
---
## License
This project is licensed under the GPL-3.0 License.
+187 -9
View File
@@ -1,10 +1,11 @@
"use client";
import { uploadCSVAction } from "./actions";
import { useEffect, useState } from "react";
import { JSXElementConstructor, Key, ReactElement, ReactNode, ReactPortal, useEffect, useState } from "react";
import Card from "@/components/Card"
import { Input } from "@/components/FormElements";
import { Screens } from "@/components/DatabaseOverview";
interface Songbook {
id: number;
@@ -12,6 +13,20 @@ interface Songbook {
language: string;
}
interface Song {
song_id: number;
songbook_id: number;
song_number: string;
title: string;
}
interface SongInfo {
songbook_id: number;
songbook_name: string;
song_number: string;
title: string;
}
export default function AdminPage() {
const [songbooks, setSongbooks] = useState<Songbook[]>([]);
const [selectedSongbookId, setSelectedSongbookId] = useState("");
@@ -24,6 +39,9 @@ export default function AdminPage() {
const [uploadStatus, setUploadStatus] = useState<string | null>(null);
const [selectedSong, setSelectedSong] = useState<Song | null>(null);
const [songInfos, setSongInfos] = useState<SongInfo[]>([])
async function handleCSVUpload(formData: FormData) {
setUploadStatus("Verarbeite...");
const result = await uploadCSVAction(formData);
@@ -35,6 +53,27 @@ export default function AdminPage() {
}
}
useEffect(() => {
if (!selectedSong) {
setSongInfos([]);
return;
}
async function fetchSongInfos() {
try {
const res = await fetch(`/api/songs/${selectedSong?.song_id}`);
if (res.ok) {
const data = await res.json();
setSongInfos(data);
}
} catch (error) {
console.error("Fehler beim Laden der Songinfos:", error);
}
}
fetchSongInfos();
}, [selectedSong]);
useEffect(() => {
async function loadSongbooks() {
try {
@@ -78,6 +117,57 @@ export default function AdminPage() {
}
};
const attachSong = async () => {
if (!selectedSongbookId || !number || !selectedSong) {
alert("Alle Felder ausfüllen!");
return;
}
try {
const res = await fetch("/api/songs/attach", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
songbookId: selectedSongbookId,
songId: selectedSong.song_id,
number: number,
})
});
if (res.ok) {
alert("Lied erfolgreich zum Liederbuch hinzugefügt!");
} else {
alert("Fehler beim Senden.");
}
} catch (error) {
console.error("Failed sending current songID:", error);
}
}
const removeSong = async () => {
if (!selectedSongbookId || !selectedSong) {
alert("Alle Felder ausfüllen!");
return;
}
try {
const res = await fetch("/api/songs/remove", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
songbookId: selectedSongbookId,
songId: selectedSong.song_id
})
});
if (res.ok) {
alert("Lied erfolgreich aus dem Liederbuch gelöscht!");
} else {
alert("Fehler beim Senden.");
}
} catch (error) {
console.error("Failed sending current songID:", error);
}
}
const addSongbook = async () => {
if (!newBookName) {
alert("Der Name des Liederbuches darf nicht leer sein!");
@@ -121,7 +211,7 @@ export default function AdminPage() {
<Card title="Neues Liederbuch">
<div className="space-y-4">
<div>
<label className="block text-xs font-semibold text-neutral-400 uppercase tracking-wider mb-1.5">Name des Buchs</label>
<Input.Label>Name des Buchs</Input.Label>
<Input.Text
type="text"
placeholder="z.B. Gesangbuch"
@@ -130,7 +220,7 @@ export default function AdminPage() {
/>
</div>
<div>
<label className="block text-xs font-semibold text-neutral-400 uppercase tracking-wider mb-1.5">Sprache (Optional)</label>
<Input.Label>Sprache (Optional)</Input.Label>
<Input.Text
type="text"
placeholder="z.B. Deutsch"
@@ -150,7 +240,7 @@ export default function AdminPage() {
<Card title="Lied hinzufügen">
<div className="space-y-4">
<div>
<label className="block text-xs font-semibold text-neutral-400 uppercase tracking-wider mb-1.5">Liederbuch wählen</label>
<Input.Label>Liederbuch wählen</Input.Label>
<Input.Select
value={selectedSongbookId}
onChange={(e) => setSelectedSongbookId(e.target.value)}
@@ -165,7 +255,7 @@ export default function AdminPage() {
</div>
<div className="grid grid-cols-3 gap-2">
<div className="col-span-1">
<label className="block text-xs font-semibold text-neutral-400 uppercase tracking-wider mb-1.5">Nummer</label>
<Input.Label>Nummer</Input.Label>
<Input.Text
type="text"
placeholder="12a"
@@ -174,7 +264,7 @@ export default function AdminPage() {
/>
</div>
<div className="col-span-2">
<label className="block text-xs font-semibold text-neutral-400 uppercase tracking-wider mb-1.5">Liedtitel</label>
<Input.Label>Titel</Input.Label>
<Input.Text
type="text"
placeholder="Großer Gott, wir..."
@@ -188,11 +278,11 @@ export default function AdminPage() {
</Card>
<Card title="CSV-Massenimport">
<form action={handleCSVUpload} className="h-full flex flex-col justify-between">
<form action={handleCSVUpload} className="flex flex-col justify-between">
<input type="hidden" name="songbookId" value={selectedSongbookId} />
<div className="space-y-4">
<div>
<label className="block text-xs font-semibold text-neutral-400 uppercase tracking-wider mb-1.5">Ziel-Liederbuch</label>
<Input.Label>Ziel-Liederbuch</Input.Label>
<Input.Select
value={selectedSongbookId}
onChange={(e) => setSelectedSongbookId(e.target.value)}
@@ -206,7 +296,7 @@ export default function AdminPage() {
</Input.Select>
</div>
<div>
<label className="block text-xs font-semibold text-neutral-400 uppercase tracking-wider mb-1.5">Datei auswählen (.csv)</label>
<Input.Label>Datei auswählen (.csv)</Input.Label>
<Input.File
name="csvFile"
accept=".csv"
@@ -229,6 +319,94 @@ export default function AdminPage() {
</form>
</Card>
</div>
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
<Screens.Songs
actionName="Auswählen"
onSelectSong={(song) => setSelectedSong(song)}
className=""
/>
<Card title="Ausgewähltes Lied">
<Input.Text value={selectedSong ? selectedSong.title : ""} disabled></Input.Text>
<Card title="Informationen" className="mt-4">
<div className="text-sm space-y-1">
<p><span className="font-semibold">Lied-ID:</span> {selectedSong?.song_id ?? "-"}</p>
<p><span className="font-semibold">In Liederbüchern:</span></p>
{songInfos.length > 0 ? (
<ul className="list-disc list-inside pl-2 text-xs text-neutral-400">
{songInfos.map((info) => (
<li key={info.songbook_id}>
{info.songbook_name} (Nr. {info.song_number})
</li>
))}
</ul>
) : (
<p className="text-xs text-neutral-500">Keine Daten geladen</p>
)}
</div>
</Card>
<Card title="Aktionen">
<Card title="Zu Liederbuch hinzufügen">
<div className="space-y-4">
<div>
<Input.Label>Ziel-Liederbuch</Input.Label>
<Input.Select
value={selectedSongbookId}
onChange={(e) => setSelectedSongbookId(e.target.value)}
>
<option value="">-- Bitte wählen --</option>
{songbooks.map((book) => (
<option key={book.id} value={String(book.id)}>
{book.name}{book.language ? ` (${book.language})` : ""}
</option>
))}
</Input.Select>
</div>
<div>
<Input.Label>Nummer</Input.Label>
<Input.Text
type="text"
placeholder="12a"
value={number}
onChange={(e) => setNumber(e.target.value)}
/>
</div>
<Input.Button
onClick={attachSong}
className="w-full mt-6 bg-blue-600 hover:bg-blue-700 text-white font-semibold rounded-lg px-4 py-2.5 transition text-sm shadow-sm"
>
Lied hinzufügen
</Input.Button>
</div>
</Card>
<Card title="Aus Liederbuch löschen">
<div className="space-y-4">
<div>
<Input.Label>Ziel-Liederbuch</Input.Label>
<Input.Select
value={selectedSongbookId}
onChange={(e) => setSelectedSongbookId(e.target.value)}
>
<option value="">-- Bitte wählen --</option>
{songInfos.length > 0 ? (
songInfos.map((info) => (
<option key={info.songbook_id} value={String(info.songbook_id)}>
{info.songbook_name} (Nr. {info.song_number})
</option>
))
): ""}
</Input.Select>
</div>
<Input.Button
onClick={removeSong}
className="w-full mt-6 bg-blue-600 hover:bg-blue-700 text-white font-semibold rounded-lg px-4 py-2.5 transition text-sm shadow-sm"
>
Lied aus Liederbuch löschen
</Input.Button>
</div>
</Card>
</Card>
</Card>
</div>
</div>
</div>
);
+151
View File
@@ -0,0 +1,151 @@
import { NextResponse } from "next/server";
import { getSongBookById, updateSongBook, deleteSongBook } from "@/lib/db/songbook";
interface RouteParams {
params: Promise<{
songBookId: string;
}>;
};
/**
* @openapi
* /api/songbooks/{id}:
* get:
* summary: Einzelnen Songbook abrufen
* tags:
* - Songbooks
* parameters:
* - in: path
* name: id
* required: true
* schema:
* type: integer
* description: Die ID des Songbooks
* responses:
* 200:
* description: Songbook erfolgreich gefunden
* 400:
* description: Ungültige Songbook-ID
* 404:
* description: Songbook nicht gefunden
* 500:
* description: Serverfehler
*/
export async function GET(_request: Request, { params }: RouteParams) {
try {
const { songBookId } = await params;
const res = await getSongBookById(parseInt(songBookId));
if (!res.success) {
return NextResponse.json({ message: res.error }, { status: res.status });
}
return NextResponse.json(res.songBook, { status: res.status });
} catch (error) {
console.error("API Error:", error);
return NextResponse.json(
{ error: "Fehler beim Laden der Songbookinfos" },
{ status: 500 }
);
}
}
/**
* @openapi
* /api/songbooks/{id}:
* patch:
* summary: Songbook aktualisieren
* tags:
* - Songbooks
* parameters:
* - in: path
* name: id
* required: true
* schema:
* type: integer
* description: Die ID des Songbooks
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* responses:
* 200:
* description: Songbook erfolgreich aktualisiert
* 400:
* description: Ungültige Parameter oder Daten
* 404:
* description: Songbook nicht gefunden
* 500:
* description: Serverfehler
*/
export async function PATCH(request: Request, { params }: RouteParams) {
try {
const { songBookId } = await params;
const data = await request.json();
const res = await updateSongBook(parseInt(songBookId), data);
if (!res.success) {
return NextResponse.json({ message: res.error }, { status: res.status });
}
return NextResponse.json(res.songBook, { status: res.status });
} catch (error) {
console.error("API Error:", error);
return NextResponse.json(
{ error: "Fehler beim Laden der Songbookinfos" },
{ status: 500 }
);
}
}
/**
* @openapi
* /api/songbooks/{id}:
* delete:
* summary: Songbook löschen
* tags:
* - Songbooks
* parameters:
* - in: path
* name: id
* required: true
* schema:
* type: integer
* description: Die ID des Songbooks
* responses:
* 200:
* description: Songbook erfolgreich gelöscht
* 400:
* description: Ungültige Songbook-ID
* 404:
* description: Songbook nicht gefunden
* 500:
* description: Serverfehler
*/
export async function DELETE(_request: Request, { params }: RouteParams) {
try {
const { songBookId } = await params;
const res = await deleteSongBook(parseInt(songBookId));
if (!res.success) {
return NextResponse.json({ message: res.error }, { status: res.status });
}
return NextResponse.json(res.songBook, { status: res.status });
} catch (error) {
console.error("API Error:", error);
return NextResponse.json(
{ error: "Fehler beim Laden der Songbookinfos" },
{ status: 500 }
);
}
}
@@ -0,0 +1,192 @@
import { NextResponse } from "next/server";
import { addSongToBook, updateSongInBook, removeSongFromBook } from "@/lib/db/songbooksongs";
interface RouteParams {
params: Promise<{
songBookId: string;
songId: string;
}>;
};
/**
* @openapi
* /api/songbooks/{songBookId}/songs/{songId}:
* post:
* summary: Song zu Liederbuch hinzufügen
* tags:
* - Songbook
* parameters:
* - in: path
* name: songBookId
* required: true
* schema:
* type: integer
* description: Die ID des Liederbuchs
* - in: path
* name: songId
* required: true
* schema:
* type: integer
* description: Die ID des Songs
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* required:
* - number
* properties:
* number:
* type: string
* example: "104a"
* description: Die Songnummer im Liederbuch
* responses:
* 200:
* description: Song erfolgreich zugewiesen
* 400:
* description: Ungültige Parameter oder fehlende Songnummer
* 409:
* description: Songnummer bereits vergeben oder Song existiert bereits im Buch
* 500:
* description: Serverfehler
*/
export async function POST(request: Request, { params }: RouteParams) {
try {
const { songBookId, songId } = await params;
const data = await request.json();
const res = await addSongToBook(parseInt(songId), parseInt(songBookId), String(data.number));
if (!res.success) {
return NextResponse.json({ message: res.error }, { status: res.status });
}
return NextResponse.json(res.entry, { status: res.status });
} catch (error) {
console.error("API Error:", error);
return NextResponse.json(
{ error: "Fehler beim Laden der Songbookinfos" },
{ status: 500 }
);
}
}
/**
* @openapi
* /api/songbooks/{songBookId}/songs/{songId}:
* patch:
* summary: Songnummer eines Songs im Liederbuch aktualisieren
* tags:
* - Songbook
* parameters:
* - in: path
* name: songBookId
* required: true
* schema:
* type: integer
* description: Die ID des Liederbuchs
* - in: path
* name: songId
* required: true
* schema:
* type: integer
* description: Die ID des Songs
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* required:
* - number
* properties:
* number:
* type: string
* example: "105"
* description: Die neue Songnummer im Liederbuch
* responses:
* 200:
* description: Songnummer erfolgreich aktualisiert
* 400:
* description: Ungültige Parameter oder fehlende Daten
* 404:
* description: Zuweisung nicht gefunden
* 409:
* description: Neue Songnummer bereits vergeben
* 500:
* description: Serverfehler
*/
export async function PATCH(request: Request, { params }: RouteParams) {
try {
const { songBookId, songId } = await params;
const data = await request.json();
const res = await updateSongInBook(parseInt(songId), parseInt(songBookId), data);
if (!res.success) {
return NextResponse.json({ message: res.error }, { status: res.status });
}
return NextResponse.json(res.entry, { status: res.status });
} catch (error) {
console.error("API Error:", error);
return NextResponse.json(
{ error: "Fehler beim Laden der Songbookinfos" },
{ status: 500 }
);
}
}
/**
* @openapi
* /api/songbooks/{songBookId}/songs/{songId}:
* delete:
* summary: Song aus Liederbuch entfernen
* tags:
* - Songbook
* parameters:
* - in: path
* name: songBookId
* required: true
* schema:
* type: integer
* description: Die ID des Liederbuchs
* - in: path
* name: songId
* required: true
* schema:
* type: integer
* description: Die ID des Songs
* responses:
* 200:
* description: Song erfolgreich aus dem Liederbuch entfernt
* 400:
* description: Ungültige Parameter
* 404:
* description: Zuweisung nicht gefunden
* 500:
* description: Serverfehler
*/
export async function DELETE(_request: Request, { params }: RouteParams) {
try {
const { songBookId, songId } = await params;
const res = await removeSongFromBook(parseInt(songId), parseInt(songBookId));
if (!res.success) {
return NextResponse.json({ message: res.error }, { status: res.status });
}
return NextResponse.json(res.entry, { status: res.status });
} catch (error) {
console.error("API Error:", error);
return NextResponse.json(
{ error: "Fehler beim Laden der Songbookinfos" },
{ status: 500 }
);
}
}
@@ -0,0 +1,58 @@
import { NextResponse } from "next/server";
import { getSongByNumber } from "@/lib/db/songbooksongs";
interface RouteParams {
params: Promise<{
songBookId: string;
}>;
};
/**
* @openapi
* /api/songbooks/{id}/songs:
* get:
* summary: Einen Song nach Nummer in einem Songbook suchen
* tags:
* - Songbook
* parameters:
* - in: path
* name: id
* required: true
* schema:
* type: integer
* description: Die ID des Songbooks
* responses:
* 200:
* description: Songbook erfolgreich gefunden
* 400:
* description: Ungültige Songbook-ID
* 404:
* description: Songbook nicht gefunden
* 500:
* description: Serverfehler
*/
export async function GET(request: Request, { params }: RouteParams) {
try {
const { songBookId } = await params;
const { searchParams } = new URL(request.url);
const number = searchParams.get("number") || searchParams.get("n");
if(number){
const res = await getSongByNumber(parseInt(songBookId), number);
if (!res.success) {
return NextResponse.json({ message: res.error }, { status: res.status });
}
return NextResponse.json(res.entry, { status: res.status });
}
return NextResponse.json({ message: "Need a number query (number=123)" }, { status: 400 });
} catch (error) {
console.error("API Error:", error);
return NextResponse.json(
{ error: "Fehler beim Laden der Songbookinfos" },
{ status: 500 }
);
}
}
+129 -17
View File
@@ -1,27 +1,139 @@
// @wikiCategory: Liederbücher
import { NextResponse } from "next/server";
import { getSongbooks, addSongbook } from "@/lib/db/managing";
import { getSongBooks, searchSongBooksByTitle, createSongBook } from "@/lib/db/songbook";
export async function GET() {
/**
* @openapi
* /api/songbooks:
* get:
* summary: Get all songbooks
* responses:
* 200:
* description: List of songbooks
* 500:
* description: Internal Server Error
*
* @wikiDescription: Liste aller Liederbücher abrufen
*/
export async function GET(request: Request) {
try {
const songbooks = await getSongbooks();
return NextResponse.json(songbooks);
} catch (error) {
return NextResponse.json({ success: false, message: error}, { status: 500})
}
}
export async function POST(request: Request) {
try {
const { name, language } = await request.json();
const { searchParams } = new URL(request.url);
const query = searchParams.get("query") || searchParams.get("q");
if (!name ) {
return NextResponse.json({ success: false, message: "Fields incomplete (name)"}, { status: 400 })
// Wenn ein Suchbegriff übergeben wurde -> Sucheinbindung
if (query) {
const res = await searchSongBooksByTitle(query); // You can enter a limit
if (!res.success) {
return NextResponse.json({ message: res.error }, { status: res.status });
}
return NextResponse.json(res.songBooks, { status: res.status });
}
const newBook = await addSongbook(String(name), String(language))
// Ansonsten alle Bücher abrufen
const res = await getSongBooks();
if (!res.success) {
return NextResponse.json({ message: res.error }, { status: res.status });
}
return NextResponse.json(res.songBooks, { status: res.status });
return NextResponse.json(newBook, { status: 201 })
} catch (error) {
return NextResponse.json({ success: false }, { status: 500 })
console.error("GET /api/songbooks error:", error);
return NextResponse.json(
{ message: "Internal Server Error" },
{ status: 500 }
);
}
}
}
/**
* @openapi
* /api/songbooks:
* post:
* summary: Creates a new songbook
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* required:
* - title
* properties:
* title:
* type: string
* example: "Feiert Jesus 1"
* language:
* type: string
* example: "DE"
* responses:
* 201:
* description: Songbook successfully created
* content:
* application/json:
* schema:
* type: object
* properties:
* success:
* type: boolean
* example: true
* songBook:
* type: object
* properties:
* id:
* type: integer
* example: 1
* title:
* type: string
* example: "Feiert Jesus 1"
* language:
* type: string
* example: "DE"
* 400:
* description: Bad Request (missing title)
* 409:
* description: Conflict (title already exists)
* 500:
* description: Internal Server Error
*
* @wikiDescription: Neues Liederbuch erstellen
*/
export async function POST(request: Request) {
try {
const data = await request.json();
if (!data.title || !data.language) {
return NextResponse.json(
{ message: "Field 'title' and 'language' are required" },
{ status: 400 }
);
}
const res = await createSongBook(data);
if (!res.success) {
return NextResponse.json(
{ message: res.error },
{ status: res.status }
);
}
return NextResponse.json(res, { status: res.status });
} catch (error) {
console.error("POST /api/songbooks error:", error);
return NextResponse.json(
{ message: "Internal Server Error" },
{ status: 500 }
);
}
}
+146
View File
@@ -0,0 +1,146 @@
import { NextResponse } from "next/server";
import { getSongById, updateSong, deleteSong } from "@/lib/db/song";
interface RouteParams {
params: Promise<{
songId: string;
}>;
};
/**
* @openapi
* /api/songs/{id}:
* get:
* summary: Einzelnen Song abrufen
* tags:
* - Songs
* parameters:
* - in: path
* name: id
* required: true
* schema:
* type: integer
* description: Die ID des Songs
* responses:
* 200:
* description: Song erfolgreich gefunden
* 400:
* description: Ungültige Song-ID
* 404:
* description: Song nicht gefunden
* 500:
* description: Serverfehler
*/
export async function GET(_request: Request, { params }: RouteParams) {
try {
const { songId } = await params;
const res = await getSongById(parseInt(songId));
if (!res.success) {
return NextResponse.json({ message: res.error }, { status: res.status });
}
return NextResponse.json(res.song, { status: res.status });
} catch (error) {
console.error("API Error:", error);
return NextResponse.json(
{ error: "Fehler beim Laden der Songinfos" },
{ status: 500 }
);
}
}
/**
* @openapi
* /api/songs/{id}:
* patch:
* summary: Song aktualisieren
* tags:
* - Songs
* parameters:
* - in: path
* name: id
* required: true
* schema:
* type: integer
* description: Die ID des Songs
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* responses:
* 200:
* description: Song erfolgreich aktualisiert
* 400:
* description: Ungültige Parameter oder Daten
* 404:
* description: Song nicht gefunden
* 500:
* description: Serverfehler
*/
export async function PATCH(request: Request, { params }: RouteParams) {
try {
const { songId } = await params;
const data = await request.json();
const res = await updateSong(parseInt(songId), data);
if (!res.success) {
return NextResponse.json({ message: res.error }, { status: res.status });
}
return NextResponse.json(res.song, { status: res.status });
} catch (error) {
console.error("API Error:", error);
return NextResponse.json(
{ error: "Fehler beim Laden der Songinfos" },
{ status: 500 }
);
}
}
/**
* @openapi
* /api/songs/{id}:
* delete:
* summary: Song löschen
* tags:
* - Songs
* parameters:
* - in: path
* name: id
* required: true
* schema:
* type: integer
* description: Die ID des Songs
* responses:
* 200:
* description: Song erfolgreich gelöscht
* 400:
* description: Ungültige Song-ID
* 404:
* description: Song nicht gefunden
* 500:
* description: Serverfehler
*/
export async function DELETE(_request: Request, { params }: RouteParams) {
try {
const { songId } = await params;
const res = await deleteSong(parseInt(songId));
if (!res.success) {
return NextResponse.json({ message: res.error }, { status: res.status });
}
return NextResponse.json(res.song, { status: res.status });
} catch (error) {
console.error("API Error:", error);
return NextResponse.json(
{ error: "Fehler beim Laden der Songinfos" },
{ status: 500 }
);
}
}
+116 -20
View File
@@ -1,31 +1,127 @@
// @wikiCategory: Lieder
import { NextResponse } from "next/server";
import { getSongs, searchSongsByTitle, createSong, } from "@/lib/db/song";
import { getSongs, addSongToSongbook } from "@/lib/db/managing";
export async function GET() {
const songs = await getSongs();
if (songs) {
return NextResponse.json(songs);
} else {
return NextResponse.json({ success: false}, { status: 500})
}
}
export async function POST(request: Request) {
/**
* @openapi
* /api/songs:
* get:
* summary: Get all songs
* responses:
* 200:
* description: List of songs
* 500:
* description: Internal Server Error
*/
export async function GET(request: Request) {
try {
const { title, songbookId, number } = await request.json();
const { searchParams } = new URL(request.url);
const query = searchParams.get("query") || searchParams.get("q");
if (!title || !songbookId || !number) {
return NextResponse.json({ success: false, message: "Fields incomplete"}, { status: 400 });
if (query) {
const res = await searchSongsByTitle(query/*, 20*/); // You can enter a limit (default: 20)
if (!res.success) {
return NextResponse.json({ message: res.error }, { status: res.status });
}
return NextResponse.json(res.songBooks, { status: res.status });
}
const result = await addSongToSongbook(title, Number(songbookId), String(number));
if (result.success) {
return NextResponse.json({ success: true });
} else {
return NextResponse.json({ success: false }, { status: 500 });
// Ansonsten alle Songs abrufen
const res = await getSongs();
if (!res.success) {
return NextResponse.json({ message: res.error }, { status: res.status });
}
return NextResponse.json(res.songs, { status: res.status });
} catch (error) {
return NextResponse.json({ success: false }, { status: 500 });
console.error("POST /api/songs error:", error);
return NextResponse.json(
{ message: "Internal Server Error" },
{ status: 500 }
);
}
}
}
/**
* @openapi
* /api/songs:
* post:
* summary: Creates a new song
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* required:
* - name
* properties:
* name:
* type: string
* example: "Großer Gott"
* responses:
* 201:
* description: Songbook successfully created
* content:
* application/json:
* schema:
* type: object
* properties:
* success:
* type: boolean
* example: true
* songBook:
* type: object
* properties:
* id:
* type: integer
* example: 1
* title:
* type: string
* example: "Großer Gott"
* 400:
* description: Bad Request (missing name)
* 409:
* description: Conflict (title already exists)
* 500:
* description: Internal Server Error
*/
export async function POST(request: Request) {
try {
const data = await request.json();
if (!data.title) {
return NextResponse.json(
{ message: "Field 'title' is required"},
{ status: 400 }
);
}
const res = await createSong(data);
if (!res.success) {
return NextResponse.json(
{ message: res.error },
{ status: res.status }
);
}
return NextResponse.json(res, { status: res.status });
} catch (error) {
console.error("POST /api/songs error:", error);
return NextResponse.json(
{ message: "Internal Server Error" },
{ status: 500 }
);
}
}
-48
View File
@@ -1,48 +0,0 @@
import { NextResponse } from "next/server";
import { getSong } from "@/lib/db/managing";
let currentSong = {
songID: "",
songbook: "",
number: "",
title: ""
};
export async function GET() {
return NextResponse.json(currentSong)
}
export async function POST(request: Request) {
try {
const data = await request.json();
const songID = data.songID;
const songbookID = data.songbookID;
if (!songID || !songbookID) {
return NextResponse.json({ success: false, error: "Fields incomplete!" }, { status: 400 });
}
const song = await getSong(Number(songbookID), String(songID));
if (song) {
currentSong = {
songID: String(songID),
songbook: song.songbook_name,
number: song.number,
title: song.song_title,
};
} else {
currentSong = {
songID: "",
songbook: "",
number: "",
title: "",
};
}
console.log(currentSong);
return NextResponse.json({ success: true });
} catch (error) {
return NextResponse.json({ success: false, error: "Server-Fehler" }, { status: 500 });
}
}
Loaded 100 of 146 files, more files were not shown because too many files have changed in this diff. Show more