Compare commits
72 Commits
874b6e0cff
...
feat/impro
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
060a4f09e4 | ||
|
|
b99bc4d519 | ||
|
|
90f31290d4 | ||
|
|
e6d405a71e | ||
|
|
b12ffdda37 | ||
|
|
9617447e05 | ||
|
|
cd82a1e549 | ||
|
|
f5e77c99f6 | ||
|
|
f4d2c26e29 | ||
|
|
bef4056f8e | ||
|
|
2467ebc0f6 | ||
|
|
ec65c2198d | ||
|
|
8c5caecdda | ||
| b11dd47534 | |||
|
|
21a4c69f38 | ||
| e03f510874 | |||
|
|
59a4d18ce6 | ||
|
|
faf949fc9b | ||
|
|
6d120f4b1f | ||
|
|
69275c37b4 | ||
|
|
01b35691df | ||
| a93450579a | |||
|
|
ef38f98747 | ||
|
|
ea722a42f1 | ||
|
|
416c6f12e1 | ||
|
|
b5a00b309d | ||
|
|
454f20ed25 | ||
|
|
4e86096653 | ||
|
|
27bff32e76 | ||
|
|
13c1446977 | ||
| e9b44caf54 | |||
|
|
581cf2f2b2 | ||
|
|
81ed5747f3 | ||
|
|
8ccff20473 | ||
|
|
9520763ec3 | ||
|
|
5ef393fa64 | ||
|
|
45a1f50231 | ||
|
|
0f02331dfc | ||
|
|
df510cfe45 | ||
|
|
9f2e770509 | ||
|
|
2be59f99dd | ||
|
|
56096b1e35 | ||
|
|
2fd1826014 | ||
|
|
05da085e36 | ||
|
|
2e027408e6 | ||
|
|
54f1c7ab34 | ||
|
|
88c8b2ec90 | ||
|
|
0cd74194e3 | ||
|
|
f05fbf9e30 | ||
| 2370895710 | |||
|
|
02af5e3c11 | ||
|
|
e736ed3547 | ||
|
|
94c353f4f2 | ||
|
|
336e1af523 | ||
|
|
efde1aaf33 | ||
|
|
2e184845e1 | ||
| a363e9e8fc | |||
|
|
f1e0fc5aae | ||
| 17dca1ad89 | |||
|
|
c1b99804b3 | ||
|
|
5572ef0869 | ||
|
|
fc30927b8b | ||
|
|
785d54df7e | ||
| a937c827bb | |||
|
|
533bae021b | ||
|
|
d76c7e6200 | ||
|
|
d7ebb5b234 | ||
|
|
fa30fe2cff | ||
|
|
e8bca3a5ae | ||
|
|
6100c998be | ||
|
|
35ab3f0c06 | ||
|
|
a92e9e77c3 |
177
.agents/skills/frontend-design/LICENSE.txt
Normal file
177
.agents/skills/frontend-design/LICENSE.txt
Normal file
@@ -0,0 +1,177 @@
|
|||||||
|
|
||||||
|
Apache License
|
||||||
|
Version 2.0, January 2004
|
||||||
|
http://www.apache.org/licenses/
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||||
|
|
||||||
|
1. Definitions.
|
||||||
|
|
||||||
|
"License" shall mean the terms and conditions for use, reproduction,
|
||||||
|
and distribution as defined by Sections 1 through 9 of this document.
|
||||||
|
|
||||||
|
"Licensor" shall mean the copyright owner or entity authorized by
|
||||||
|
the copyright owner that is granting the License.
|
||||||
|
|
||||||
|
"Legal Entity" shall mean the union of the acting entity and all
|
||||||
|
other entities that control, are controlled by, or are under common
|
||||||
|
control with that entity. For the purposes of this definition,
|
||||||
|
"control" means (i) the power, direct or indirect, to cause the
|
||||||
|
direction or management of such entity, whether by contract or
|
||||||
|
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||||
|
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||||
|
|
||||||
|
"You" (or "Your") shall mean an individual or Legal Entity
|
||||||
|
exercising permissions granted by this License.
|
||||||
|
|
||||||
|
"Source" form shall mean the preferred form for making modifications,
|
||||||
|
including but not limited to software source code, documentation
|
||||||
|
source, and configuration files.
|
||||||
|
|
||||||
|
"Object" form shall mean any form resulting from mechanical
|
||||||
|
transformation or translation of a Source form, including but
|
||||||
|
not limited to compiled object code, generated documentation,
|
||||||
|
and conversions to other media types.
|
||||||
|
|
||||||
|
"Work" shall mean the work of authorship, whether in Source or
|
||||||
|
Object form, made available under the License, as indicated by a
|
||||||
|
copyright notice that is included in or attached to the work
|
||||||
|
(an example is provided in the Appendix below).
|
||||||
|
|
||||||
|
"Derivative Works" shall mean any work, whether in Source or Object
|
||||||
|
form, that is based on (or derived from) the Work and for which the
|
||||||
|
editorial revisions, annotations, elaborations, or other modifications
|
||||||
|
represent, as a whole, an original work of authorship. For the purposes
|
||||||
|
of this License, Derivative Works shall not include works that remain
|
||||||
|
separable from, or merely link (or bind by name) to the interfaces of,
|
||||||
|
the Work and Derivative Works thereof.
|
||||||
|
|
||||||
|
"Contribution" shall mean any work of authorship, including
|
||||||
|
the original version of the Work and any modifications or additions
|
||||||
|
to that Work or Derivative Works thereof, that is intentionally
|
||||||
|
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||||
|
or by an individual or Legal Entity authorized to submit on behalf of
|
||||||
|
the copyright owner. For the purposes of this definition, "submitted"
|
||||||
|
means any form of electronic, verbal, or written communication sent
|
||||||
|
to the Licensor or its representatives, including but not limited to
|
||||||
|
communication on electronic mailing lists, source code control systems,
|
||||||
|
and issue tracking systems that are managed by, or on behalf of, the
|
||||||
|
Licensor for the purpose of discussing and improving the Work, but
|
||||||
|
excluding communication that is conspicuously marked or otherwise
|
||||||
|
designated in writing by the copyright owner as "Not a Contribution."
|
||||||
|
|
||||||
|
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||||
|
on behalf of whom a Contribution has been received by Licensor and
|
||||||
|
subsequently incorporated within the Work.
|
||||||
|
|
||||||
|
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
copyright license to reproduce, prepare Derivative Works of,
|
||||||
|
publicly display, publicly perform, sublicense, and distribute the
|
||||||
|
Work and such Derivative Works in Source or Object form.
|
||||||
|
|
||||||
|
3. Grant of Patent License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
(except as stated in this section) patent license to make, have made,
|
||||||
|
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||||
|
where such license applies only to those patent claims licensable
|
||||||
|
by such Contributor that are necessarily infringed by their
|
||||||
|
Contribution(s) alone or by combination of their Contribution(s)
|
||||||
|
with the Work to which such Contribution(s) was submitted. If You
|
||||||
|
institute patent litigation against any entity (including a
|
||||||
|
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||||
|
or a Contribution incorporated within the Work constitutes direct
|
||||||
|
or contributory patent infringement, then any patent licenses
|
||||||
|
granted to You under this License for that Work shall terminate
|
||||||
|
as of the date such litigation is filed.
|
||||||
|
|
||||||
|
4. Redistribution. You may reproduce and distribute copies of the
|
||||||
|
Work or Derivative Works thereof in any medium, with or without
|
||||||
|
modifications, and in Source or Object form, provided that You
|
||||||
|
meet the following conditions:
|
||||||
|
|
||||||
|
(a) You must give any other recipients of the Work or
|
||||||
|
Derivative Works a copy of this License; and
|
||||||
|
|
||||||
|
(b) You must cause any modified files to carry prominent notices
|
||||||
|
stating that You changed the files; and
|
||||||
|
|
||||||
|
(c) You must retain, in the Source form of any Derivative Works
|
||||||
|
that You distribute, all copyright, patent, trademark, and
|
||||||
|
attribution notices from the Source form of the Work,
|
||||||
|
excluding those notices that do not pertain to any part of
|
||||||
|
the Derivative Works; and
|
||||||
|
|
||||||
|
(d) If the Work includes a "NOTICE" text file as part of its
|
||||||
|
distribution, then any Derivative Works that You distribute must
|
||||||
|
include a readable copy of the attribution notices contained
|
||||||
|
within such NOTICE file, excluding those notices that do not
|
||||||
|
pertain to any part of the Derivative Works, in at least one
|
||||||
|
of the following places: within a NOTICE text file distributed
|
||||||
|
as part of the Derivative Works; within the Source form or
|
||||||
|
documentation, if provided along with the Derivative Works; or,
|
||||||
|
within a display generated by the Derivative Works, if and
|
||||||
|
wherever such third-party notices normally appear. The contents
|
||||||
|
of the NOTICE file are for informational purposes only and
|
||||||
|
do not modify the License. You may add Your own attribution
|
||||||
|
notices within Derivative Works that You distribute, alongside
|
||||||
|
or as an addendum to the NOTICE text from the Work, provided
|
||||||
|
that such additional attribution notices cannot be construed
|
||||||
|
as modifying the License.
|
||||||
|
|
||||||
|
You may add Your own copyright statement to Your modifications and
|
||||||
|
may provide additional or different license terms and conditions
|
||||||
|
for use, reproduction, or distribution of Your modifications, or
|
||||||
|
for any such Derivative Works as a whole, provided Your use,
|
||||||
|
reproduction, and distribution of the Work otherwise complies with
|
||||||
|
the conditions stated in this License.
|
||||||
|
|
||||||
|
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||||
|
any Contribution intentionally submitted for inclusion in the Work
|
||||||
|
by You to the Licensor shall be under the terms and conditions of
|
||||||
|
this License, without any additional terms or conditions.
|
||||||
|
Notwithstanding the above, nothing herein shall supersede or modify
|
||||||
|
the terms of any separate license agreement you may have executed
|
||||||
|
with Licensor regarding such Contributions.
|
||||||
|
|
||||||
|
6. Trademarks. This License does not grant permission to use the trade
|
||||||
|
names, trademarks, service marks, or product names of the Licensor,
|
||||||
|
except as required for reasonable and customary use in describing the
|
||||||
|
origin of the Work and reproducing the content of the NOTICE file.
|
||||||
|
|
||||||
|
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||||
|
agreed to in writing, Licensor provides the Work (and each
|
||||||
|
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||||
|
implied, including, without limitation, any warranties or conditions
|
||||||
|
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||||
|
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||||
|
appropriateness of using or redistributing the Work and assume any
|
||||||
|
risks associated with Your exercise of permissions under this License.
|
||||||
|
|
||||||
|
8. Limitation of Liability. In no event and under no legal theory,
|
||||||
|
whether in tort (including negligence), contract, or otherwise,
|
||||||
|
unless required by applicable law (such as deliberate and grossly
|
||||||
|
negligent acts) or agreed to in writing, shall any Contributor be
|
||||||
|
liable to You for damages, including any direct, indirect, special,
|
||||||
|
incidental, or consequential damages of any character arising as a
|
||||||
|
result of this License or out of the use or inability to use the
|
||||||
|
Work (including but not limited to damages for loss of goodwill,
|
||||||
|
work stoppage, computer failure or malfunction, or any and all
|
||||||
|
other commercial damages or losses), even if such Contributor
|
||||||
|
has been advised of the possibility of such damages.
|
||||||
|
|
||||||
|
9. Accepting Warranty or Additional Liability. While redistributing
|
||||||
|
the Work or Derivative Works thereof, You may choose to offer,
|
||||||
|
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||||
|
or other liability obligations and/or rights consistent with this
|
||||||
|
License. However, in accepting such obligations, You may act only
|
||||||
|
on Your own behalf and on Your sole responsibility, not on behalf
|
||||||
|
of any other Contributor, and only if You agree to indemnify,
|
||||||
|
defend, and hold each Contributor harmless for any liability
|
||||||
|
incurred by, or claims asserted against, such Contributor by reason
|
||||||
|
of your accepting any such warranty or additional liability.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
71
.agents/skills/frontend-design/SKILL.md
Normal file
71
.agents/skills/frontend-design/SKILL.md
Normal file
@@ -0,0 +1,71 @@
|
|||||||
|
---
|
||||||
|
name: frontend-design
|
||||||
|
description: Guidance for distinctive, intentional visual design when building new UI or reshaping an existing one. Helps with aesthetic direction, typography, and making choices that don't read as templated defaults.
|
||||||
|
license: Complete terms in LICENSE.txt
|
||||||
|
---
|
||||||
|
|
||||||
|
# Frontend Design
|
||||||
|
|
||||||
|
Approach this as the design lead at a design studio known for giving every client a distinct visual identity that is not mistaken for anyone else's. This client has already rejected proposals that felt cliché or templated, and is paying for a distinctive point of view: make deliberate, opinionated choices about palette, typography, and layout that are specific to this brief, and take aesthetic risk if justified.
|
||||||
|
|
||||||
|
## Ground your designs in the subject matter
|
||||||
|
|
||||||
|
If the brief does not identify what the product or subject matter is, identify it yourself before designing, and confirm with the client. You can come up with one concrete subject, the design's audience, and the design's primary job, as a proposal. If there's any information in your memory about the client's preferences or context about what they're building, use that as a hint. The subject's industry, subject matter, materials, and vernacular are where distinctive visual choices come from — a design for a toy for girls aged 8–11 will be very aesthetically different from a dashboard for financial analysts. Build with the brief's real content and subject matter throughout.
|
||||||
|
|
||||||
|
## Design principles
|
||||||
|
|
||||||
|
For web designs, the hero is the first thing viewers will see. Open with the most characteristic thing in the subject's world, in the form that is most appropriate: a headline, an image, an animation, a live demo, an interactive moment, or other treatments. Be deliberate with your choice: a big number with a small label, supporting stats, and a gradient accent is the default treatment, so only use it if that's truly the best option.
|
||||||
|
|
||||||
|
Typography carries the personality of the page. You don't need a different typeface for display or headline text and body content: use one family or two, and if two, make them clearly distinct.
|
||||||
|
|
||||||
|
Choose your typefaces deliberately, not the default families you would reach for on any other project, and set a clear type scale following the default guidance of The Elements of Typographic Style with intentional weights, widths, and spacing. When type is used as a headline or visual element, use the type treatment itself as an active part of the design, not a neutral delivery vehicle for the content.
|
||||||
|
|
||||||
|
Default to line lengths of less than 80 characters. Serif typefaces can have slightly longer line lengths; give serif body text slightly more line-height than a sans-serif.
|
||||||
|
|
||||||
|
Avoid these default typographic treatments; they are the commonest tells of a generated page:
|
||||||
|
- Accenting just a single word or phrase in a headline, like putting one word in italic/bold or a different color.
|
||||||
|
- Using all caps for labels.
|
||||||
|
- Adding unnecessary typographic labels above content.
|
||||||
|
|
||||||
|
Visual structure is information. Structural devices like outlines, borders, numbering, eyebrows, dividers, labels, etc., encode useful information about the content rather than decorate it. Many generic designs use numbered markers (01 / 02 / 03), but that's only appropriate if the content actually is a sequence — like a stepped process or a timeline. Before adding numbered markers, check the content really is a sequence.
|
||||||
|
|
||||||
|
Use non-user-triggered motion sparingly and deliberately, only to draw attention. A single orchestrated moment — one page-load sequence or one reveal — lands better than scattered effects; fade-and-slide-up entrances on each section and hover transitions on every card are the generic default and read as AI-generated. Motion that answers a person's action (opening, expanding, confirming) is welcome when it shows what changed.
|
||||||
|
|
||||||
|
Consider written content carefully. Often a design brief may not contain real content, and it's up to you to come up with copy and placeholder content. Copy can make a design feel as templated as the design itself. See the below section on writing for more guidance.
|
||||||
|
|
||||||
|
## Process: plan, review against the brief, build, critique
|
||||||
|
|
||||||
|
For calibration, AI-generated design right now clusters around some traits:
|
||||||
|
1. a warm cream background (near #F4F1EA) with a high-contrast serif display and a terracotta or warm-clay accent (often near #D97757 — Anthropic's own Claude-interaction accent, so on a user's brief it reads as a tell);
|
||||||
|
2. a near-black background with a single bright acid-green or vermilion accent;
|
||||||
|
3. a broadsheet-style layout with hairline rules, zero border-radius, and dense newspaper-like columns;
|
||||||
|
4. the SaaS-card kit: content chopped into identical rounded cards, one border-radius on everything regardless of hierarchy, the same soft grey shadow (rgba(0,0,0,.1)) under each, and gradient washes as decoration;
|
||||||
|
5. template chrome that appears whatever the subject: a tracked-out ALL-CAPS eyebrow label above every heading; meta strings joined with middle dots ('A · B · C'); labels built as 'WORD — fragment' with a spaced em dash; tinted near-black (#0B0B0B, #111) standing in for black; a monospace face for small data labels; a '→' appended to link and button text.
|
||||||
|
|
||||||
|
All traits are legitimate for some briefs, but they are defaults rather than choices, and they appear regardless of subject. Where the brief pins down a visual direction, follow it exactly — the brief's own words always win, including when it asks for one of these looks. Where it leaves an axis free, don't spend that freedom on one of these defaults. As with a hired human designer, there's often a careful balance between doing what you're good at and taking each project as a chance to experiment and learn.
|
||||||
|
|
||||||
|
Work in two passes. First, brainstorm a short design plan based on the client's design brief: create a compact token system with color, type, layout, and principles.
|
||||||
|
- Color: describe the core base palette as 4–6 named hex values.
|
||||||
|
- Type: the typefaces and their roles.
|
||||||
|
- Layout: a layout concept, using one-sentence prose descriptions and ASCII wireframes to ideate and compare. Include alignment guidance; should the content be left aligned, center aligned, justified?
|
||||||
|
- Principles: the high-level guidance for what makes this page unique.
|
||||||
|
|
||||||
|
Then review that plan against the brief before building: if any part of it reads like the generic default you would produce for any similar page (work through a similar prompt to see if you arrive somewhere similar) rather than a choice made for this specific brief — revise that part, say what you changed and why. Only after you've confirmed the relative uniqueness of your design plan should you start to write the code, following the revised plan.
|
||||||
|
|
||||||
|
When writing the code, be careful of structuring your CSS selector specificities. It's easy to generate CSS classes that cancel each other out (especially with a type-based selector like .section and an element-based selector like .cta). This can happen often with padding/margin between sections.
|
||||||
|
|
||||||
|
## Restraint and self-critique
|
||||||
|
|
||||||
|
Spend your boldness in one place. Let one element be the memorable thing, keep everything around it quiet and disciplined, and cut any decoration that does not serve the brief. Build to a quality floor without announcing it: responsive down to mobile, visible keyboard focus, reduced motion respected, visually accessible, harmonious color palettes. Critique your own work as you build, taking screenshots to review if your environment supports it — a picture is worth 1000 tokens. Consider Chanel's advice: before leaving the house, take a look in the mirror and remove one accessory. Human creatives have memory and always try to do something new, so if you have a space to quickly jot down notes about what you've tried, it can help you in future passes.
|
||||||
|
|
||||||
|
## More on writing in design
|
||||||
|
|
||||||
|
Words appear in a design for one reason: to make it easier to understand and use. They are design content, not decoration. Bring the same intentionality and minimalism to copywriting that you would bring to spacing and color. Before writing anything, ask what the design needs to say, and how it can best be said to help the person navigate the experience.
|
||||||
|
|
||||||
|
Write from the end user's perspective. Name things by what users will understand in simple language, not by how the system is built. A user manages notifications, not webhook config. Describe what something is or does in plain terms rather than selling it. Being specific and legible to new users is always better than being clever.
|
||||||
|
|
||||||
|
Use active voice as default. A CTA says exactly what happens when it is used: "Save changes," not "Submit." An action keeps the same name through the whole flow, so the button that says "Publish" produces a toast that says "Published." The vocabulary of an interface is the signposting for someone navigating the product. Cohesion and consistency are how people learn their way around.
|
||||||
|
|
||||||
|
Treat failure and emptiness as moments for direction, not mood. Explain what went wrong and how to fix it, in the interface's voice rather than a person's. Errors don't apologize, and they are never vague about what happened. An empty screen is an invitation to act.
|
||||||
|
|
||||||
|
Keep the tone conversational: plain verbs, sentence case, no filler, with tone matched to the brand and the audience. Let each written element do exactly one job.
|
||||||
29
.dockerignore
Normal file
29
.dockerignore
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
# Dependencias y artefactos locales: el build los regenera adentro de la imagen.
|
||||||
|
node_modules
|
||||||
|
**/node_modules
|
||||||
|
|
||||||
|
# Se generan en el builder (prisma generate, vite build).
|
||||||
|
apps/backend/generated
|
||||||
|
apps/backend/dist
|
||||||
|
apps/web/dist
|
||||||
|
.turbo
|
||||||
|
**/.turbo
|
||||||
|
|
||||||
|
# Secretos: en Dokploy llegan por variables de entorno.
|
||||||
|
.env
|
||||||
|
**/.env
|
||||||
|
!.env.example
|
||||||
|
**/.env.example
|
||||||
|
|
||||||
|
# Ruido del repo.
|
||||||
|
.git
|
||||||
|
.gitignore
|
||||||
|
.github
|
||||||
|
.DS_Store
|
||||||
|
*.log
|
||||||
|
README.md
|
||||||
|
stack.md
|
||||||
|
skills-lock.json
|
||||||
|
**/skills-lock.json
|
||||||
|
.agents
|
||||||
|
**/.agents
|
||||||
81
.env.example
Normal file
81
.env.example
Normal file
@@ -0,0 +1,81 @@
|
|||||||
|
# Variable template for `docker compose`.
|
||||||
|
#
|
||||||
|
# Local: copy this file to `.env` at the root and fill in the values.
|
||||||
|
# Dokploy: no file needed; define the same variables in the Environment tab of
|
||||||
|
# the Compose service (Dokploy writes them to a `.env` next to the compose
|
||||||
|
# file, which is where the `${...}` come from).
|
||||||
|
|
||||||
|
# Public origin of the app, no trailing slash. The same value feeds WEB_URL and
|
||||||
|
# BETTER_AUTH_URL because nginx proxies /api: the web and the API share a
|
||||||
|
# domain, so the session cookie is first-party.
|
||||||
|
WEB_URL="http://localhost:8080"
|
||||||
|
|
||||||
|
# Production PostgreSQL.
|
||||||
|
# The password must be percent-encoded: if it has #, @, :, /, ?, % or a space,
|
||||||
|
# escape it (%23, %40, %3A, %2F, %3F, %25, %20). Otherwise Prisma truncates the
|
||||||
|
# URL where the fragment starts and fails with P1013 "invalid port number in
|
||||||
|
# database URL".
|
||||||
|
DATABASE_URL="postgresql://user:password@localhost:5432/gruperly?schema=public"
|
||||||
|
|
||||||
|
# Generate it with: openssl rand -base64 32
|
||||||
|
BETTER_AUTH_SECRET=""
|
||||||
|
|
||||||
|
# ── Optional ─────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
# Social login with Google. Without a client id/secret the provider is not
|
||||||
|
# registered.
|
||||||
|
# GOOGLE_CLIENT_ID=""
|
||||||
|
# GOOGLE_CLIENT_SECRET=""
|
||||||
|
|
||||||
|
# Email sending (same variables as apps/backend/.env.example).
|
||||||
|
# EMAIL_PROVIDER="smtp"
|
||||||
|
# EMAIL_SERVER_HOST=""
|
||||||
|
# EMAIL_SERVER_PORT="587"
|
||||||
|
# EMAIL_SERVER_USER=""
|
||||||
|
# EMAIL_SERVER_PASSWORD=""
|
||||||
|
# EMAIL_FROM="Gruperly <no-reply@gruperly.com>"
|
||||||
|
|
||||||
|
# Mercado Pago (OAuth Authorization Code + PKCE). Opcionales: sin credenciales
|
||||||
|
# GET /mp/connect responde 503 mp_not_configured y la app sigue funcionando
|
||||||
|
# (el paso "Cobros" del onboarding es salteable).
|
||||||
|
# Generate it with: openssl rand -base64 32 -- exactly 32 bytes once decoded.
|
||||||
|
# TOKEN_ENCRYPTION_KEY=""
|
||||||
|
# Redirect URL registered in the Mercado Pago panel, character for character.
|
||||||
|
# The panel requires HTTPS (no http://localhost): local dev goes through a tunnel.
|
||||||
|
# MP_REDIRECT_URI="https://api.gruperly.com/api/v1/mp/callback"
|
||||||
|
# MP_CLIENT_ID=""
|
||||||
|
# MP_CLIENT_SECRET=""
|
||||||
|
|
||||||
|
# Suscripción a Gruperly Pro (Suscripciones de Mercado Pago, ver docs/billing.md).
|
||||||
|
# Credenciales de las cuentas de MP **de Gruperly**, una por país (MP no cobra
|
||||||
|
# entre países). No son las del OAuth del profesor. Un país sin las dos queda
|
||||||
|
# con Pro "no disponible" (503). Códigos: AR, BR, CL, CO, MX, PE, UY.
|
||||||
|
# MP_PLATFORM_ACCESS_TOKEN_AR=""
|
||||||
|
# MP_PLATFORM_WEBHOOK_SECRET_AR=""
|
||||||
|
# on = aplica los límites del plan Free. Cualquier otro valor (o vacío): todos Pro.
|
||||||
|
# BILLING_ENFORCEMENT="off"
|
||||||
|
# Días que un Pro vencido (cancelado o con el cobro rechazado) sigue funcionando.
|
||||||
|
# BILLING_GRACE_DAYS="7"
|
||||||
|
|
||||||
|
# WhatsApp: recordatorios de pago y reenganche semanales (docs/whatsapp.md).
|
||||||
|
# Opcional: sin las variables del proveedor elegido, /whatsapp/* responde 503
|
||||||
|
# whatsapp_not_configured y el paso del onboarding es salteable.
|
||||||
|
# WHATSAPP_PROVIDER="openwa" # openwa (MVP) | kapso
|
||||||
|
# WHATSAPP_SEND_INTERVAL_MS="5000" # pausa entre envios del mismo profesor
|
||||||
|
#
|
||||||
|
# OpenWA (se instala aparte, fuera de este compose).
|
||||||
|
# OPENWA_API_URL="https://openwa.example.com/api"
|
||||||
|
# OPENWA_API_KEY="" # key OPERATOR, sin allowedSessions
|
||||||
|
# OPENWA_WEBHOOK_URL="https://app.gruperly.com/api/v1/whatsapp/webhooks/openwa"
|
||||||
|
# OPENWA_WEBHOOK_SECRET="" # 16+ caracteres: openssl rand -hex 24
|
||||||
|
#
|
||||||
|
# Kapso (API oficial de WhatsApp Cloud).
|
||||||
|
# KAPSO_API_KEY=""
|
||||||
|
# KAPSO_CALLBACK_URL="https://app.gruperly.com/api/v1/whatsapp/callback"
|
||||||
|
# KAPSO_WEBHOOK_URL="https://app.gruperly.com/api/v1/whatsapp/webhooks/kapso"
|
||||||
|
# KAPSO_WEBHOOK_SECRET="" # el mismo del project webhook de Kapso
|
||||||
|
|
||||||
|
# Only if you want the API on another domain: it is baked into the Vite bundle
|
||||||
|
# and forces you to drop the /api proxy from apps/web/nginx.conf. Empty = same
|
||||||
|
# origin (recommended).
|
||||||
|
# VITE_API_URL=""
|
||||||
2
.gitignore
vendored
2
.gitignore
vendored
@@ -90,6 +90,8 @@ out
|
|||||||
# Nuxt.js build / generate output
|
# Nuxt.js build / generate output
|
||||||
.nuxt
|
.nuxt
|
||||||
dist
|
dist
|
||||||
|
# Service worker que vite-plugin-pwa escribe al serving en dev
|
||||||
|
dev-dist
|
||||||
|
|
||||||
# Gatsby files
|
# Gatsby files
|
||||||
.cache/
|
.cache/
|
||||||
|
|||||||
954
.interface-design/group-detail-redesign.html
Normal file
954
.interface-design/group-detail-redesign.html
Normal file
@@ -0,0 +1,954 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="es">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||||
|
<title>Gruperly — Rediseño detalle de grupo (2 estados)</title>
|
||||||
|
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||||
|
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
||||||
|
<link
|
||||||
|
href="https://fonts.googleapis.com/css2?family=Inter:wght@100..900&display=swap"
|
||||||
|
rel="stylesheet"
|
||||||
|
/>
|
||||||
|
<script src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"></script>
|
||||||
|
<script src="https://cdn.jsdelivr.net/npm/lucide@0.469.0/dist/umd/lucide.min.js"></script>
|
||||||
|
<style type="text/tailwindcss">
|
||||||
|
@theme inline {
|
||||||
|
--color-background: var(--background);
|
||||||
|
--color-surface: var(--surface);
|
||||||
|
--color-primary: var(--primary);
|
||||||
|
--color-primary-soft: var(--primary-soft);
|
||||||
|
--color-foreground: var(--foreground);
|
||||||
|
--color-accent: var(--accent);
|
||||||
|
--color-accent-strong: var(--accent-strong);
|
||||||
|
--color-accent-soft: var(--accent-soft);
|
||||||
|
--color-accent-fg: var(--accent-fg);
|
||||||
|
--color-border: var(--border);
|
||||||
|
--color-on-accent: var(--on-accent);
|
||||||
|
--color-success: var(--success);
|
||||||
|
--color-success-soft: var(--success-soft);
|
||||||
|
--color-warning: var(--warning);
|
||||||
|
--color-warning-soft: var(--warning-soft);
|
||||||
|
--color-danger: var(--danger);
|
||||||
|
--color-danger-soft: var(--danger-soft);
|
||||||
|
--radius-xl: 0.75rem;
|
||||||
|
--font-sans: "Inter", ui-sans-serif, system-ui, sans-serif;
|
||||||
|
--animate-fade-in: fade-in 0.2s ease-out;
|
||||||
|
@keyframes fade-in {
|
||||||
|
from {
|
||||||
|
opacity: 0;
|
||||||
|
}
|
||||||
|
to {
|
||||||
|
opacity: 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
:root {
|
||||||
|
color-scheme: dark;
|
||||||
|
--background: #020617;
|
||||||
|
--surface: #0f172a;
|
||||||
|
--primary: #f1f5f9;
|
||||||
|
--primary-soft: #1e293b;
|
||||||
|
--foreground: #94a3b8;
|
||||||
|
--accent: #2544ea;
|
||||||
|
--accent-strong: #1d33d8;
|
||||||
|
--accent-soft: color-mix(in srgb, #3b63f5 15%, transparent);
|
||||||
|
--accent-fg: #93b4fd;
|
||||||
|
--border: #1e293b;
|
||||||
|
--on-accent: #ffffff;
|
||||||
|
--success: #34d399;
|
||||||
|
--success-soft: color-mix(in srgb, #34d399 15%, transparent);
|
||||||
|
--warning: #fcd34d;
|
||||||
|
--warning-soft: color-mix(in srgb, #fcd34d 15%, transparent);
|
||||||
|
--danger: #fb7185;
|
||||||
|
--danger-soft: color-mix(in srgb, #fb7185 15%, transparent);
|
||||||
|
}
|
||||||
|
|
||||||
|
html,
|
||||||
|
body {
|
||||||
|
background: var(--background);
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
<style>
|
||||||
|
.frames {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 32px;
|
||||||
|
align-items: flex-start;
|
||||||
|
}
|
||||||
|
.frame {
|
||||||
|
width: 390px;
|
||||||
|
}
|
||||||
|
.screen {
|
||||||
|
background: var(--background);
|
||||||
|
border: 1px solid color-mix(in srgb, var(--border) 70%, transparent);
|
||||||
|
border-radius: 24px;
|
||||||
|
padding: 16px 12px 24px;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
/* Botón (equivalente a components/ui/button.tsx, clases ya fusionadas) */
|
||||||
|
.btn {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
gap: 8px;
|
||||||
|
white-space: nowrap;
|
||||||
|
border-radius: 0.75rem;
|
||||||
|
font-weight: 500;
|
||||||
|
font-size: 14px;
|
||||||
|
line-height: 20px;
|
||||||
|
padding: 0 16px;
|
||||||
|
height: 44px;
|
||||||
|
cursor: pointer;
|
||||||
|
border: 0;
|
||||||
|
font-family: inherit;
|
||||||
|
}
|
||||||
|
.btn-outline {
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
background: var(--surface);
|
||||||
|
color: var(--primary);
|
||||||
|
}
|
||||||
|
.btn-ghost {
|
||||||
|
background: transparent;
|
||||||
|
color: var(--primary);
|
||||||
|
}
|
||||||
|
.btn-primary {
|
||||||
|
background: var(--accent);
|
||||||
|
color: var(--on-accent);
|
||||||
|
}
|
||||||
|
.btn-block {
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
.chip {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 6px;
|
||||||
|
min-height: 44px;
|
||||||
|
border-radius: 9999px;
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
padding: 0 14px;
|
||||||
|
font-size: 12px;
|
||||||
|
font-weight: 600;
|
||||||
|
background: var(--surface);
|
||||||
|
color: color-mix(in srgb, var(--foreground) 80%, transparent);
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
.chip-active {
|
||||||
|
border-color: transparent;
|
||||||
|
background: var(--accent);
|
||||||
|
color: var(--on-accent);
|
||||||
|
box-shadow: 0 1px 2px rgb(0 0 0 / 0.05);
|
||||||
|
}
|
||||||
|
.pill {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
border-radius: 9999px;
|
||||||
|
padding: 2px 6px;
|
||||||
|
font-size: 10px;
|
||||||
|
font-weight: 700;
|
||||||
|
line-height: 1;
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
}
|
||||||
|
.pill-warn {
|
||||||
|
background: var(--warning-soft);
|
||||||
|
color: var(--warning);
|
||||||
|
}
|
||||||
|
.pill-neutral {
|
||||||
|
background: var(--primary-soft);
|
||||||
|
color: color-mix(in srgb, var(--foreground) 60%, transparent);
|
||||||
|
}
|
||||||
|
.pill-on-accent {
|
||||||
|
background: color-mix(in srgb, var(--on-accent) 25%, transparent);
|
||||||
|
color: var(--on-accent);
|
||||||
|
}
|
||||||
|
.label-cell {
|
||||||
|
font-size: 11px;
|
||||||
|
font-weight: 600;
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: 0.02em;
|
||||||
|
color: color-mix(in srgb, var(--foreground) 70%, transparent);
|
||||||
|
}
|
||||||
|
.avatar {
|
||||||
|
display: flex;
|
||||||
|
width: 36px;
|
||||||
|
height: 36px;
|
||||||
|
flex-shrink: 0;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
border-radius: 9999px;
|
||||||
|
background: color-mix(in srgb, var(--accent) 10%, transparent);
|
||||||
|
font-size: 12px;
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--accent);
|
||||||
|
}
|
||||||
|
.row {
|
||||||
|
border-bottom: 1px solid color-mix(in srgb, var(--border) 70%, transparent);
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
.row:last-child {
|
||||||
|
border-bottom: 0;
|
||||||
|
}
|
||||||
|
table {
|
||||||
|
width: 100%;
|
||||||
|
table-layout: fixed;
|
||||||
|
text-align: left;
|
||||||
|
font-size: 14px;
|
||||||
|
}
|
||||||
|
th {
|
||||||
|
font-size: 12px;
|
||||||
|
font-weight: 600;
|
||||||
|
color: color-mix(in srgb, var(--foreground) 80%, transparent);
|
||||||
|
padding: 0 12px 8px;
|
||||||
|
}
|
||||||
|
td {
|
||||||
|
padding: 10px 12px;
|
||||||
|
vertical-align: middle;
|
||||||
|
}
|
||||||
|
.truncate {
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
.tabular {
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
}
|
||||||
|
svg.lucide {
|
||||||
|
width: 16px;
|
||||||
|
height: 16px;
|
||||||
|
stroke-width: 2;
|
||||||
|
}
|
||||||
|
.icon-20 svg.lucide,
|
||||||
|
svg.icon-20 {
|
||||||
|
width: 20px;
|
||||||
|
height: 20px;
|
||||||
|
}
|
||||||
|
.icon-40 svg.lucide,
|
||||||
|
svg.icon-40 {
|
||||||
|
width: 40px;
|
||||||
|
height: 40px;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body class="antialiased">
|
||||||
|
<div class="mx-auto max-w-[1780px] px-6 py-8">
|
||||||
|
<header class="mb-8 max-w-3xl">
|
||||||
|
<p class="text-xs font-semibold uppercase tracking-wide text-accent-fg">
|
||||||
|
Gruperly · /groups/$groupId
|
||||||
|
</p>
|
||||||
|
<h1 class="mt-1 text-2xl font-bold text-primary">Rediseño del detalle de grupo</h1>
|
||||||
|
<p class="mt-2 text-sm leading-relaxed text-foreground/80">
|
||||||
|
Dos pestañas (<strong class="text-primary">Miembros</strong> ·
|
||||||
|
<strong class="text-primary">Pendientes</strong>), tarjeta de info con lectura
|
||||||
|
Horario → Cupo → Cobro, un solo foco primario por estado y objetivos táctiles de 44px.
|
||||||
|
Tema oscuro, tokens reales de <code class="text-accent-fg">apps/web/src/index.css</code>.
|
||||||
|
</p>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<div class="frames">
|
||||||
|
<!-- ═══════════════ ESTADO 1 · MIEMBROS ═══════════════ -->
|
||||||
|
<div class="frame">
|
||||||
|
<p class="mb-2 text-sm font-semibold text-primary">
|
||||||
|
1 · Con miembros + pre-inscripciones — pestaña “Miembros”
|
||||||
|
</p>
|
||||||
|
<div class="screen">
|
||||||
|
<section class="space-y-5">
|
||||||
|
<!-- Header -->
|
||||||
|
<div>
|
||||||
|
<div class="flex flex-col gap-3">
|
||||||
|
<div class="min-w-0">
|
||||||
|
<h1 class="text-2xl font-bold leading-tight text-primary">Tai Chi Martes</h1>
|
||||||
|
<p class="mt-1.5 text-sm leading-relaxed text-foreground/80">
|
||||||
|
Tai chi para principiantes. Trae ropa cómoda.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div class="flex flex-wrap items-center gap-2">
|
||||||
|
<span
|
||||||
|
class="inline-flex shrink-0 items-center gap-1.5 whitespace-nowrap rounded-full bg-success-soft px-2.5 py-0.5 text-[11px] font-medium text-success"
|
||||||
|
>
|
||||||
|
<span class="size-1.5 rounded-full bg-success"></span>Activo
|
||||||
|
</span>
|
||||||
|
<span
|
||||||
|
class="inline-flex shrink-0 items-center gap-1.5 whitespace-nowrap rounded-full bg-warning-soft px-2.5 py-0.5 text-[11px] font-medium text-warning"
|
||||||
|
>
|
||||||
|
<span class="size-1.5 rounded-full bg-warning"></span>Riesgo moderado
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Acciones: dos outline + "Agregar" ghost (no compite) -->
|
||||||
|
<div class="mt-4 grid grid-cols-2 gap-2.5">
|
||||||
|
<button class="btn btn-outline btn-block">
|
||||||
|
<i data-lucide="bar-chart-3" class="text-accent"></i><span>Estadísticas</span>
|
||||||
|
</button>
|
||||||
|
<button class="btn btn-outline btn-block">
|
||||||
|
<i data-lucide="share-2" class="text-accent"></i><span>Compartir Link</span>
|
||||||
|
</button>
|
||||||
|
<button class="btn btn-ghost btn-block col-span-2">
|
||||||
|
<i data-lucide="user-plus" class="text-accent"></i
|
||||||
|
><span>Agregar Miembros</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Tarjeta de info: Horario → Cupo → Cobro -->
|
||||||
|
<div
|
||||||
|
class="divide-y divide-border/70 rounded-2xl bg-primary-soft p-4"
|
||||||
|
>
|
||||||
|
<div class="flex items-start gap-3 py-3 first:pt-0">
|
||||||
|
<i data-lucide="calendar-clock" class="icon-20 mt-0.5 shrink-0 text-accent"></i>
|
||||||
|
<div class="min-w-0 flex-1">
|
||||||
|
<p class="label-cell">Horario</p>
|
||||||
|
<p class="mt-1 text-base font-semibold leading-snug text-primary">Martes</p>
|
||||||
|
<p class="mt-0.5 text-sm tabular text-foreground">18:00 - 19:30</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="flex items-start gap-3 py-3">
|
||||||
|
<i data-lucide="users" class="icon-20 mt-0.5 shrink-0 text-accent"></i>
|
||||||
|
<div class="min-w-0 flex-1">
|
||||||
|
<p class="label-cell">Miembros & Cupo</p>
|
||||||
|
<p
|
||||||
|
class="mt-1 flex items-baseline text-2xl font-semibold leading-none tracking-tight tabular text-primary"
|
||||||
|
>
|
||||||
|
<span>3</span><span class="text-base font-medium text-foreground/70">/4</span>
|
||||||
|
</p>
|
||||||
|
<div
|
||||||
|
class="mt-2 h-1.5 w-full max-w-[9rem] overflow-hidden rounded-full bg-accent/15"
|
||||||
|
>
|
||||||
|
<div class="h-full w-3/4 rounded-full bg-accent"></div>
|
||||||
|
</div>
|
||||||
|
<p class="mt-1.5 text-sm text-foreground">1 lugar libre · 1 en espera</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="flex items-start gap-3 py-3 last:pb-0">
|
||||||
|
<div
|
||||||
|
class="mt-0.5 flex size-5 shrink-0 items-center justify-center text-sm font-bold leading-none text-accent"
|
||||||
|
>
|
||||||
|
$
|
||||||
|
</div>
|
||||||
|
<div class="min-w-0 flex-1">
|
||||||
|
<p class="label-cell">Cobro</p>
|
||||||
|
<p class="mt-1 text-base font-semibold tabular text-primary">$450.00</p>
|
||||||
|
<p class="mt-0.5 text-sm text-foreground">Vence el día 10 de cada mes</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Listados -->
|
||||||
|
<div class="rounded-2xl bg-primary-soft p-2">
|
||||||
|
<div class="space-y-2 p-2">
|
||||||
|
<div class="flex flex-col gap-2.5">
|
||||||
|
<div class="flex w-full flex-wrap items-center gap-2">
|
||||||
|
<button class="chip chip-active">
|
||||||
|
<i data-lucide="users"></i><span>Miembros</span
|
||||||
|
><span class="pill pill-on-accent">3</span>
|
||||||
|
</button>
|
||||||
|
<button class="chip">
|
||||||
|
<i data-lucide="inbox"></i><span>Pendientes</span
|
||||||
|
><span class="pill pill-warn">3</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div class="relative w-full">
|
||||||
|
<i
|
||||||
|
data-lucide="search"
|
||||||
|
class="absolute left-3 top-1/2 -translate-y-1/2 text-foreground/70"
|
||||||
|
></i>
|
||||||
|
<input
|
||||||
|
class="h-11 w-full rounded-lg border border-transparent bg-surface pl-9 pr-3 text-base text-primary shadow-xs placeholder:text-foreground/80 focus:outline-none"
|
||||||
|
placeholder="Buscar por nombre o teléfono..."
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<p class="text-xs leading-relaxed text-foreground/80">
|
||||||
|
Listado de todos los miembros incorporados al grupo.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="rounded-lg bg-surface p-1 shadow-xs">
|
||||||
|
<table>
|
||||||
|
<thead>
|
||||||
|
<tr class="border-b border-border/70">
|
||||||
|
<th scope="col" class="w-[48%]">Nombre</th>
|
||||||
|
<th scope="col">Teléfono</th>
|
||||||
|
<th scope="col" class="w-9 px-1"><span class="sr-only">Detalle</span></th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
<tr class="row">
|
||||||
|
<td>
|
||||||
|
<div class="flex min-w-0 items-center gap-2.5">
|
||||||
|
<div class="avatar">A</div>
|
||||||
|
<span class="min-w-0 truncate font-medium text-primary">Ana López</span>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
<td class="min-w-0 text-foreground/80">
|
||||||
|
<span class="block truncate tabular">55 1234 5678</span>
|
||||||
|
</td>
|
||||||
|
<td class="w-9 px-1 text-foreground/50">
|
||||||
|
<i data-lucide="chevron-right" class="ml-auto block"></i>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<tr class="row">
|
||||||
|
<td>
|
||||||
|
<div class="flex min-w-0 items-center gap-2.5">
|
||||||
|
<div class="avatar">C</div>
|
||||||
|
<span class="min-w-0 truncate font-medium text-primary"
|
||||||
|
>Carlos Mendoza</span
|
||||||
|
>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
<td class="min-w-0 text-foreground/80">
|
||||||
|
<span class="block truncate tabular">55 2345 6789</span>
|
||||||
|
</td>
|
||||||
|
<td class="w-9 px-1 text-foreground/50">
|
||||||
|
<i data-lucide="chevron-right" class="ml-auto block"></i>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<tr class="row">
|
||||||
|
<td>
|
||||||
|
<div class="flex min-w-0 items-center gap-2.5">
|
||||||
|
<div class="avatar">L</div>
|
||||||
|
<span class="min-w-0 truncate font-medium text-primary"
|
||||||
|
>Lucía Hernández</span
|
||||||
|
>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
<td class="min-w-0 text-foreground/80">
|
||||||
|
<span class="block truncate tabular">55 3456 7890</span>
|
||||||
|
</td>
|
||||||
|
<td class="w-9 px-1 text-foreground/50">
|
||||||
|
<i data-lucide="chevron-right" class="ml-auto block"></i>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
<p class="mt-3 text-xs leading-relaxed text-foreground/70">
|
||||||
|
Un solo tono activo: el chip “Miembros”. “Agregar Miembros” es
|
||||||
|
<code class="text-foreground/80">ghost</code> — disponible, no dominante. Cupo
|
||||||
|
escaneable como <strong class="text-primary">3/4</strong> + barra.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- ═══════════════ ESTADO 1 · PENDIENTES ═══════════════ -->
|
||||||
|
<div class="frame">
|
||||||
|
<p class="mb-2 text-sm font-semibold text-primary">
|
||||||
|
1 · Con miembros + pre-inscripciones — pestaña “Pendientes”
|
||||||
|
</p>
|
||||||
|
<div class="screen">
|
||||||
|
<section class="space-y-5">
|
||||||
|
<div>
|
||||||
|
<div class="flex flex-col gap-3">
|
||||||
|
<div class="min-w-0">
|
||||||
|
<h1 class="text-2xl font-bold leading-tight text-primary">Tai Chi Martes</h1>
|
||||||
|
<p class="mt-1.5 text-sm leading-relaxed text-foreground/80">
|
||||||
|
Tai chi para principiantes. Trae ropa cómoda.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div class="flex flex-wrap items-center gap-2">
|
||||||
|
<span
|
||||||
|
class="inline-flex shrink-0 items-center gap-1.5 whitespace-nowrap rounded-full bg-success-soft px-2.5 py-0.5 text-[11px] font-medium text-success"
|
||||||
|
>
|
||||||
|
<span class="size-1.5 rounded-full bg-success"></span>Activo
|
||||||
|
</span>
|
||||||
|
<span
|
||||||
|
class="inline-flex shrink-0 items-center gap-1.5 whitespace-nowrap rounded-full bg-warning-soft px-2.5 py-0.5 text-[11px] font-medium text-warning"
|
||||||
|
>
|
||||||
|
<span class="size-1.5 rounded-full bg-warning"></span>Riesgo moderado
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="mt-4 grid grid-cols-2 gap-2.5">
|
||||||
|
<button class="btn btn-outline btn-block">
|
||||||
|
<i data-lucide="bar-chart-3" class="text-accent"></i><span>Estadísticas</span>
|
||||||
|
</button>
|
||||||
|
<button class="btn btn-outline btn-block">
|
||||||
|
<i data-lucide="share-2" class="text-accent"></i><span>Compartir Link</span>
|
||||||
|
</button>
|
||||||
|
<button class="btn btn-ghost btn-block col-span-2">
|
||||||
|
<i data-lucide="user-plus" class="text-accent"></i
|
||||||
|
><span>Agregar Miembros</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="divide-y divide-border/70 rounded-2xl bg-primary-soft p-4">
|
||||||
|
<div class="flex items-start gap-3 py-3 first:pt-0">
|
||||||
|
<i data-lucide="calendar-clock" class="icon-20 mt-0.5 shrink-0 text-accent"></i>
|
||||||
|
<div class="min-w-0 flex-1">
|
||||||
|
<p class="label-cell">Horario</p>
|
||||||
|
<p class="mt-1 text-base font-semibold leading-snug text-primary">Martes</p>
|
||||||
|
<p class="mt-0.5 text-sm tabular text-foreground">18:00 - 19:30</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="flex items-start gap-3 py-3">
|
||||||
|
<i data-lucide="users" class="icon-20 mt-0.5 shrink-0 text-accent"></i>
|
||||||
|
<div class="min-w-0 flex-1">
|
||||||
|
<p class="label-cell">Miembros & Cupo</p>
|
||||||
|
<p
|
||||||
|
class="mt-1 flex items-baseline text-2xl font-semibold leading-none tracking-tight tabular text-primary"
|
||||||
|
>
|
||||||
|
<span>3</span><span class="text-base font-medium text-foreground/70">/4</span>
|
||||||
|
</p>
|
||||||
|
<div
|
||||||
|
class="mt-2 h-1.5 w-full max-w-[9rem] overflow-hidden rounded-full bg-accent/15"
|
||||||
|
>
|
||||||
|
<div class="h-full w-3/4 rounded-full bg-accent"></div>
|
||||||
|
</div>
|
||||||
|
<p class="mt-1.5 text-sm text-foreground">1 lugar libre · 1 en espera</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="flex items-start gap-3 py-3 last:pb-0">
|
||||||
|
<div
|
||||||
|
class="mt-0.5 flex size-5 shrink-0 items-center justify-center text-sm font-bold leading-none text-accent"
|
||||||
|
>
|
||||||
|
$
|
||||||
|
</div>
|
||||||
|
<div class="min-w-0 flex-1">
|
||||||
|
<p class="label-cell">Cobro</p>
|
||||||
|
<p class="mt-1 text-base font-semibold tabular text-primary">$450.00</p>
|
||||||
|
<p class="mt-0.5 text-sm text-foreground">Vence el día 10 de cada mes</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="rounded-2xl bg-primary-soft p-2">
|
||||||
|
<div class="space-y-2 p-2">
|
||||||
|
<div class="flex flex-col gap-2.5">
|
||||||
|
<div class="flex w-full flex-wrap items-center gap-2">
|
||||||
|
<button class="chip">
|
||||||
|
<i data-lucide="users"></i><span>Miembros</span
|
||||||
|
><span class="pill pill-neutral">3</span>
|
||||||
|
</button>
|
||||||
|
<button class="chip chip-active">
|
||||||
|
<i data-lucide="inbox"></i><span>Pendientes</span
|
||||||
|
><span class="pill pill-on-accent">3</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div class="relative w-full">
|
||||||
|
<i
|
||||||
|
data-lucide="search"
|
||||||
|
class="absolute left-3 top-1/2 -translate-y-1/2 text-foreground/70"
|
||||||
|
></i>
|
||||||
|
<input
|
||||||
|
class="h-11 w-full rounded-lg border border-transparent bg-surface pl-9 pr-3 text-base text-primary shadow-xs placeholder:text-foreground/80 focus:outline-none"
|
||||||
|
placeholder="Buscar por nombre o teléfono..."
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<p class="text-xs leading-relaxed text-foreground/80">
|
||||||
|
Pre-inscripciones que esperan tu aprobación y personas en lista de espera por
|
||||||
|
un cupo libre.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="rounded-lg bg-surface p-1 shadow-xs">
|
||||||
|
<!-- Pre-inscripciones -->
|
||||||
|
<section>
|
||||||
|
<div class="flex items-center gap-2 border-b border-border/70 px-3 pb-2 pt-3">
|
||||||
|
<i data-lucide="user-check" class="shrink-0 text-accent"></i>
|
||||||
|
<h3 class="text-xs font-semibold uppercase tracking-wide text-foreground/70">
|
||||||
|
Pre-inscripciones
|
||||||
|
</h3>
|
||||||
|
<span class="pill pill-warn ml-auto">2</span>
|
||||||
|
</div>
|
||||||
|
<div class="pt-1">
|
||||||
|
<table>
|
||||||
|
<thead>
|
||||||
|
<tr class="border-b border-border/70">
|
||||||
|
<th scope="col" class="w-[46%]">Nombre</th>
|
||||||
|
<th scope="col">Teléfono</th>
|
||||||
|
<th scope="col" class="hidden w-9 px-1 sm:table-cell"
|
||||||
|
><span class="sr-only">Detalle</span></th
|
||||||
|
>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
<tr class="row">
|
||||||
|
<td>
|
||||||
|
<div class="flex min-w-0 items-center gap-2.5">
|
||||||
|
<div class="avatar">J</div>
|
||||||
|
<div class="min-w-0">
|
||||||
|
<p class="truncate font-medium text-primary">Jorge Ramírez</p>
|
||||||
|
<p class="truncate text-xs text-foreground/70">
|
||||||
|
jorge.r@correo.mx
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
<td class="min-w-0 text-foreground/80">
|
||||||
|
<span class="block truncate tabular">55 4567 8901</span>
|
||||||
|
</td>
|
||||||
|
<td class="w-9 px-1 text-foreground/50">
|
||||||
|
<i data-lucide="chevron-right" class="ml-auto block"></i>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<tr class="row">
|
||||||
|
<td>
|
||||||
|
<div class="flex min-w-0 items-center gap-2.5">
|
||||||
|
<div class="avatar">S</div>
|
||||||
|
<div class="min-w-0">
|
||||||
|
<p class="truncate font-medium text-primary">Sofía Torres</p>
|
||||||
|
<p class="truncate text-xs text-foreground/70">
|
||||||
|
sofia.t@correo.mx
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
<td class="min-w-0 text-foreground/80">
|
||||||
|
<span class="block truncate tabular">55 5678 9012</span>
|
||||||
|
</td>
|
||||||
|
<td class="w-9 px-1 text-foreground/50">
|
||||||
|
<i data-lucide="chevron-right" class="ml-auto block"></i>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<!-- Lista de espera -->
|
||||||
|
<section>
|
||||||
|
<div class="flex items-center gap-2 border-b border-border/70 px-3 pb-2 pt-3">
|
||||||
|
<i data-lucide="clock" class="shrink-0 text-accent"></i>
|
||||||
|
<h3 class="text-xs font-semibold uppercase tracking-wide text-foreground/70">
|
||||||
|
Lista de espera
|
||||||
|
</h3>
|
||||||
|
<span class="pill pill-neutral ml-auto">1</span>
|
||||||
|
</div>
|
||||||
|
<div class="pt-1">
|
||||||
|
<table>
|
||||||
|
<thead>
|
||||||
|
<tr class="border-b border-border/70">
|
||||||
|
<th scope="col" class="w-[48%]">Nombre</th>
|
||||||
|
<th scope="col">Teléfono</th>
|
||||||
|
<th scope="col" class="w-9 px-1"
|
||||||
|
><span class="sr-only">Detalle</span></th
|
||||||
|
>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
<tr class="row">
|
||||||
|
<td>
|
||||||
|
<div class="flex min-w-0 items-center gap-2.5">
|
||||||
|
<div class="avatar">D</div>
|
||||||
|
<div class="min-w-0">
|
||||||
|
<p class="truncate font-medium text-primary">Diego Peña</p>
|
||||||
|
<p class="truncate text-xs text-foreground/70">
|
||||||
|
Prefiere horario de 19:00
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
<td class="min-w-0 text-foreground/80">
|
||||||
|
<span class="block truncate tabular">55 6789 0123</span>
|
||||||
|
</td>
|
||||||
|
<td class="w-9 px-1 text-foreground/50">
|
||||||
|
<i data-lucide="chevron-right" class="ml-auto block"></i>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
<p class="mt-3 text-xs leading-relaxed text-foreground/70">
|
||||||
|
“Pendientes” agrupa Pre-inscripciones (pill ámbar = requiere decisión) y Lista de
|
||||||
|
espera como secciones apiladas — sin una tercera pestaña.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- ═══════════════ ESTADO 2 · VACÍO (MIEMBROS) ═══════════════ -->
|
||||||
|
<div class="frame">
|
||||||
|
<p class="mb-2 text-sm font-semibold text-primary">
|
||||||
|
2 · Estado vacío — pestaña “Miembros” (sin miembros ni pre-inscripciones)
|
||||||
|
</p>
|
||||||
|
<div class="screen">
|
||||||
|
<section class="space-y-5">
|
||||||
|
<div>
|
||||||
|
<div class="flex flex-col gap-3">
|
||||||
|
<div class="min-w-0">
|
||||||
|
<h1 class="text-2xl font-bold leading-tight text-primary">Tai Chi Martes</h1>
|
||||||
|
<p class="mt-1.5 text-sm leading-relaxed text-foreground/80">
|
||||||
|
Tai chi para principiantes. Trae ropa cómoda.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div class="flex flex-wrap items-center gap-2">
|
||||||
|
<span
|
||||||
|
class="inline-flex shrink-0 items-center gap-1.5 whitespace-nowrap rounded-full bg-success-soft px-2.5 py-0.5 text-[11px] font-medium text-success"
|
||||||
|
>
|
||||||
|
<span class="size-1.5 rounded-full bg-success"></span>Activo
|
||||||
|
</span>
|
||||||
|
<span
|
||||||
|
class="inline-flex shrink-0 items-center gap-1.5 whitespace-nowrap rounded-full bg-warning-soft px-2.5 py-0.5 text-[11px] font-medium text-warning"
|
||||||
|
>
|
||||||
|
<span class="size-1.5 rounded-full bg-warning"></span>Riesgo moderado
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<!-- Grupo vacío: el header no repite Compartir/Agregar; los lleva el empty state. -->
|
||||||
|
<div class="mt-4 grid grid-cols-2 gap-2.5">
|
||||||
|
<button class="btn btn-outline btn-block">
|
||||||
|
<i data-lucide="bar-chart-3" class="text-accent"></i><span>Estadísticas</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Tarjeta vacía: 0/4 -->
|
||||||
|
<div class="divide-y divide-border/70 rounded-2xl bg-primary-soft p-4">
|
||||||
|
<div class="flex items-start gap-3 py-3 first:pt-0">
|
||||||
|
<i data-lucide="calendar-clock" class="icon-20 mt-0.5 shrink-0 text-accent"></i>
|
||||||
|
<div class="min-w-0 flex-1">
|
||||||
|
<p class="label-cell">Horario</p>
|
||||||
|
<p class="mt-1 text-base font-semibold leading-snug text-primary">Martes</p>
|
||||||
|
<p class="mt-0.5 text-sm tabular text-foreground">18:00 - 19:30</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="flex items-start gap-3 py-3">
|
||||||
|
<i data-lucide="users" class="icon-20 mt-0.5 shrink-0 text-accent"></i>
|
||||||
|
<div class="min-w-0 flex-1">
|
||||||
|
<p class="label-cell">Miembros & Cupo</p>
|
||||||
|
<p
|
||||||
|
class="mt-1 flex items-baseline text-2xl font-semibold leading-none tracking-tight tabular text-primary"
|
||||||
|
>
|
||||||
|
<span>0</span><span class="text-base font-medium text-foreground/70">/4</span>
|
||||||
|
</p>
|
||||||
|
<div
|
||||||
|
class="mt-2 h-1.5 w-full max-w-[9rem] overflow-hidden rounded-full bg-accent/15"
|
||||||
|
>
|
||||||
|
<div class="h-full w-0 rounded-full bg-accent"></div>
|
||||||
|
</div>
|
||||||
|
<p class="mt-1.5 text-sm text-foreground">4 lugares libres</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="flex items-start gap-3 py-3 last:pb-0">
|
||||||
|
<div
|
||||||
|
class="mt-0.5 flex size-5 shrink-0 items-center justify-center text-sm font-bold leading-none text-accent"
|
||||||
|
>
|
||||||
|
$
|
||||||
|
</div>
|
||||||
|
<div class="min-w-0 flex-1">
|
||||||
|
<p class="label-cell">Cobro</p>
|
||||||
|
<p class="mt-1 text-base font-semibold tabular text-primary">$450.00</p>
|
||||||
|
<p class="mt-0.5 text-sm text-foreground">Vence el día 10 de cada mes</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="rounded-2xl bg-primary-soft p-2">
|
||||||
|
<div class="space-y-2 p-2">
|
||||||
|
<div class="flex flex-col gap-2.5">
|
||||||
|
<div class="flex w-full flex-wrap items-center gap-2">
|
||||||
|
<button class="chip chip-active">
|
||||||
|
<i data-lucide="users"></i><span>Miembros</span>
|
||||||
|
</button>
|
||||||
|
<button class="chip">
|
||||||
|
<i data-lucide="inbox"></i><span>Pendientes</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div class="relative w-full">
|
||||||
|
<i
|
||||||
|
data-lucide="search"
|
||||||
|
class="absolute left-3 top-1/2 -translate-y-1/2 text-foreground/70"
|
||||||
|
></i>
|
||||||
|
<input
|
||||||
|
class="h-11 w-full rounded-lg border border-transparent bg-surface pl-9 pr-3 text-base text-primary shadow-xs placeholder:text-foreground/80 focus:outline-none"
|
||||||
|
placeholder="Buscar por nombre o teléfono..."
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<p class="text-xs leading-relaxed text-foreground/80">
|
||||||
|
Listado de todos los miembros incorporados al grupo.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="rounded-lg bg-surface p-1 shadow-xs">
|
||||||
|
<div class="rounded-lg bg-primary-soft/50 px-4 py-10 text-center">
|
||||||
|
<i
|
||||||
|
data-lucide="users"
|
||||||
|
class="icon-40 mx-auto mb-2 block text-foreground/40"
|
||||||
|
></i>
|
||||||
|
<p class="text-sm font-semibold text-primary">
|
||||||
|
Todavía no hay miembros en este grupo
|
||||||
|
</p>
|
||||||
|
<p class="mx-auto mt-1 max-w-sm text-sm text-foreground/80">
|
||||||
|
Puedes compartir el enlace de invitación único o agregar miembros de forma
|
||||||
|
manual o masiva.
|
||||||
|
</p>
|
||||||
|
<div class="mt-4 flex flex-col gap-2.5">
|
||||||
|
<button class="btn btn-outline btn-block">
|
||||||
|
<i data-lucide="share-2"></i><span>Compartir Enlace</span>
|
||||||
|
</button>
|
||||||
|
<button class="btn btn-primary btn-block">
|
||||||
|
<i data-lucide="plus"></i><span>Agregar Miembros</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
<p class="mt-3 text-xs leading-relaxed text-foreground/70">
|
||||||
|
Exactamente <strong class="text-primary">un primario</strong>: “Agregar Miembros” en el
|
||||||
|
empty state. El header no repite Compartir/Agregar —solo queda Estadísticas—, así que
|
||||||
|
no compiten dos CTA idénticos.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- ═══════════════ ESTADO 2 · VACÍO (PENDIENTES) ═══════════════ -->
|
||||||
|
<div class="frame">
|
||||||
|
<p class="mb-2 text-sm font-semibold text-primary">
|
||||||
|
2 · Estado vacío — pestaña “Pendientes”
|
||||||
|
</p>
|
||||||
|
<div class="screen">
|
||||||
|
<section class="space-y-5">
|
||||||
|
<div>
|
||||||
|
<div class="flex flex-col gap-3">
|
||||||
|
<div class="min-w-0">
|
||||||
|
<h1 class="text-2xl font-bold leading-tight text-primary">Tai Chi Martes</h1>
|
||||||
|
<p class="mt-1.5 text-sm leading-relaxed text-foreground/80">
|
||||||
|
Tai chi para principiantes. Trae ropa cómoda.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div class="flex flex-wrap items-center gap-2">
|
||||||
|
<span
|
||||||
|
class="inline-flex shrink-0 items-center gap-1.5 whitespace-nowrap rounded-full bg-success-soft px-2.5 py-0.5 text-[11px] font-medium text-success"
|
||||||
|
>
|
||||||
|
<span class="size-1.5 rounded-full bg-success"></span>Activo
|
||||||
|
</span>
|
||||||
|
<span
|
||||||
|
class="inline-flex shrink-0 items-center gap-1.5 whitespace-nowrap rounded-full bg-warning-soft px-2.5 py-0.5 text-[11px] font-medium text-warning"
|
||||||
|
>
|
||||||
|
<span class="size-1.5 rounded-full bg-warning"></span>Riesgo moderado
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<!-- Grupo vacío: el header no repite Compartir/Agregar; los lleva el empty state. -->
|
||||||
|
<div class="mt-4 grid grid-cols-2 gap-2.5">
|
||||||
|
<button class="btn btn-outline btn-block">
|
||||||
|
<i data-lucide="bar-chart-3" class="text-accent"></i><span>Estadísticas</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="divide-y divide-border/70 rounded-2xl bg-primary-soft p-4">
|
||||||
|
<div class="flex items-start gap-3 py-3 first:pt-0">
|
||||||
|
<i data-lucide="calendar-clock" class="icon-20 mt-0.5 shrink-0 text-accent"></i>
|
||||||
|
<div class="min-w-0 flex-1">
|
||||||
|
<p class="label-cell">Horario</p>
|
||||||
|
<p class="mt-1 text-base font-semibold leading-snug text-primary">Martes</p>
|
||||||
|
<p class="mt-0.5 text-sm tabular text-foreground">18:00 - 19:30</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="flex items-start gap-3 py-3">
|
||||||
|
<i data-lucide="users" class="icon-20 mt-0.5 shrink-0 text-accent"></i>
|
||||||
|
<div class="min-w-0 flex-1">
|
||||||
|
<p class="label-cell">Miembros & Cupo</p>
|
||||||
|
<p
|
||||||
|
class="mt-1 flex items-baseline text-2xl font-semibold leading-none tracking-tight tabular text-primary"
|
||||||
|
>
|
||||||
|
<span>0</span><span class="text-base font-medium text-foreground/70">/4</span>
|
||||||
|
</p>
|
||||||
|
<div
|
||||||
|
class="mt-2 h-1.5 w-full max-w-[9rem] overflow-hidden rounded-full bg-accent/15"
|
||||||
|
>
|
||||||
|
<div class="h-full w-0 rounded-full bg-accent"></div>
|
||||||
|
</div>
|
||||||
|
<p class="mt-1.5 text-sm text-foreground">4 lugares libres</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="flex items-start gap-3 py-3 last:pb-0">
|
||||||
|
<div
|
||||||
|
class="mt-0.5 flex size-5 shrink-0 items-center justify-center text-sm font-bold leading-none text-accent"
|
||||||
|
>
|
||||||
|
$
|
||||||
|
</div>
|
||||||
|
<div class="min-w-0 flex-1">
|
||||||
|
<p class="label-cell">Cobro</p>
|
||||||
|
<p class="mt-1 text-base font-semibold tabular text-primary">$450.00</p>
|
||||||
|
<p class="mt-0.5 text-sm text-foreground">Vence el día 10 de cada mes</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="rounded-2xl bg-primary-soft p-2">
|
||||||
|
<div class="space-y-2 p-2">
|
||||||
|
<div class="flex flex-col gap-2.5">
|
||||||
|
<div class="flex w-full flex-wrap items-center gap-2">
|
||||||
|
<button class="chip">
|
||||||
|
<i data-lucide="users"></i><span>Miembros</span>
|
||||||
|
</button>
|
||||||
|
<button class="chip chip-active">
|
||||||
|
<i data-lucide="inbox"></i><span>Pendientes</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div class="relative w-full">
|
||||||
|
<i
|
||||||
|
data-lucide="search"
|
||||||
|
class="absolute left-3 top-1/2 -translate-y-1/2 text-foreground/70"
|
||||||
|
></i>
|
||||||
|
<input
|
||||||
|
class="h-11 w-full rounded-lg border border-transparent bg-surface pl-9 pr-3 text-base text-primary shadow-xs placeholder:text-foreground/80 focus:outline-none"
|
||||||
|
placeholder="Buscar por nombre o teléfono..."
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<p class="text-xs leading-relaxed text-foreground/80">
|
||||||
|
Pre-inscripciones que esperan tu aprobación y personas en lista de espera por
|
||||||
|
un cupo libre.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="rounded-lg bg-surface p-1 shadow-xs">
|
||||||
|
<div class="rounded-lg bg-primary-soft/50 px-4 py-10 text-center">
|
||||||
|
<i
|
||||||
|
data-lucide="inbox"
|
||||||
|
class="icon-40 mx-auto mb-2 block text-foreground/40"
|
||||||
|
></i>
|
||||||
|
<p class="text-sm font-semibold text-primary">No hay pendientes</p>
|
||||||
|
<p class="mx-auto mt-1 max-w-sm text-sm text-foreground/80">
|
||||||
|
Las pre-inscripciones que lleguen por el enlace compartido y las personas en
|
||||||
|
lista de espera aparecerán aquí para que las revises.
|
||||||
|
</p>
|
||||||
|
<div class="mt-4 flex justify-center">
|
||||||
|
<button class="btn btn-primary btn-block">
|
||||||
|
<i data-lucide="share-2"></i><span>Compartir Enlace</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
<p class="mt-3 text-xs leading-relaxed text-foreground/70">
|
||||||
|
Cada pestaña vacía explica qué aparecerá ahí y ofrece
|
||||||
|
<strong class="text-primary">una</strong> acción primaria concreta.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<footer class="mt-10 max-w-3xl border-t border-border pt-6 text-xs leading-relaxed text-foreground/70">
|
||||||
|
<p>
|
||||||
|
<strong class="text-primary">Jerarquía de la tarjeta:</strong> label 11px · dato 16px ·
|
||||||
|
cupo 24px (único hero). Orden de lectura: Horario → Cupo → Cobro.
|
||||||
|
<strong class="text-primary">Objetivos táctiles:</strong> chips, botones y buscador a
|
||||||
|
44px; filas de tabla ~56px. <strong class="text-primary">Badges</strong> “Activo” y
|
||||||
|
“Riesgo moderado” conservados.
|
||||||
|
</p>
|
||||||
|
</footer>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
window.addEventListener('load', () => {
|
||||||
|
if (window.lucide) window.lucide.createIcons();
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
BIN
.interface-design/group-detail-redesign.png
Normal file
BIN
.interface-design/group-detail-redesign.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 314 KiB |
136
.interface-design/system.md
Normal file
136
.interface-design/system.md
Normal file
@@ -0,0 +1,136 @@
|
|||||||
|
# Gruperly — sistema de interfaz (apps/web)
|
||||||
|
|
||||||
|
Aplicado en el rediseño de `/groups/$groupId` (sept 2026). Fuente de verdad de tokens:
|
||||||
|
`apps/web/src/index.css` (`@theme`). Ojo: `stack.md` trae tokens viejos (accent `#1e90ff`);
|
||||||
|
el accent real es **`#2544ea`**.
|
||||||
|
|
||||||
|
## Dirección y sensación
|
||||||
|
|
||||||
|
Herramienta diaria de un profesor/organizador que abre la pantalla para responder tres
|
||||||
|
preguntas: ¿quién está? ¿quién falta? ¿qué cobro?. Sensación: **calma operativa** — densa
|
||||||
|
pero escaneable, nada grita salvo lo que requiere decisión. Tema oscuro slate + un solo
|
||||||
|
accent azul; copy en español, verbos en infinitivo.
|
||||||
|
|
||||||
|
## Profundidad y espaciado
|
||||||
|
|
||||||
|
- **Estrategia de depth**: cambios de superficie + bordes de baja opacidad. Sombras solo
|
||||||
|
`shadow-xs` en tarjetas/paneles. Nada de drop shadows marcados.
|
||||||
|
- **Unidad base 4px.** Densidad: padding de componente 8–16px, separación entre bloques
|
||||||
|
`space-y-5 sm:space-y-6` (20/24px).
|
||||||
|
- **Radius**: default `rounded-xl` (0.75rem). Concéntrico: contenedor `rounded-2xl` (16px) +
|
||||||
|
padding 8px → interior `rounded-lg` (8px). Chips y pills: `rounded-full`.
|
||||||
|
|
||||||
|
## Jerarquía tipográfica (ratio ~1.25)
|
||||||
|
|
||||||
|
| nivel | valor | uso |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| label | 11px semibold uppercase `tracking-wide` `text-foreground/70` | títulos de celda/sección |
|
||||||
|
| body | 14px (`text-sm`) `text-foreground/80` | descripciones, filas |
|
||||||
|
| value | 16px semibold `text-primary` (`text-base`) | dato principal de una celda |
|
||||||
|
| hero | 24px semibold `tracking-tight` `tabular-nums` | **solo uno por bloque** (hoy: el cupo `1/4`) |
|
||||||
|
| micro | 10–12px | pills de conteo (`text-[10px] font-bold`), captions |
|
||||||
|
|
||||||
|
- Cuatro niveles de color de texto: `text-primary` → `text-foreground` → `/70` → `/50`.
|
||||||
|
- **Todo dato numérico lleva `tabular-nums`** (contadores, teléfonos, precios, fechas).
|
||||||
|
|
||||||
|
## Patrón focal
|
||||||
|
|
||||||
|
**Un punto focal por bloque y por estado.** La tarjeta de info manda con el cupo; el header
|
||||||
|
de grupo no tiene ningún `primary` (Estadísticas y Compartir son `outline` y **Agregar es
|
||||||
|
`ghost`**: con miembros en el grupo deja de competir con el listado) y el `primary` vive en
|
||||||
|
el empty state de la vista que lo explica. Así nunca hay dos elementos azules compitiendo.
|
||||||
|
|
||||||
|
**Objetivos táctiles ≥ 44px** en esta pantalla: chips (`min-h-11`), botones del header y del
|
||||||
|
empty state (`h-11`), buscador (`h-11`). Filas de tabla ~56px.
|
||||||
|
|
||||||
|
Preview visual de los dos estados (con miembros + vacío):
|
||||||
|
`group-detail-redesign.html` / `.png` (mismo directorio).
|
||||||
|
|
||||||
|
## Componentes (valores exactos)
|
||||||
|
|
||||||
|
### Chip de sección — `detail/SectionChips.tsx`
|
||||||
|
- Contenedor: `flex w-full flex-wrap items-center gap-2` + `role="group"` (no tablist).
|
||||||
|
- Chip: `min-h-11 rounded-full border px-3.5 text-xs font-semibold gap-1.5`,
|
||||||
|
activo `border-transparent bg-accent text-on-accent shadow-xs`,
|
||||||
|
inactivo `border-border bg-surface text-foreground/80 hover:border-accent/40 hover:bg-primary-soft hover:text-primary`,
|
||||||
|
focus `ring-2 ring-accent ring-offset-2 ring-offset-primary-soft`.
|
||||||
|
- Pill de conteo: `px-1.5 py-0.5 text-[10px] font-bold leading-none tabular-nums`;
|
||||||
|
**oculto si el conteo es 0**; atención `bg-warning-soft text-warning`;
|
||||||
|
neutro `bg-primary-soft text-foreground/60`; sobre chip activo `bg-on-accent/25 text-on-accent`.
|
||||||
|
- `aria-pressed` en cada chip. Envuelve en 1–3 filas según ancho: nunca recorta.
|
||||||
|
|
||||||
|
### Encabezado de pantalla — `components/layout/LargeTitle.tsx`
|
||||||
|
- Patrón iOS: título grande que al scrollear se desliza debajo de una barra de
|
||||||
|
navegación que se opaca y recibe el título en versión chica.
|
||||||
|
- Caja de la barra: `h-14` (56px) `sticky top-0 z-40` + `bg-background/80 backdrop-blur-md`
|
||||||
|
y `border-b`, con opacidad ligada al progreso. `h-14` tiene que coincidir con
|
||||||
|
`BAR_HEIGHT` de `hooks/useLargeTitleCollapse.ts`.
|
||||||
|
- Título grande: `text-[2.125rem] leading-[1.1] tracking-tight`, `sm:text-[2.5rem]`,
|
||||||
|
con `text-balance` para nombres largos.
|
||||||
|
- Título de la barra: `text-base font-semibold`, `truncate`, `aria-hidden` (es
|
||||||
|
duplicado visual del `h1`).
|
||||||
|
- El progreso sale de la posición del título en cada frame (`rAF` agrupa los
|
||||||
|
eventos de scroll), no de una transición: por eso se siente pegado al dedo. El
|
||||||
|
estado vive dentro de `LargeTitle` para que `children` no se re-renderice en
|
||||||
|
cada frame.
|
||||||
|
- La barra se monta en una caja que el layout pone arriba de `<main>`
|
||||||
|
(`ImmersiveBarHost`): un `sticky` está limitado a la caja de su padre, y el
|
||||||
|
padre natural (el bloque del feature) es corto.
|
||||||
|
- Sólo en tres rutas: `isImmersiveRoute` (`lib/immersive-routes.ts`): ficha de
|
||||||
|
grupo, sus estadísticas y la asistencia. Ahí no se renderiza el header global
|
||||||
|
y el sidebar pasa a `top-0 h-dvh`.
|
||||||
|
- El link "volver" vive en la barra como `leading` y sigue `hidden lg:inline-flex`.
|
||||||
|
- En las pantallas de un grupo (ficha y estadísticas) el título grande es **el
|
||||||
|
nombre del grupo**, no el de la sección: la barra colapsada tiene que decir
|
||||||
|
sobre qué se está mirando. "Estadísticas" va como subtítulo (label 11px
|
||||||
|
uppercase + body), no como título.
|
||||||
|
|
||||||
|
### Acciones de cabecera — `detail/GroupHeader.tsx`
|
||||||
|
- Título, badges y descripción los dibuja `LargeTitle`; las acciones quedan
|
||||||
|
debajo, en el flujo normal.
|
||||||
|
- Estadísticas y Compartir: `variant="outline"` con icono `text-accent`; **Agregar Miembros:
|
||||||
|
`variant="ghost"`** (disponible, no dominante). Todas `h-11` (44px).
|
||||||
|
- **Grupo vacío** (0 miembros + 0 pendientes): el header muestra **solo Estadísticas** —
|
||||||
|
Compartir y Agregar los ofrecen los empty states, que ya llevan su primario explicado.
|
||||||
|
- Móvil: `grid grid-cols-2 gap-2.5` (tercera acción `col-span-2`); `sm+`: `flex justify-end`.
|
||||||
|
- Badges de estado: `rounded-full px-2.5 py-0.5 text-[11px]` + punto `size-1.5`,
|
||||||
|
en su propia fila bajo el título grande (`mt-3`) y se van al colapsar la barra.
|
||||||
|
|
||||||
|
### Tarjeta de info — `detail/GroupInfoCard.tsx`
|
||||||
|
- Contenedor: `rounded-2xl bg-primary-soft p-4 sm:p-5` + `divide-y divide-border/70` en móvil,
|
||||||
|
`md:grid md:grid-cols-3 md:divide-x md:divide-y-0`.
|
||||||
|
- Celda: `flex items-start gap-3 py-3 first:pt-0 last:pb-0 md:py-0` + `md:pr-6` / `md:px-6` / `md:pl-6`.
|
||||||
|
- Barra de cupo: `h-1.5 max-w-[9rem] rounded-full bg-accent/15`, fill `bg-accent`
|
||||||
|
(o `bg-warning` si `total >= capacity`), `transition-[width] duration-300 ease-out`,
|
||||||
|
con `role="progressbar"` + `aria-valuetext`.
|
||||||
|
|
||||||
|
### Sección de listados — `detail/MembersWaitlistSection.tsx`
|
||||||
|
- Externo `rounded-2xl bg-primary-soft p-2`; interno `space-y-2 p-2 sm:p-3`.
|
||||||
|
- Panel de contenido: `rounded-lg bg-surface p-1 shadow-xs sm:p-2`.
|
||||||
|
- Fila header: chips + buscador (`sm:w-72 lg:shrink-0`), apilados hasta `lg`.
|
||||||
|
- Sub-encabezado de sección apilada (`PendingView.tsx`):
|
||||||
|
`flex items-center gap-2 border-b border-border/70 px-3 pb-2 pt-3`,
|
||||||
|
título label 11px, pill a la derecha con `ml-auto`; tabla envuelta en `pt-1`.
|
||||||
|
|
||||||
|
### Empty state
|
||||||
|
`rounded-lg bg-primary-soft/50 px-4 py-10 text-center` · icono `size-10 text-foreground/40` ·
|
||||||
|
título `text-sm font-semibold text-primary` · cuerpo `max-w-sm text-sm text-foreground/80` ·
|
||||||
|
acciones: **una** `primary` + el resto `outline`, todas `h-11`.
|
||||||
|
|
||||||
|
### Tablas — `detail/*Table.tsx`
|
||||||
|
`table-fixed text-sm` · nombre `w-[48%]` · chevron `w-9` · filas `px-3 py-2.5`
|
||||||
|
con `border-b border-border/70 last:border-b-0 hover:bg-primary-soft/60` ·
|
||||||
|
avatar `size-9 rounded-full bg-accent/10 text-xs font-semibold text-accent` ·
|
||||||
|
columnas secundarias con `hidden sm:table-cell` (en móvil manda el teléfono).
|
||||||
|
|
||||||
|
### Botón — `components/ui/button.tsx`
|
||||||
|
`rounded-xl font-medium h-10 px-4 text-sm` · `active:scale-[0.96] motion-reduce:active:scale-100` ·
|
||||||
|
focus `ring-2 ring-accent` · variantes `primary` (`bg-accent`/`hover:bg-accent-strong`),
|
||||||
|
`outline`, `ghost`.
|
||||||
|
|
||||||
|
## Convenciones que sostienen el sistema
|
||||||
|
|
||||||
|
- Sin Radix/shadcn instalado: primitivos propios en `components/ui/` + `cn()` (clsx + tailwind-merge).
|
||||||
|
- Sin botón "volver" en mobile: `hidden lg:inline-flex`.
|
||||||
|
- Elementos fijos abajo: `env(safe-area-inset-bottom)` en el padding.
|
||||||
|
- Los controles nuevos deben pasar el squint test: si dos cosas brillan, sobra una.
|
||||||
54
AGENTS.md
54
AGENTS.md
@@ -21,6 +21,7 @@ bun run lint:fix # biome check --write
|
|||||||
bun --filter @gruperly/backend typecheck # verificación de un solo paquete
|
bun --filter @gruperly/backend typecheck # verificación de un solo paquete
|
||||||
bun --filter @gruperly/backend test # bun test (backend)
|
bun --filter @gruperly/backend test # bun test (backend)
|
||||||
bun --filter @gruperly/backend db:* # db:generate / db:migrate / db:push / db:studio
|
bun --filter @gruperly/backend db:* # db:generate / db:migrate / db:push / db:studio
|
||||||
|
bun --filter @gruperly/web icons # regenera los iconos PWA de apps/web/public/ (sharp)
|
||||||
```
|
```
|
||||||
|
|
||||||
## Estructura y fronteras
|
## Estructura y fronteras
|
||||||
@@ -30,30 +31,71 @@ bun --filter @gruperly/backend db:* # db:generate / db:migrate / db:push
|
|||||||
- `src/modules/<modulo>/` — por módulo: `index.ts`, `routes.ts` y `features/<accion>/{route,use-case}.ts`. **Patrón**: el route valida (`validate.query/json`) y delega en un use-case que devuelve `Result<T, ProblemDetails>` (`ok`/`err` desde `@gruperly/shared`); el route responde con `resultJson` (o `problemJson`).
|
- `src/modules/<modulo>/` — por módulo: `index.ts`, `routes.ts` y `features/<accion>/{route,use-case}.ts`. **Patrón**: el route valida (`validate.query/json`) y delega en un use-case que devuelve `Result<T, ProblemDetails>` (`ok`/`err` desde `@gruperly/shared`); el route responde con `resultJson` (o `problemJson`).
|
||||||
- `src/lib/` — `prisma.ts` (`getPrismaClient`, proxy `default` y clase `UnitOfWork`), `pagination.ts` (offset/metadata), `email.ts`, `error-message.ts`.
|
- `src/lib/` — `prisma.ts` (`getPrismaClient`, proxy `default` y clase `UnitOfWork`), `pagination.ts` (offset/metadata), `email.ts`, `error-message.ts`.
|
||||||
- `src/logger.ts` — pino + pino-pretty.
|
- `src/logger.ts` — pino + pino-pretty.
|
||||||
- Módulos existentes: `health-check`, `auth` (**Better Auth 1.7.2 público**, montado en `/api/v1/auth` vía `basePath` del server; cookie de sesión con `path: "/"`), `groups`, `students`, `payments`, `waitlist` (listados paginados `{ data, pagination }`).
|
- Módulos existentes: `mp` (OAuth de Mercado Pago, Authorization Code + PKCE; `apps/backend/src/modules/mp/`), `health-check`, `auth` (**Better Auth 1.7.2 público**, montado en `/api/v1/auth` vía `basePath` del server; cookie de sesión con `path: "/"`; recuperar contraseña en la web vía `/forgot-password` → email → `/reset-password?token=…`: el `redirectTo` de `requestPasswordReset` tiene que ser **absoluto** a la web, uno relativo Better Auth lo resuelve contra la URL de la API; `revokeSessionsOnPasswordReset` cierra todas las sesiones), `groups`, `attendees`, `payments`, `waitlist` (listados paginados `{ data, pagination }`). `group-waitlist` y `group-preregistrations` no se montan en `app.ts`: se enganchan en `modules/groups/routes.ts`. El link compartido (`Group.inviteToken`, público en `/api/v1/invitations`) **no** da de alta en `attendees`: crea una `GroupPreRegistration` (PENDING) que el dueño aprueba (`POST /groups/:gid/preregistrations/:id/approve` → attendee si hay cupo, si no waitlist) o rechaza. `payments` (links de Checkout Pro por alumno y período): `GET /api/v1/payments` (get-all) y `POST /api/v1/payments/:id/renew` se montan en `modules/payments/routes.ts`; **el batch** (`POST /groups/:gid/payments/batch`) se engancha en `modules/groups/routes.ts` porque nace del grupo. Los jobs de reconciliación por polling (`ReconcilePayments`, `*/15 * * * *`) y overdue (`MarkOverduePayments`, `4 4 * * *` UTC) viven en `modules/payments/jobs/` y los arranca `startPaymentJobs()` desde `server.ts`. `whatsapp` (mensajes automáticos semanales: recordatorio de pago y reenganche; `WEEKLY_MESSAGES_CRON` `0 13 * * 1` UTC y `SyncKapsoTemplates` `*/30` solo con Kapso, arrancados por `startWhatsappJobs()`; `PATCH /groups/:gid/automations` se engancha en `modules/groups/routes.ts`; guía en `docs/whatsapp.md`). `billing` (plan de Gruperly: Free/Pro con Suscripciones de MP; `startBillingJobs()` y `planReadOnlyMiddleware` en `app.ts`; guía en `docs/billing.md`). `admin` (backoffice de solo lectura de las cuentas de profesores: acceso por allowlist `ADMIN_EMAILS`, `GET /admin/me` abierto a cualquier sesión y `adminOnlyMiddleware` en `/admin/accounts*`; el filtro por plan usa `proSubscriptionWhere`, que tiene que seguir a `resolvePlan`). En la web vive en `/admin`, colgado de la raíz y **no** de `_authenticated` (un admin no pasa por el onboarding); el link aparece en `UserMenu` solo para admins. `attention` ("Requiere atención": `GET /attention` devuelve todos los miembros ACTIVE por grupo con sus alertas, teléfono en E.164 y cuotas `OVERDUE`; `POST /attention/:attendeeId/resolve` guarda `{ tipo, firma }` en `attendee_alert_resolutions`, una fila por alumno y tipo: la alerta vuelve sola cuando cambia la firma —última falta o ids de cuotas vencidas—). Las alertas salen de `computeStudentAlerts` (`packages/shared/src/lib/student-alerts.ts`), que reusa la **única** regla de asistencia (`ATTENDANCE_RISK_RULES` en `attendance-risk.ts`: urgente = 3 seguidas o 4 de las últimas 6 clases marcadas; a vigilar = 2 de las últimas 4) y suma la de cuotas (`STUDENT_ALERT_RULES`: 1 vencida vigilar, 2+ urgente). Inicio, la ficha de grupo y el job de reenganche usan la misma regla.
|
||||||
- `apps/web` — Frontend React 19 + Vite + Tailwind v4. Entry `src/main.tsx` → `src/router.tsx`. Puerto **6173** (`vite.config.ts`). Auth client con `basePath: '/api/v1/auth'` (`src/lib/auth-client.ts`); el backend llama a `/api/v1/groups/from-organization` (`src/routes/organizations.tsx`).
|
- `student-portal` (API del **alumno o tutor**, `/api/v1/student-portal/*`) y `student-access` (su lado profe: invitar/estado en `/groups/:gid/attendees/:aid/student-access`, faltas avisadas en `/groups/:gid/absence-notices`, enganchado en `modules/groups/routes.ts`). La revisión de pagos informados (`/payments/reported*`) y los datos para transferir (`/payments/transfer-details`) viven en `modules/payments`. Guía en el gotcha **App de alumnos**.
|
||||||
|
- `apps/web` — Frontend React 19 + Vite + Tailwind v4. Entry `src/main.tsx` → `src/router.tsx`. Puerto **6173** (`vite.config.ts`). Auth client con `basePath: '/api/v1/auth'` (`src/lib/auth-client.ts`). Es una **PWA instalable** (`vite-plugin-pwa` + Workbox, config en `vite.config.ts`); el registro del SW y el banner de instalación viven en `src/features/pwa/` (`PwaProvider`, montado en `main.tsx` dentro de `ToastProvider`).
|
||||||
- `packages/shared` — Esquemas Zod (v3.24) + tipos + `Result` + Problem Details. **Se consume como TS fuente directo** (`exports` apunta a `src/index.ts`, sin build previo); se resuelve vía el symlink de bun en `node_modules` (`@gruperly/shared` no está en `paths` de los tsconfig). El `paths` de los tsconfig solo mapea `@/*` → `src/*` y `@generated/*` → `generated/*`.
|
- `packages/shared` — Esquemas Zod (v3.24) + tipos + `Result` + Problem Details. **Se consume como TS fuente directo** (`exports` apunta a `src/index.ts`, sin build previo); se resuelve vía el symlink de bun en `node_modules` (`@gruperly/shared` no está en `paths` de los tsconfig). El `paths` de los tsconfig solo mapea `@/*` → `src/*` y `@generated/*` → `generated/*`.
|
||||||
- `packages/config` — `tsconfig.base.json`; tsconfigs lo extienden con `"extends": "@gruperly/config/tsconfig.base.json"` (por eso `@gruperly/config` es devDependency de cada paquete).
|
- `packages/config` — `tsconfig.base.json`; tsconfigs lo extienden con `"extends": "@gruperly/config/tsconfig.base.json"` (por eso `@gruperly/config` es devDependency de cada paquete).
|
||||||
|
|
||||||
## Gotchas operativos
|
## Gotchas operativos
|
||||||
|
|
||||||
|
- **Mercado Pago (`modules/mp/`)**: el paso "Cobros" del onboarding es **salteable** y no hay ningún gate `payment_not_setup`: sin cuenta vinculada se puede crear el grupo igual. `GET /mp/connect` devuelve `{ authorizationUrl }` (el navegador navega; no se puede hacer con `fetch`), `GET /mp/callback` **siempre** responde 302 (a `/onboarding` o `/settings` con `?mp=success` / `?mp=error&reason=…`), `GET /mp/status` da `none|active|requires_reauth` (un `REVOKED` se reporta como `none`) y `DELETE /mp/connect` vacía los tokens sin borrar la fila, para que la cuenta de MP quede reservada al mismo profesor. Ojo con cuatro cosas: (1) `MpCallbackQuerySchema` es `z.object` y no `strictObject` a propósito —MP manda `error_description` y otros campos, y un esquema estricto devolvía un 400 JSON en el navegador en vez del redirect—; (2) los tokens se cifran con AES-256-GCM (`sealToken`/`openToken`, payload `v1:iv:tag:ciphertext`) y `TOKEN_ENCRYPTION_KEY` tiene que decodificar a 32 bytes; cambiar la clave deja ilegibles las cuentas existentes; (3) el `state` (10 min, en `mp_oauth_states`) se **quema antes** de hablar con MP: `deleteMany().count === 0` significa replay; (4) el panel de MP exige **HTTPS** en la Redirect URL (rechaza `http://localhost`), así que en local el callback pasa por un túnel (`ngrok http --url=https://TU-DOMINIO.ngrok-free.app 4000`, dominio fijo por cuenta; los quick tunnels de cloudflared cambian de URL en cada arranque) —`MP_REDIRECT_URI` y el panel deben coincidir carácter a carácter—, y las credenciales en dev son las de **producción** de la app (no existe OAuth sandbox; el OAuth solo vincula y no mueve dinero). El cron de renovación (`17 3 * * *` UTC, lotes de 20 con `FOR UPDATE SKIP LOCKED`) solo marca `REQUIRES_REAUTH` con `invalid_grant`, nunca por un 5xx. Nunca loguear tokens, `code`, `code_verifier` ni `client_secret`.
|
||||||
- **Prisma 7**: requiere `apps/backend/.env` (con `DATABASE_URL`). El CLI lee `apps/backend/prisma.config.ts` (datasource `url` vía `env('DATABASE_URL')`); el schema es **multi-archivo**: `prisma/schema.prisma` (generator con output `../generated/prisma` + datasource simple) que incluye `prisma/models/*.prisma` (`auth.prisma`, `domain.prisma`). El cliente se regenra con `bun --filter @gruperly/backend db:generate` y se importa desde `@generated/prisma/client` (alias → `generated/prisma`, gitignoreado); se instancia con `@prisma/adapter-pg`. Sin `.env` el CLI falla; copia desde `apps/backend/.env.example`.
|
- **Prisma 7**: requiere `apps/backend/.env` (con `DATABASE_URL`). El CLI lee `apps/backend/prisma.config.ts` (datasource `url` vía `env('DATABASE_URL')`); el schema es **multi-archivo**: `prisma/schema.prisma` (generator con output `../generated/prisma` + datasource simple) que incluye `prisma/models/*.prisma` (`auth.prisma`, `domain.prisma`). El cliente se regenra con `bun --filter @gruperly/backend db:generate` y se importa desde `@generated/prisma/client` (alias → `generated/prisma`, gitignoreado); se instancia con `@prisma/adapter-pg`. Sin `.env` el CLI falla; copia desde `apps/backend/.env.example`.
|
||||||
- **Tests (bun test)**: viven en `apps/backend/test/`. Mockean el módulo `@/lib/prisma` con `mock.module` (si el mock se comparte como `tx`, declara la const fuera del mock; `vi` de `bun:test` NO tiene `vi.mocked`). Los use-cases ponen el db mockable en `constructor(deps)`. Los tests NO pasan por `sessionAuthMiddleware`; si el route lee `c.get('user')`, inyecta un usuario con un middleware en el harness.
|
- **Tests (bun test)**: viven en `apps/backend/test/`. Mockean el módulo `@/lib/prisma` con `mock.module` (si el mock se comparte como `tx`, declara la const fuera del mock; `vi` de `bun:test` NO tiene `vi.mocked`). Los use-cases ponen el db mockable en `constructor(deps)`. Los tests NO pasan por `sessionAuthMiddleware`; si el route lee `c.get('user')`, inyecta un usuario con un middleware en el harness.
|
||||||
|
- **Payments (`modules/payments/`)**: el batch crea primero las filas `Payment` (fuente de verdad) y después una preferencia de Checkout Pro por alumno; una preferencia que falla deja su fila `PENDING` sin link y el profesor lo reintenta con `POST /payments/:id/renew` (idempotente). La moneda sale de `user.country` (onboarding, default `AR` → `ARS`; `shared/schemas/country.ts`). No hay webhook: la reconciliación es por polling (`GET /v1/payments/search` con `external_reference`, marca `PAID` solo si `status === 'approved'`), y `CreateFirstGroupSchema` reusa el form de grupo web, por eso `country` lleva `.default(DEFAULT_COUNTRY)` (un POST de grupo sin `country` daba 400). Cuidado en los tests: los `mock.module('@/modules/mp'…)'` se filtran entre archivos de test en la suite completa (workers reutilizados) — no mockear los namespaces de MP: inyectar fakes por constructor deps (`getToken`, `createPreference`, `search`) o usar los módulos reales. `vi.clearAllMocks()` no borra implementaciones (`mockResolvedValue` persiste), los valores `…Once` se consumen antes que la implementación default, y el problema real de "no conectado" es `mpNotConnectedProblem()` → **409 conflict**.
|
||||||
|
- **WhatsApp (`modules/whatsapp/`)**: proveedor intercambiable detrás del puerto `MessagingProvider` (`providers/messaging-provider.ts`); OpenWA (MVP: QR o código por número de teléfono —`requestPairingCode`, opcional en el puerto—, texto libre, no oficial) o Kapso (Meta: setup link, templates), elegido con `WHATSAPP_PROVIDER`. Ojo con esto:
|
||||||
|
1. El dominio, los jobs y la UI **nunca** importan un adaptador: todo pasa por `getMessagingProvider()`. Lo específico de un proveedor vive solo en `providers/<nombre>/`.
|
||||||
|
2. `POST /whatsapp/webhooks/openwa|kapso` es **público** (está en `isPublicApiRequest`). Se autentica con HMAC-SHA256 sobre el **raw body** (`c.req.text()`), deduplica en `whatsapp_webhook_events` y, si aplicar el evento falla, borra la clave de deduplicación para que el reintento del proveedor entre.
|
||||||
|
3. El callback de Kapso no confía en la query: exige el `setupLinkId` guardado y que Kapso confirme que el número es del customer del profesor.
|
||||||
|
4. La idempotencia de los envíos es el `@@unique([kind, attendeeId, periodKey])` de `outbound_messages` (semana ISO): la fila se crea **antes** de llamar al proveedor y su id es el `Idempotency-Key`.
|
||||||
|
5. Los teléfonos se guardan en formato nacional: el envío pasa por `toWhatsappE164` (shared) con el país del profesor.
|
||||||
|
6. Sin SDK de Kapso (trae su propio zod): `fetch` plano.
|
||||||
|
7. El sandbox de Kapso no soporta templates.
|
||||||
|
8. OpenWA se instala **aparte** (no está en `docker-compose.yml`); la API le habla por `OPENWA_API_URL`. Su guard SSRF rechaza webhooks a hosts internos que no estén en `SSRF_ALLOWED_HOSTS`.
|
||||||
|
9. Al cambiar `WHATSAPP_PROVIDER`, las cuentas del proveedor anterior quedan `requires_reconnect`.
|
||||||
|
10. Nunca loguear API keys, secretos ni cuerpos de pedidos, que llevan teléfonos.
|
||||||
|
11. En los tests, los proveedores se inyectan por constructor y `fetch` va en `deps`, sin `mock.module`.
|
||||||
|
- **Billing (`modules/billing/`)**: es lo que el **profesor le paga a Gruperly** (Pro mensual), no lo que pagan los alumnos. Ojo con esto:
|
||||||
|
1. Proveedor intercambiable detrás del puerto `BillingProvider` (`providers/billing-provider.ts`, mismo patrón que WhatsApp): Mercado Pago (`/preapproval`) en **AR** y Stripe (Checkout en modo suscripción, `fetch` plano sin SDK) en el resto; el mapa es `BILLING_PROVIDER_BY_COUNTRY` (shared). Los use-cases, `SyncSubscription` y el job **nunca** importan un adaptador: piden `getBillingProvider(id)` (inyectable como `providers` en `deps`). El país elige proveedor solo para suscripciones **nuevas**: sync/cancel/webhook usan siempre `row.provider`. MP usa credenciales **de plataforma por país** (`MP_PLATFORM_ACCESS_TOKEN_<CC>`, nunca `getMpAccessToken`); Stripe, una sola cuenta (`STRIPE_SECRET_KEY` / `STRIPE_WEBHOOK_SECRET`) que cobra en la moneda local (CLP es zero-decimal). Sin credenciales: `503 billing_not_available`. Con Stripe la suscripción no existe hasta completar el checkout: la fila guarda `checkoutRef` (la session) y la sync completa `externalId`.
|
||||||
|
2. Los límites (`PLAN_LIMITS` en shared) se miden contra el **dueño del grupo** (`group.createdById`), con `PlanGuard` inyectado en el `constructor(deps)` de los use-cases (`canCreateGroup`, `canAddAttendees`, `requireFeature`). Un use-case nuevo que cree grupos/alumnos, cobre con MP o active automatizaciones tiene que pasar por el guard.
|
||||||
|
3. Sin `BILLING_ENFORCEMENT=on` todo es Pro y los guards no tocan la base (por eso los tests viejos con prisma mockeado no necesitan `billingSubscription`).
|
||||||
|
4. Los webhooks `POST /billing/webhooks/mp/:country` y `POST /billing/webhooks/stripe` son públicos (`isPublicApiRequest`): el adaptador verifica la firma (`x-signature` / `Stripe-Signature`) y solo dice qué suscripción sincronizar; se deduplica por `(source, dedupeKey)` y se le vuelve a pedir todo al proveedor. El polling (`ReconcileSubscriptions` + sync on-read en `GET /billing/status` si está `PENDING`) es el fallback.
|
||||||
|
5. `402` con `plan_limit_reached` / `plan_feature_required` / `plan_read_only`: la web abre el aviso de Pro desde el `MutationCache` de `main.tsx`.
|
||||||
|
6. Onboarding: paso **Plan** obligatorio (`POST /onboarding/plan`, guarda `country` y `plan_selected_at`); `first-group` da `409 plan_not_selected` sin él. Los pasos del wizard son ids (`features/onboarding/steps.ts`) y con Free se saltean Cobros y WhatsApp.
|
||||||
- **zod en v3.24 (pin exacto)**, no v4: `better-call` (transitiva de better-auth) pide `zod ^4` — ese peer warning es conocido y aceptado. `validator` de hono (`hono/validator`) sustituyó a `@hono/zod-validator` (sus tipos duales zod v3/v4 causaban TS2589/exhaustion no resolubles con `ZodTypeAny`); las rutas tipan `c.req.valid` vía el `ValidationInput` derivado del schema.
|
- **zod en v3.24 (pin exacto)**, no v4: `better-call` (transitiva de better-auth) pide `zod ^4` — ese peer warning es conocido y aceptado. `validator` de hono (`hono/validator`) sustituyó a `@hono/zod-validator` (sus tipos duales zod v3/v4 causaban TS2589/exhaustion no resolubles con `ZodTypeAny`); las rutas tipan `c.req.valid` vía el `ValidationInput` derivado del schema.
|
||||||
- `.env`, `dist/`, `.turbo/`, `apps/backend/generated/`, `node_modules/` están gitignoreados (que no te extrañe su ausencia).
|
- **PWA (`apps/web`)**: Workbox precachea todo lo que emite Vite, así que el tamaño del precache es un costo real de arranque offline. Cuatro trampas ya pisadas: (1) `globIgnores: ['**/workbox-*.js']` matchea también `workbox-window.*.js`, que es el módulo cliente de `virtual:pwa-register` — excluirlo rompe el registro del SW en cada carga; solo se excluye `**/sw.js`. (2) Importar `@fontsource-variable/inter/wght.css` arrastra los 7 subsets (~220 KB que el navegador nunca baja); por eso los `@font-face` de `latin`/`latin-ext` están escritos a mano en `src/index.css`. **No re-agregar `<link>` a `fonts.googleapis.com`**: rompe el offline. (3) El SW necesita contexto seguro (HTTPS o `localhost`); por IP de LAN sobre `http://` no se registra y no avisa. (4) El aviso de instalación vive en `PwaProvider` (fuera del `RouterProvider`, así que sigue la ruta con `router.subscribe('onResolved')`) y **no** en `RootLayout`: `AppLayoutGuard` desmonta `RootLayout` cada vez que su query de onboarding vuelve a `pending`, y un `settled` de dwell en el hijo se perdería en cada navegación.
|
||||||
|
- **Aviso de instalación (`src/features/pwa/`)**: se ofrece solo con **sesión iniciada**, fuera de `/onboarding` y tras **20 s seguidos en la misma ruta** (navegar antes reinicia la cuenta; después de armado ya no se oculta). El descarte es definitivo vía `localStorage['pwa-install-dismissed']`. Ojo: `_authenticated` **no** es un guard de sesión —`AppLayoutGuard` renderiza `RootLayout` aunque no haya `user`—, así que el gate se chequea en el provider. Safari en iOS no dispara `beforeinstallprompt`: ahí se muestra `IosInstallHint` con la instrucción de Compartir → Agregar a pantalla de inicio (excluye CriOS/FxiOS/EdgiOS, que también usan WebKit pero se instalan desde Safari).
|
||||||
|
- **App de alumnos (`modules/student-portal`, `modules/student-access`, web `/i/$token`, `/acceso`, `/alumno/*`)**: acceso sin contraseña y sin datos obligatorios nuevos. Ojo con esto:
|
||||||
|
1. **No pasa por Better Auth**: tablas propias (`student_*`), cookie propia (`gruperly_student`, `__Host-` con HTTPS, 90 días deslizante, se reescribe como mucho cada 1 h) y middleware propio (`studentSession`). Todo `/api/v1/student-portal` está en `isPublicApiRequest` del profe; cada ruta privada declara `studentSession`. Así una sesión de alumno no llega a endpoints del profe y al revés. Nunca montes rutas del profe bajo `/student-portal`.
|
||||||
|
2. Tokens de 32 bytes base64url; **en la base solo el SHA-256**. Invitación 72 h, recuperación 15 min, confirmación de mail 24 h. El **GET del link no consume** (vistas previas de WhatsApp); el POST consume con `updateMany` condicional (`used_at IS NULL AND revoked_at IS NULL AND expires_at > now`) y `count === 1` gana. Todo link inválido responde el mismo `{ status: 'invalid' }` / 410.
|
||||||
|
3. **Reinvitar reinicia el acceso**: revoca tokens pendientes y sesiones, **borra las passkeys** y resetea `welcomed_at`.
|
||||||
|
4. CSRF: `studentOriginGuard` exige `Origin === WEB_URL` (o `WEBAUTHN_ORIGIN`) en todo POST/PUT/DELETE, además de `SameSite=Lax`.
|
||||||
|
5. Autorización: todo pasa por `findLinkedAttendee` (attendee vinculado a la cuenta y no `DROPPED`); lo ajeno es 404. Los alumnos nunca ven a otros miembros. Vincular tutores a varios hijos (N:N en `student_account_attendees`) es solo del lado profe y **todavía no tiene UI**.
|
||||||
|
6. "Pedir un link a mi mail": respuesta idéntica exista o no el mail; rate limit en `rate_limit_events` (3 por mail y 10 por IP cada 15 min). La IP sale de `X-Forwarded-For` contando `TRUSTED_PROXY_HOPS` desde el final. El envío corre después de responder, para no filtrar por tiempo.
|
||||||
|
7. Avisar falta reutiliza `registerAbsence` (EXCUSED + liberación de cupo); `AbsenceNotice` tiene índice único **parcial** (`cancelled_at IS NULL`, escrito a mano en la migración: Prisma no lo modela). Solo antes del inicio de la clase y solo en ocurrencias reales del grupo, en la zona del profe (`COUNTRY_TIME_ZONES[user.country]`, default `APP_TIMEZONE` = Buenos Aires).
|
||||||
|
8. Pago informado: `Payment.status` **no cambia** hasta que el profe confirma. "Requiere atención" y el recordatorio de WhatsApp excluyen cuotas con un `ReportedPayment` `REPORTED` (`reportedItems: { none: … }`); si se rechaza, vuelven. Confirmar marca `PAID` con `paid_at = reviewed_at`; "Deshacer" (10 min) revierte solo esas filas (sin `mp_payment_id`). El mail al alumno sale 60 s después, solo si la revisión sigue en pie y el mail está confirmado.
|
||||||
|
9. Comprobantes: tipo real por magic bytes (`lib/file-type.ts`: JPG, PNG, WEBP, HEIC, PDF; 10 MB), storage S3 privado detrás de `FileStorage` (`lib/storage.ts`, `Bun.S3Client`, path-style para RustFS), URLs firmadas de 5 min. En los tests se inyecta `storage` por deps. Retención: `RECEIPT_RETENTION_DAYS` (job diario `startStudentAccessJobs`).
|
||||||
|
10. Tests: los de `test/db/` van contra Postgres real (concurrencia del link, IDOR, revisión) y solo corren con `bun --filter @gruperly/backend test:db`; en `bun test` aparecen como `skip`.
|
||||||
|
- `.env`, `dist/`, `dev-dist/`, `.turbo/`, `apps/backend/generated/`, `node_modules/` están gitignoreados (que no te extrañe su ausencia).
|
||||||
|
|
||||||
## Convenciones repo-específicas
|
## Convenciones repo-específicas
|
||||||
|
|
||||||
- **Frontend en español**: copy de UI, comentarios y textos en español.
|
- **Frontend en español**: copy de UI, comentarios y textos en español.
|
||||||
- **Base de datos**: todas las tablas usan **snake_case** vía `@@map` en `prisma/models/*.prisma` (p. ej. `User` → `users`, `WaitlistEntry` → `waitlist_entries`). Al agregar un modelo nuevo, incluir siempre `@@map("nombre_tabla")`.
|
- **Base de datos**: todas las tablas y columnas físicas usan **snake_case**. Los modelos declaran `@@map` (p. ej. `User` → `users`, `WaitlistEntry` → `waitlist_entries`) y todo campo Prisma camelCase que cree una columna debe declarar `@map("nombre_campo")` (p. ej. `createdAt @map("created_at")`). Al agregar un modelo o campo nuevo, incluir siempre el mapping correspondiente sin cambiar la API camelCase de Prisma Client.
|
||||||
- **API** responde errores en **Problem Details RFC 7807** (`application/problem+json`) y resultados como `{ data, pagination }`; los "use cases" devuelven `Result` y nunca lanzan excepciones de dominio.
|
- **API** responde errores en **Problem Details RFC 7807** (`application/problem+json`) y resultados como `{ data, pagination }`; los "use cases" devuelven `Result` y nunca lanzan excepciones de dominio.
|
||||||
- **Tailwind v4** con tokens en `@theme` dentro de `apps/web/src/index.css` (p. ej. `--color-accent: #1e90ff`). Se usan como clases auto-generadas: `text-accent`, `bg-success-soft`, etc. Radius por defecto `0.75rem` (`rounded-xl`).
|
- **Tailwind v4** con tokens en `@theme` dentro de `apps/web/src/index.css` (p. ej. `--color-accent: #1e90ff`). Se usan como clases auto-generadas: `text-accent`, `bg-success-soft`, etc. Radius por defecto `0.75rem` (`rounded-xl`).
|
||||||
- **Router NO es file-based** (aunque `stack.md` lo diga): las rutas se declaran manualmente en `apps/web/src/router.tsx` con `createRoute` + `addChildren` y se registran vía module augmentation. **Cada vista nueva debe añadirse ahí.**
|
- **Router ES file-based** (TanStack Router + `@tanstack/router-plugin`): las rutas viven en `apps/web/src/routes/` y solo contienen definiciones (`createFileRoute` + `component`), sin lógica de UI. `src/router.tsx` solo crea el router con el `routeTree` importado de `src/routeTree.gen.ts` (**archivo generado por el plugin en build/dev, versionado en git**: si agregás/renombrás una ruta, corré `bun --filter @gruperly/web build` para regenerarlo). Las rutas autenticadas cuelgan del layout pathless `_authenticated.tsx` (`AppLayoutGuard` + `RootLayout` con `<Outlet />`).
|
||||||
|
- **Vistas en `apps/web/src/features/<feature>/`**: un componente por archivo, nombre de archivo en PascalCase igual al componente, imports relativos (sin alias). El estado compartido padre-hijo vive en un `*Provider.tsx` del feature (contexto + queries/mutations de React Query) que se monta en el route file; los componentes hijos consumen `use<Feature>()` y las forms locales mantienen su propio estado.
|
||||||
|
- **Grupos y "Requiere atención"** comparten la query `['attention']` (`features/attention/queries.ts`): el "Resuelto" es optimista sobre ese caché y por eso los contadores de Grupos se mueven sin refetch. El "Nuevo grupo" de Grupos es un FAB (`NewGroupFab`, se pliega al scrollear con `useCollapseOnScroll`) y por eso los toasts en mobile van a `bottom-[calc(9rem+…)]`. Los colores de gravedad son tokens (`alert-urgent-*`, `alert-watch-*`, `free-fg`) definidos para claro y oscuro en `index.css`.
|
||||||
- Nav (Inicio/Grupos/Cobros/Ajustes) vive en `apps/web/src/components/layout/nav-items.ts`; es la fuente única para `BottomNav` (móvil) y `Sidebar` (desktop) — no dupliques la lista.
|
- Nav (Inicio/Grupos/Cobros/Ajustes) vive en `apps/web/src/components/layout/nav-items.ts`; es la fuente única para `BottomNav` (móvil) y `Sidebar` (desktop) — no dupliques la lista.
|
||||||
|
- **Rutas immersive (Large Title)**: la ficha de grupo, sus estadísticas y la asistencia arman su propia barra de título (`components/layout/LargeTitle.tsx`) en vez del header global. La lista está en `apps/web/src/lib/immersive-routes.ts` (`isImmersiveRoute`, con test) y la consulta `RootLayout`: si el pathname matchea, no se renderiza `<Header />`, `<main>` va `pt-0` y el `Sidebar` pasa a `top-0 h-dvh`. Ojo con dos cosas: (1) un `sticky` solo se pega mientras su **caja padre** esté en pantalla, así que la barra no puede colgar del bloque del feature (se despegaría a los ~200px): se monta por portal en `ImmersiveBarHost`, una caja `h-14` que el layout pone de primer hijo de `<main>`. (2) el colapso va ligado al scroll (pos del `h1` en cada frame), no a una transición CSS, y el estado vive dentro de `LargeTitle` para que `children` no se re-renderice en cada frame. Para sumar una pantalla: registrar el path en `immersive-routes.ts` y usar `<LargeTitle>`; nada más. En las tres pantallas el `<h1>` se renderiza siempre, incluso en estado de carga o error: es lo que le da altura a la barra y evita que el layout salte cuando llegan los datos.
|
||||||
- **UI**: primitivos propios en `apps/web/src/components/ui/` (avatar, button, badge) más helper `cn()` en `src/lib/utils.ts` (clsx + tailwind-merge). Aunque `stack.md` mencione Shadcn, **todavía no está instalado** (sin Radix); úsalos directos.
|
- **UI**: primitivos propios en `apps/web/src/components/ui/` (avatar, button, badge) más helper `cn()` en `src/lib/utils.ts` (clsx + tailwind-merge). Aunque `stack.md` mencione Shadcn, **todavía no está instalado** (sin Radix); úsalos directos.
|
||||||
|
- **Foco al abrir formularios**: siempre que una acción muestre o monte un formulario, el primer campo editable debe recibir el foco automáticamente. Preferí `autoFocus` cuando el formulario aparece por render condicional; si permanece montado u otro flujo lo impide, usá un `ref` con foco explícito al activar la edición.
|
||||||
- Layout mobile-first: `RootLayout` usa columna `max-w-md` en móvil y dos columnas (Sidebar + contenido `max-w-6xl`) en `lg+`.
|
- Layout mobile-first: `RootLayout` usa columna `max-w-md` en móvil y dos columnas (Sidebar + contenido `max-w-6xl`) en `lg+`.
|
||||||
|
- **Safe areas (iOS standalone)**: `index.html` lleva `viewport-fit=cover`; todo elemento fijo pegado al borde inferior (hoy `BottomNav`) necesita `env(safe-area-inset-bottom)` en su padding, y el `pb` del `<main>` en `RootLayout` lo suma (`pb-[calc(6rem+env(safe-area-inset-bottom))]`). Si agregás otro elemento fijo abajo, seguí el mismo patrón o el home indicator lo tapa.
|
||||||
|
- **Sin "volver atrás" en mobile**: en ninguna vista se muestra un link/botón de navegación a la página anterior cuando se ve en mobile (se apoya en el gesto de back del dispositivo). **Excepción**: `/groups/attention` ("Requiere atención", sin entrada en el nav) muestra su botón Volver también en mobile. Los links de "volver" solo en desktop: usar `hidden ... lg:inline-flex` (p. ej. `create-group`, `group-detail`) o `hidden lg:flex` (`Breadcrumb`). No confundir con botones "Volver" de pasos dentro de un wizard/formulario: esos sí se mantienen.
|
||||||
|
|
||||||
## Fuentes de contexto
|
## Fuentes de contexto
|
||||||
|
|
||||||
- `stack.md` — arquitectura y spec técnica de referencia (UI tokens exactos, stack por app).
|
- `stack.md` — arquitectura y spec técnica de referencia (UI tokens exactos, stack por app).
|
||||||
- `README.md` — setup de la base de datos y comandos generales.
|
- `README.md` — setup de la base de datos y comandos generales.
|
||||||
|
|||||||
66
Dockerfile.backend
Normal file
66
Dockerfile.backend
Normal file
@@ -0,0 +1,66 @@
|
|||||||
|
# syntax=docker/dockerfile:1
|
||||||
|
|
||||||
|
# ─── Base ────────────────────────────────────────────────────────────────────
|
||||||
|
FROM oven/bun:1.4-alpine AS base
|
||||||
|
WORKDIR /app
|
||||||
|
ENV CI=1
|
||||||
|
|
||||||
|
# ─── Dependencies ────────────────────────────────────────────────────────────
|
||||||
|
# Only the package.json files: bun needs no source code to resolve the lockfile.
|
||||||
|
FROM base AS deps
|
||||||
|
COPY package.json bun.lock bunfig.toml turbo.json ./
|
||||||
|
COPY apps/backend/package.json ./apps/backend/
|
||||||
|
COPY apps/web/package.json ./apps/web/
|
||||||
|
COPY packages/config/package.json ./packages/config/
|
||||||
|
COPY packages/shared/package.json ./packages/shared/
|
||||||
|
# bun's global cache weighs ~370MB: it is dropped in the same layer.
|
||||||
|
RUN bun install --frozen-lockfile && rm -rf /root/.bun/install
|
||||||
|
|
||||||
|
# ─── Prisma Client ───────────────────────────────────────────────────────────
|
||||||
|
# The "prisma-client" generator emits TypeScript, so the generated client runs
|
||||||
|
# with Bun without compilation. The URL is a placeholder: `generate` only needs
|
||||||
|
# to read the schema, not connect to a database.
|
||||||
|
FROM deps AS generate
|
||||||
|
ARG DATABASE_URL=postgresql://user:password@localhost:5432/placeholder
|
||||||
|
ENV DATABASE_URL=$DATABASE_URL
|
||||||
|
COPY apps/backend/prisma.config.ts ./apps/backend/
|
||||||
|
COPY apps/backend/prisma ./apps/backend/prisma
|
||||||
|
WORKDIR /app/apps/backend
|
||||||
|
RUN bun run db:generate
|
||||||
|
|
||||||
|
# ─── API image ───────────────────────────────────────────────────────────────
|
||||||
|
FROM base AS api
|
||||||
|
ENV NODE_ENV=production \
|
||||||
|
PORT=4000
|
||||||
|
|
||||||
|
COPY package.json bun.lock bunfig.toml ./
|
||||||
|
COPY apps/backend/package.json ./apps/backend/
|
||||||
|
COPY packages/config/package.json ./packages/config/
|
||||||
|
COPY packages/shared/package.json ./packages/shared/
|
||||||
|
# `prisma` and `dotenv` are dependencies (not dev) because the entrypoint runs
|
||||||
|
# `prisma migrate deploy` on every boot. With `--production` the rest of the
|
||||||
|
# tooling does not come in: biome, typescript, turbo.
|
||||||
|
RUN bun install --frozen-lockfile --production && rm -rf /root/.bun/install
|
||||||
|
|
||||||
|
# The Prisma CLI loads prisma.config.ts, which points to the schema.
|
||||||
|
COPY apps/backend/prisma ./apps/backend/prisma
|
||||||
|
COPY apps/backend/prisma.config.ts ./apps/backend/prisma.config.ts
|
||||||
|
COPY --from=generate /app/apps/backend/generated ./apps/backend/generated
|
||||||
|
COPY apps/backend/tsconfig.json ./apps/backend/
|
||||||
|
COPY apps/backend/src ./apps/backend/src
|
||||||
|
# @gruperly/shared is consumed as TS source; @gruperly/config provides the base
|
||||||
|
# tsconfig that the backend tsconfig extends.
|
||||||
|
COPY packages ./packages
|
||||||
|
COPY apps/backend/docker-entrypoint.sh /usr/local/bin/docker-entrypoint.sh
|
||||||
|
RUN chmod +x /usr/local/bin/docker-entrypoint.sh
|
||||||
|
|
||||||
|
WORKDIR /app/apps/backend
|
||||||
|
EXPOSE 4000
|
||||||
|
# No `${...}` here: the CMD runs under /bin/sh (ash), where that is a syntax error.
|
||||||
|
HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \
|
||||||
|
CMD bun --eval "fetch('http://127.0.0.1:4000/api/v1/health').then((r) => process.exit(r.ok ? 0 : 1)).catch(() => process.exit(1))"
|
||||||
|
|
||||||
|
ENTRYPOINT ["/usr/local/bin/docker-entrypoint.sh"]
|
||||||
|
# Bun runs the TypeScript directly and resolves `@/*` with the tsconfig.json,
|
||||||
|
# same as `bun start` locally.
|
||||||
|
CMD ["bun", "src/server.ts"]
|
||||||
35
Dockerfile.web
Normal file
35
Dockerfile.web
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
# syntax=docker/dockerfile:1
|
||||||
|
|
||||||
|
# ─── Base ────────────────────────────────────────────────────────────────────
|
||||||
|
FROM oven/bun:1.4-alpine AS base
|
||||||
|
WORKDIR /app
|
||||||
|
ENV CI=1
|
||||||
|
|
||||||
|
# ─── Dependencies ────────────────────────────────────────────────────────────
|
||||||
|
FROM base AS deps
|
||||||
|
COPY package.json bun.lock bunfig.toml turbo.json ./
|
||||||
|
COPY apps/backend/package.json ./apps/backend/
|
||||||
|
COPY apps/web/package.json ./apps/web/
|
||||||
|
COPY packages/config/package.json ./packages/config/
|
||||||
|
COPY packages/shared/package.json ./packages/shared/
|
||||||
|
# bun's global cache weighs ~370MB: it is dropped in the same layer.
|
||||||
|
RUN bun install --frozen-lockfile && rm -rf /root/.bun/install
|
||||||
|
|
||||||
|
# ─── Vite build ──────────────────────────────────────────────────────────────
|
||||||
|
FROM deps AS build
|
||||||
|
# Vite replaces import.meta.env.* at build time, not at runtime.
|
||||||
|
# Empty = same origin: nginx's /api proxy acts as the API.
|
||||||
|
ARG VITE_API_URL=""
|
||||||
|
ENV VITE_API_URL=$VITE_API_URL
|
||||||
|
COPY apps/web ./apps/web
|
||||||
|
COPY packages ./packages
|
||||||
|
RUN bun --filter @gruperly/web build
|
||||||
|
|
||||||
|
# ─── Final image ─────────────────────────────────────────────────────────────
|
||||||
|
FROM nginx:1.27-alpine AS web
|
||||||
|
COPY apps/web/nginx.conf /etc/nginx/conf.d/default.conf
|
||||||
|
COPY --from=build /app/apps/web/dist /usr/share/nginx/html
|
||||||
|
EXPOSE 80
|
||||||
|
HEALTHCHECK --interval=30s --timeout=5s --start-period=5s --retries=3 \
|
||||||
|
CMD wget --quiet --tries=1 --spider http://127.0.0.1/ || exit 1
|
||||||
|
CMD ["nginx", "-g", "daemon off;"]
|
||||||
197
README.md
197
README.md
@@ -7,7 +7,7 @@ Monorepo de Gruperly. Consulta [stack.md](./stack.md) para arquitectura y especi
|
|||||||
- Package manager: [Bun](https://bun.sh/) 1.4
|
- Package manager: [Bun](https://bun.sh/) 1.4
|
||||||
- Monorepo: bun workspaces + Turborepo
|
- Monorepo: bun workspaces + Turborepo
|
||||||
- Backend (`apps/backend`): Bun + Hono (`Bun.serve`) + Prisma + PostgreSQL + Better Auth
|
- Backend (`apps/backend`): Bun + Hono (`Bun.serve`) + Prisma + PostgreSQL + Better Auth
|
||||||
- Frontend (`apps/web`): React 19 + TypeScript + TanStack Router + TanStack Query + Tailwind v4
|
- Frontend (`apps/web`): React 19 + TypeScript + TanStack Router + TanStack Query + Tailwind v4 + PWA (vite-plugin-pwa / Workbox)
|
||||||
- Shared (`packages/shared`): esquemas Zod, tipos, `Result` y Problem Details compartidos
|
- Shared (`packages/shared`): esquemas Zod, tipos, `Result` y Problem Details compartidos
|
||||||
|
|
||||||
## Estructura
|
## Estructura
|
||||||
@@ -31,9 +31,202 @@ bun run lint # biome check (backend y shared)
|
|||||||
bun --filter @gruperly/backend test # bun test (backend)
|
bun --filter @gruperly/backend test # bun test (backend)
|
||||||
bun --filter @gruperly/backend db:push # Aplica el esquema de Prisma a la base de datos
|
bun --filter @gruperly/backend db:push # Aplica el esquema de Prisma a la base de datos
|
||||||
bun --filter @gruperly/backend db:studio # Abre Prisma Studio
|
bun --filter @gruperly/backend db:studio # Abre Prisma Studio
|
||||||
|
bun --filter @gruperly/web icons # Regenera los iconos PWA de public/ desde el isotipo SVG
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## PWA
|
||||||
|
|
||||||
|
La web es instalable y abre sin conexión el shell de la app (rutas, JS, CSS, tipografía e iconos). Los datos de la API **no** se cachean: son cobros y una respuesta vieja sería peor que un error, así que offline la app carga pero las consultas fallan.
|
||||||
|
|
||||||
|
- **Manifest y service worker**: `apps/web/vite.config.ts` (`VitePWA`, `generateSW`, `registerType: 'autoUpdate'`). El registro se hace desde `apps/web/src/features/pwa/PwaProvider.tsx` (`injectRegister: null`) para poder avisar con un toast cuando la app ya quedó lista para offline.
|
||||||
|
- **`workbox-window` es dependencia directa de `apps/web` a propósito**: `virtual:pwa-register` la importa desde el grafo de la app, pero llega como dependencia transitiva de `vite-plugin-pwa`. Localmente bun la hoistea a la raíz y todo anda; en la imagen de Docker bun usa el layout aislado y la deja solo en `node_modules/.bun/`, así que Rollup falla con `failed to resolve import "workbox-window"` y el build de Dokploy se cae. Declararla en `apps/web/package.json` la hace resoluble desde `apps/web/node_modules/`. **No la borres por "no estar imports en el código".**
|
||||||
|
- **Iconos**: se generan con sharp desde `apps/web/src/assets/brand/isotipo-y-organica.svg` y se versionan en `apps/web/public/` (`pwa-192x192`, `pwa-512x512`, `pwa-maskable-512x512`, `apple-touch-icon-180`). El build **no** los regenera; corré `bun --filter @gruperly/web icons` cuando cambie el isotipo.
|
||||||
|
- **Tipografía**: Inter variable auto-hospedada vía `@fontsource-variable/inter`, declarada a mano en `apps/web/src/index.css`. No hay `<link>` a `fonts.googleapis.com`: era una dependencia de red en runtime.
|
||||||
|
- **Aviso de instalación**: la lógica de *cuándo* se ofrece vive en `apps/web/src/features/pwa/PwaProvider.tsx` (captura `beforeinstallprompt`, gate de sesión, dwell y descarte) y el dibujo en `InstallPrompt.tsx` → `InstallBanner.tsx` (Chromium) o `IosInstallHint.tsx` (Safari en iOS, que no dispara el evento y hay que instruir con Compartir → Agregar a pantalla de inicio).
|
||||||
|
- Se ofrece solo con **sesión iniciada**, **fuera del onboarding** y después de **20 s seguidos en la misma ruta**; `beforeinstallprompt` llega a los segundos y sin ese margen el aviso cae en medio de la primera tarea de la visita. Navegar antes de que se cumpla el tiempo reinicia la cuenta; una vez cumplido no se oculta más al navegar.
|
||||||
|
- El descarte es definitivo: se guarda en `localStorage['pwa-install-dismissed']` y no vuelve a preguntar en ese navegador.
|
||||||
|
- El timer vive en el provider y no en el componente que dibuja el aviso a propósito: `AppLayoutGuard` desmonta `RootLayout` cada vez que su query de onboarding vuelve a `pending`, y un timer en el hijo se perdería en cada navegación. El provider, en cambio, sigue montado y se suscribe al router (`router.subscribe('onResolved')`) porque está fuera del `RouterProvider`.
|
||||||
|
- Ojo: `_authenticated` **no** es un guard de sesión —`AppLayoutGuard` renderiza `RootLayout` sin usuario—, así que el gate se chequea en el provider y no se puede inferir de dónde se monte el prompt.
|
||||||
|
- **nginx**: `apps/web/nginx.conf` sirve `sw.js`, `workbox-*.js` y `manifest.webmanifest` con `Cache-Control: no-cache` y `=404` (no el fallback del SPA), para que una versión vieja no quede cacheada para siempre.
|
||||||
|
|
||||||
|
### Requisitos para que funcione
|
||||||
|
|
||||||
|
El service worker necesita un **contexto seguro**: HTTPS, o `http://localhost`. Probar por IP de LAN sobre `http://` no registra el SW en silencio, sin error visible. En producción el TLS lo termina Traefik adelante de nginx.
|
||||||
|
|
||||||
|
### Verificar
|
||||||
|
|
||||||
|
```bash
|
||||||
|
bun --filter @gruperly/web build
|
||||||
|
bun --filter @gruperly/web preview # http://localhost:4173
|
||||||
|
```
|
||||||
|
|
||||||
|
En DevTools → Application: el manifest sin warnings, el service worker `activated`, y en Network → Offline un reload de `/` o `/groups` tiene que seguir pintando la app. `bun dev` también registra el SW (está en `devOptions`), así que se puede probar sin build, pero `dev-dist/` queda gitignoreado.
|
||||||
|
|
||||||
## Setup de base de datos
|
## Setup de base de datos
|
||||||
|
|
||||||
1. Crea una base PostgreSQL y copia `apps/backend/.env.example` → `apps/backend/.env`, ajustando `DATABASE_URL`.
|
1. Crea una base PostgreSQL y copia `apps/backend/.env.example` → `apps/backend/.env`, ajustando `DATABASE_URL`.
|
||||||
2. Ejecuta `bun --filter @gruperly/backend db:generate` y `bun --filter @gruperly/backend db:push` (o `bun --filter @gruperly/backend db:migrate` en desarrollo).
|
2. Ejecuta `bun --filter @gruperly/backend db:generate` y `bun --filter @gruperly/backend db:push` (o `bun --filter @gruperly/backend db:migrate` en desarrollo).
|
||||||
|
|
||||||
|
## Mercado Pago (OAuth)
|
||||||
|
|
||||||
|
Los cobros llegan a la cuenta del profesor a través de una app de Mercado Pago en modo directo: el profesor autoriza desde el panel de MP y los pagos entran en su propia cuenta, sin comisión ni split de plataforma (`platform_id=mp`). El OAuth vive en `apps/backend/src/modules/mp/`; los links de pago y la reconciliación están en `modules/payments/` (ver [Cobros](#cobros-links-de-pago)).
|
||||||
|
|
||||||
|
**Panel de Mercado Pago** (Developer panel → Tu aplicación):
|
||||||
|
|
||||||
|
- **Redirect URL**: el panel la exige en **HTTPS** (rechaza `http://localhost`) y tiene que coincidir carácter por carácter con `MP_REDIRECT_URI`. En local, meté un túnel delante del backend y registrá esa URL HTTPS tanto en el panel como en la env var: `ngrok http --url=https://TU-DOMINIO.ngrok-free.app 4000` (el *dev domain* de ngrok es fijo por cuenta, gratis) o un túnel nombrado de Cloudflare (`cloudflared tunnel route dns …`). `WEB_URL` y `VITE_API_URL` siguen en localhost: el túnel solo lo usa el navegador para volver desde MP. Los *quick tunnels* de cloudflared generan una URL nueva en cada arranque, así que obligan a regenerar la URL en el panel y en la env var cada reinicio.
|
||||||
|
- **PKCE (S256)**: activado. El `code_verifier` se genera y se consume en el servidor, nunca pasa por el navegador.
|
||||||
|
- **Permisos**: `offline_access read write`. Sin `offline_access` Mercado Pago no devuelve *refresh token* y la renovación automática no tiene con qué trabajar.
|
||||||
|
|
||||||
|
**Variables de entorno** (`apps/backend/.env` en local, pestaña Environment del compose en Dokploy):
|
||||||
|
|
||||||
|
| Variable | ¿Obligatoria? | Descripción |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `MP_CLIENT_ID` | para vincular | Client ID de la app de MP |
|
||||||
|
| `MP_CLIENT_SECRET` | para vincular | Secret de la app de MP |
|
||||||
|
| `MP_REDIRECT_URI` | para vincular | Callback registrado en el panel |
|
||||||
|
| `TOKEN_ENCRYPTION_KEY` | para vincular | `openssl rand -base64 32`. Cifra los tokens en reposo con AES-256-GCM. Si no decodifica a 32 bytes, el backend lo rechaza al guardar la cuenta |
|
||||||
|
|
||||||
|
Sin las cuatro, `GET /api/v1/mp/connect` responde `503 mp_not_configured` y la app sigue funcionando: el paso "Cobros" del onboarding es **salteable**.
|
||||||
|
|
||||||
|
En local se usan las credenciales de **producción** de la app: no existe OAuth sandbox en MP (las credenciales de prueba del panel son solo Public Key y Access Token, sin Client ID/secret). No hay riesgo, porque el OAuth solo vincula una cuenta y no mueve dinero; se prueba con una cuenta propia y se desvincúa con `DELETE /mp/connect`. Los links de pago también se prueban con la cuenta propia (crear un link no cobra nada; el cobro real le pide credenciales de pago al alumno).
|
||||||
|
|
||||||
|
### Cómo funciona
|
||||||
|
|
||||||
|
```text
|
||||||
|
onboarding/ajustes → GET /mp/connect → { authorizationUrl } (state + PKCE en la DB, 10 min)
|
||||||
|
→ https://auth.mercadopago.com/authorization
|
||||||
|
→ GET /mp/callback → ?code&state (se quema el state, se cambia el código)
|
||||||
|
→ 302 a /onboarding?mp=success o /settings?mp=error&reason=…
|
||||||
|
```
|
||||||
|
|
||||||
|
- La API de MP es `GET /mp/status` (`none` | `active` | `requires_reauth`) y `DELETE /mp/connect` (desvincula; conserva la fila para que la cuenta de MP quede reservada al mismo profesor).
|
||||||
|
- Los tokens se guardan cifrados; `status` nunca devuelve tokens, scope ni el id completo de MP (solo los últimos 4 dígitos, para que el profesor confirme que vinculó la cuenta correcta).
|
||||||
|
- Un cron diario (`17 3 * * *` UTC) renueva las cuentas que vencen en menos de 30 días, en lotes de 20 con `FOR UPDATE SKIP LOCKED`. Solo `invalid_grant` marca la cuenta como `requires_reauth`; un 5xx o un fallo de red se reintenta al día siguiente, para no bloquear a un profesor por una tarde mala de MP. `apps/backend/src/modules/mp/access-token.ts` (`getMpAccessToken`) renueva bajo demanda si el token está por vencer.
|
||||||
|
|
||||||
|
### Verificar a mano
|
||||||
|
|
||||||
|
1. `bun dev`, crear una cuenta nueva y llegar al paso "Cobros".
|
||||||
|
2. **Vincular**: "Vincular cuenta" debe abrir el consent de MP; al aceptar se vuelve a `/onboarding` con el mensaje de cuenta vinculada, y Ajustes → Cobros muestra "Vinculada" con los últimos 4 dígitos.
|
||||||
|
3. **Saltear**: con una cuenta nueva, "Lo hago después" deja crear el grupo igual; el resumen final ofrece vincularlo después desde Ajustes.
|
||||||
|
4. **Denegar**: en la pantalla de consentimiento de MP, elegir no autorizar → vuelve con "No autorizaste la conexión en Mercado Pago" y el estado sigue en `none`.
|
||||||
|
5. **Desvincular**: Ajustes → Cobros → Desvincular (pide confirmación) deja el estado en `none` y la tarjeta de cuenta conectada desaparece.
|
||||||
|
6. **Reautenticación**: `UPDATE users SET ...` no hace falta; para forzarla, `UPDATE mp_accounts SET status = 'REQUIRES_REAUTH'` y recargar cualquier pantalla: aparece el aviso global (excepto en Ajustes, donde la tarjeta ofrece la acción).
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Estado real, con la sesión del profesor:
|
||||||
|
curl -s http://localhost:4000/api/v1/mp/status -H 'Cookie: <cookie de sesión>' | jq
|
||||||
|
```
|
||||||
|
|
||||||
|
## Cobros (links de pago)
|
||||||
|
|
||||||
|
Un cobro es un **link de pago de Checkout Pro por alumno y por período**. El profesor lo dispara desde la ficha del grupo (**Cobrar**, habilitado cuando el grupo tiene precio): se crea un `Payment` por cada asistente activo y, para cada uno, una preferencia de Checkout Pro con `external_reference` = id del pago. Crear un link no cobra nada; el cobro real lo paga el alumno desde el link.
|
||||||
|
|
||||||
|
La moneda sale del país del profesor (`user.country`, elegido en el onboarding; default `AR` → `ARS`): `AR→ARS, BR→BRL, CL→CLP, CO→COP, MX→MXN, PE→PEN, UY→UYU`.
|
||||||
|
|
||||||
|
**Endpoints** (todos requieren sesión; solo grupos propios o donde el profesor es miembro):
|
||||||
|
|
||||||
|
| Endpoint | Qué hace |
|
||||||
|
| --- | --- |
|
||||||
|
| `POST /api/v1/groups/:groupId/payments/batch` | Crea el lote. Body: `{ dueDate, description?, attendeeIds? }`. Responde `201` con `{ total, linked, failed, items }`; cada item es `LINKED` (trae `checkoutUrl`) o `FAILED` (error del proveedor, la fila queda `PENDING` sin link) |
|
||||||
|
| `POST /api/v1/payments/:id/renew` | Regenera el link de un pago que lo perdió (item `FAILED`). Idempotente: si ya tiene link, lo devuelve tal cual |
|
||||||
|
| `GET /api/v1/payments?groupId&status&page&pageSize` | Lista paginada `{ data, pagination }` de los cobros visibles |
|
||||||
|
|
||||||
|
**Estados**: `PENDING` (esperando pago) → `PAID` (aprobado en MP) | `OVERDUE` (venció + 24 h de gracia y sigue sin pagar; sigue siendo cobrable) | `CANCELLED` (reservado, hoy no se usa).
|
||||||
|
|
||||||
|
**Reconciliación, sin webhook.** El MVP consolida por polling porque un webhook exige una URL pública y verificación de firma, y no aporta nada a esta escala: un cron cada 15 min consulta la API de MP por `external_reference`, y si el pago está `approved` marca el `Payment` como `PAID` (guarda `mpPaymentId` y `paidAt`). Solo toca pagos con link y de más de 5 min de antigüedad, en lotes de 50. Un cron diario (`4 4 * * *` UTC) convierte en `OVERDUE` los `PENDING` cuya fecha venció hace más de 24 h. Los anuncian en el log (`startPaymentJobs()` en `apps/backend/src/server.ts`).
|
||||||
|
|
||||||
|
**En la web**: la vista **Cobros** (nav) filtra por grupo y estado y deja copiar el link o regenerarlo con "Generar link" (botón renovar). Del modal **Cobrar** en la ficha del grupo se eligen vencimiento y descripción (default: mes en mayúscula) y se muestra un link por alumno para copiar, con los que fallaron listos para reintentar.
|
||||||
|
|
||||||
|
**Errores típicos**: `409 group_without_price` (el grupo no tiene precio definido), `409 no_attendees_to_bill` (sin alumnos activos), `409 mp_not_connected` (el dueño desvinculó MP), `503 mp_not_configured` (faltan las env vars del OAuth).
|
||||||
|
|
||||||
|
### Verificar a mano (además del flujo de OAuth)
|
||||||
|
|
||||||
|
1. Con un grupo con precio y alumnos, "Cobrar" → elegir vencimiento → los links se generan uno por alumno.
|
||||||
|
2. En **Cobros** el grupo aparece con `PENDING` por alumno; "Copiar" pega un link `https://www.mercadopago.com.ar/checkout/v1/…`.
|
||||||
|
3. Abrir el link, pagar (puede fallar si el teste es con la cuenta real: probar el "sandbox de pago" del panel si existe) y esperar la reconciliación (hasta 15 min) o correr el job a mano.
|
||||||
|
4. Un pago aprobado pasa a `PAID`; uno cuyo vencimiento pasó (con +24 h) pasa a `OVERDUE` y permite regenerar el link.
|
||||||
|
|
||||||
|
## WhatsApp (recordatorios y reenganche)
|
||||||
|
|
||||||
|
Una vez por semana (lunes 10:00, hora de Argentina) Gruperly le escribe por WhatsApp, **desde el número del profesor**, a los miembros de los grupos que tengan la automatización prendida:
|
||||||
|
|
||||||
|
- **Recordatorio de pago**: cobros `PENDING`/`OVERDUE` con link que vencen en los próximos 7 días o ya vencieron.
|
||||||
|
- **Reenganche**: los mismos que muestra "Alumnos en riesgo", como mucho uno cada 14 días.
|
||||||
|
|
||||||
|
Las dos se prenden por grupo (ficha del grupo → "Mensajes automáticos por WhatsApp") y vienen apagadas. El profesor vincula su número en el onboarding (paso "WhatsApp", salteable) o en Ajustes → WhatsApp.
|
||||||
|
|
||||||
|
El envío pasa por un proveedor intercambiable (`WHATSAPP_PROVIDER`):
|
||||||
|
|
||||||
|
- **`openwa`** (MVP, default): gateway self-hosted. El profesor lo vincula escaneando un QR o, desde el teléfono, con un código para su número; los mensajes son texto libre. No es oficial y hay riesgo de bloqueo del número.
|
||||||
|
- **`kapso`**: API oficial de Meta. La vinculación es un setup link y los mensajes usan templates aprobados.
|
||||||
|
|
||||||
|
El código vive en `apps/backend/src/modules/whatsapp/`.
|
||||||
|
|
||||||
|
| Variable | ¿Obligatoria? | Descripción |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `WHATSAPP_PROVIDER` | no | `openwa` (default) o `kapso` |
|
||||||
|
| `OPENWA_API_URL`, `OPENWA_API_KEY` | con OpenWA | URL de la API de OpenWA y una key OPERATOR |
|
||||||
|
| `OPENWA_WEBHOOK_URL`, `OPENWA_WEBHOOK_SECRET` | no | Confirmaciones de entrega y lectura. El secreto es obligatorio si hay URL |
|
||||||
|
| `KAPSO_API_KEY`, `KAPSO_CALLBACK_URL`, `KAPSO_WEBHOOK_URL`, `KAPSO_WEBHOOK_SECRET` | con Kapso | Ver la guía |
|
||||||
|
| `WHATSAPP_SEND_INTERVAL_MS` | no | Pausa entre envíos del mismo profesor. Default `5000` |
|
||||||
|
|
||||||
|
Si faltan las variables del proveedor activo, `/whatsapp/*` responde `503 whatsapp_not_configured` y la app sigue funcionando.
|
||||||
|
|
||||||
|
La guía completa está en **[docs/whatsapp.md](docs/whatsapp.md)**: arquitectura, deploy de OpenWA y primera API key, setup de Kapso y templates, riesgos, verificación a mano, troubleshooting y una guía para el profesor.
|
||||||
|
|
||||||
|
## Deploy en producción (Docker / Dokploy)
|
||||||
|
|
||||||
|
Dos imágenes y un compose: `Dockerfile.backend` (API Bun) y `Dockerfile.web` (Vite + nginx).
|
||||||
|
|
||||||
|
- `api` corre Bun sobre el TypeScript fuente (`bun src/server.ts`), igual que en local: el cliente de Prisma se genera como TS y el tsconfig resuelve los aliases `@/*`.
|
||||||
|
- Al arrancar, `apps/backend/docker-entrypoint.sh` aplica `prisma migrate deploy` y recién después levanta el servidor. Si la migración falla, el contenedor no levanta y el error queda en los logs del servicio. Reintenta hasta 30 veces (5s) porque la base puede seguir arrancando.
|
||||||
|
- `web` compila con Vite y lo sirve nginx, que además hace de proxy de `/api` hacia `api`. Así el navegador siempre pega al mismo origen: la cookie de sesión es first-party y el CORS del backend no se activa.
|
||||||
|
- Ambos servicios se enchufan a `dokploy-network`, la red donde Dokploy deja las bases de datos que administra. Dokploy solo agrega esa red al servicio al que le asociás el dominio, así que está declarada a mano en el compose: sin ella, `api` no alcanza a la base y Prisma falla con `P1001 Can't reach database server`.
|
||||||
|
|
||||||
|
### Variables de entorno
|
||||||
|
|
||||||
|
El compose las interpola desde el entorno. En Dokploy van en la pestaña **Environment** del servicio Compose (Dokploy las guarda en un `.env` al lado del `docker-compose.yml`); en local, copiá `.env.example` → `.env` en la raíz.
|
||||||
|
|
||||||
|
| Variable | ¿Obligatoria? | Descripción |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `DATABASE_URL` | sí | `postgresql://user:pass@host:5432/gruperly?schema=public`. La password va percent-encoded: `#` → `%23`, `@` → `%40`, `:` → `%3A`, `/` → `%2F`, `?` → `%3F`, `%` → `%25`, espacio → `%20`. Sin eso, Prisma corta la URL en el fragmento y falla con `P1013 invalid port number` |
|
||||||
|
| `WEB_URL` | sí | Origen público de la app, sin barra final (`https://gruperly.com`). Alimenta `WEB_URL` y `BETTER_AUTH_URL` del contenedor, porque el proxy de nginx deja web y API en el mismo dominio |
|
||||||
|
| `BETTER_AUTH_SECRET` | sí | `openssl rand -base64 32` |
|
||||||
|
| `GOOGLE_CLIENT_ID` / `GOOGLE_CLIENT_SECRET` | no | Login social. Si faltan, no se registra el provider |
|
||||||
|
| `EMAIL_PROVIDER`, `EMAIL_SERVER_*`, `EMAIL_FROM` | no | Salida de emails (mismos nombres que en `apps/backend/.env.example`) |
|
||||||
|
| `MP_CLIENT_ID`, `MP_CLIENT_SECRET`, `MP_REDIRECT_URI` | no | Vinculación con Mercado Pago. Sin ellos, `/mp/connect` responde 503 y la app anda igual (ver [Mercado Pago](#mercadopago-oauth)) |
|
||||||
|
| `TOKEN_ENCRYPTION_KEY` | no (sí para cobrar) | `openssl rand -base64 32`. Cifra los tokens de MP en reposo |
|
||||||
|
| `WHATSAPP_PROVIDER`, `OPENWA_*`, `KAPSO_*`, `WHATSAPP_SEND_INTERVAL_MS` | no | Mensajes automáticos por WhatsApp (ver [WhatsApp](#whatsapp-recordatorios-y-reenganche)). OpenWA no está en el compose: se instala aparte y la API le habla por `OPENWA_API_URL` |
|
||||||
|
| `VITE_API_URL` | no | Se hornea en el bundle de web. Vacío = mismo origen. Solo si querés la API en otro dominio |
|
||||||
|
| `RUN_MIGRATIONS` | no | `false` para arrancar sin aplicar migraciones |
|
||||||
|
|
||||||
|
Si falta alguna obligatoria, el compose aborta antes de construir, con el nombre de la variable en el mensaje.
|
||||||
|
|
||||||
|
### Pasos en Dokploy
|
||||||
|
|
||||||
|
1. Creá una aplicación tipo **Compose** apuntando al repo (el `docker-compose.yml` de la raíz).
|
||||||
|
2. En **Environment** cargá `DATABASE_URL`, `WEB_URL` y `BETTER_AUTH_SECRET` (deshabilitadas las que no uses). Guardá.
|
||||||
|
3. En **General → Domains** asociá el dominio solo al servicio `web`, puerto **`80`**. Ojo: el puerto del dominio es el **puerto del contenedor**, no el del host. El compose publica `8080:80` — el `8080` es para probar en local; nginx escucha `80` adentro. Si ponés `8080` en el panel, Traefik marca la conexión y devuelve Bad Gateway.
|
||||||
|
4. Deploy.
|
||||||
|
|
||||||
|
En `DATABASE_URL` usá el host interno que muestra la base en Dokploy (ej. `piservices-db-llwatq:5432`), que solo resuelve dentro de `dokploy-network`.
|
||||||
|
|
||||||
|
Si la API no levanta, el motivo está en los logs del servicio `api` (pestaña **Logs**), que incluyen la salida de Prisma.
|
||||||
|
|
||||||
|
### Correr las migraciones a mano
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose exec api bun run db:deploy
|
||||||
|
```
|
||||||
|
|
||||||
|
### Comprobar el compose en local
|
||||||
|
|
||||||
|
Fuera de Dokploy hay que crear `dokploy-network` una vez, porque el compose la declara como externa:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker network create dokploy-network # una sola vez
|
||||||
|
cp .env.example .env # completá DATABASE_URL, WEB_URL y BETTER_AUTH_SECRET
|
||||||
|
docker compose up --build -d
|
||||||
|
docker compose logs api # debe salir "migrate: listo" y "Server running on ..."
|
||||||
|
curl http://localhost:8080/api/v1/health
|
||||||
|
```
|
||||||
|
|||||||
265
apps/backend/.agents/skills/prisma-cli/SKILL.md
Normal file
265
apps/backend/.agents/skills/prisma-cli/SKILL.md
Normal file
@@ -0,0 +1,265 @@
|
|||||||
|
---
|
||||||
|
name: prisma-cli
|
||||||
|
description: Prisma ORM CLI commands reference covering init, generate, migrate, db, dev, complete, studio, validate, format, debug, and mcp. Use for ORM/database CLI workflows, not the Prisma Platform CLI. Triggers on "prisma init", "prisma generate", "prisma migrate", "prisma db", "prisma complete", "prisma studio", "prisma mcp".
|
||||||
|
license: MIT
|
||||||
|
metadata:
|
||||||
|
author: prisma
|
||||||
|
version: "7.9.1"
|
||||||
|
---
|
||||||
|
|
||||||
|
# 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: Platform and Compute
|
||||||
|
|
||||||
|
Do not confuse the stable ORM command (`prisma`) with the public-beta Platform package (`@prisma/cli`, binary `prisma-cli`). Use `prisma-compute` for Compute apps and workspace auth, and `prisma-postgres` for Platform projects and databases.
|
||||||
|
|
||||||
|
## 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`)
|
||||||
|
- Generating shell completions (`prisma complete`)
|
||||||
|
|
||||||
|
## 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 | `complete`, `studio`, `validate`, `format`, `debug`, `mcp` |
|
||||||
|
|
||||||
|
## Command Categories
|
||||||
|
|
||||||
|
| Category | Commands | Purpose |
|
||||||
|
|----------|----------|---------|
|
||||||
|
| Setup | `init` | Initialize a 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 | `complete`, `studio`, `mcp`, `version`, `debug` | Shell, 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
|
||||||
|
|
||||||
|
# Generate shell completion code
|
||||||
|
prisma complete zsh
|
||||||
|
```
|
||||||
|
|
||||||
|
## AI Safety Checkpoint
|
||||||
|
|
||||||
|
Prisma blocks destructive commands when it detects an AI agent until the agent has obtained explicit user consent. This covers `migrate reset`, `db push --force-reset`, and `db push --accept-data-loss`.
|
||||||
|
|
||||||
|
- Explain the exact data-loss impact and ask for consent immediately before running the command.
|
||||||
|
- Do not infer consent from earlier or unrelated messages.
|
||||||
|
- If automation needs the consent variable, set `PRISMA_USER_CONSENT_FOR_DANGEROUS_AI_ACTION` to the user's exact consent message. Do not invent the text.
|
||||||
|
- The Prisma MCP server deliberately has no `migrate-reset` tool.
|
||||||
|
|
||||||
|
Read `references/agent-safety.md` before any destructive Prisma command.
|
||||||
|
|
||||||
|
## 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/complete.md - Shell completion generation
|
||||||
|
references/agent-safety.md - AI consent checkpoint for destructive commands
|
||||||
|
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,27 @@
|
|||||||
|
# AI safety checkpoint for destructive commands
|
||||||
|
|
||||||
|
Prisma detects common AI-agent environments and blocks these commands until the user gives explicit consent:
|
||||||
|
|
||||||
|
- `prisma migrate reset`
|
||||||
|
- `prisma db push --force-reset`
|
||||||
|
- `prisma db push --accept-data-loss`
|
||||||
|
|
||||||
|
## Required workflow
|
||||||
|
|
||||||
|
1. Inspect the target database/config and explain exactly what can be deleted or reset.
|
||||||
|
2. Ask the user for explicit consent immediately before the action.
|
||||||
|
3. Run the command only after that consent.
|
||||||
|
|
||||||
|
For an agent-run subprocess, Prisma accepts the exact consent text through:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
PRISMA_USER_CONSENT_FOR_DANGEROUS_AI_ACTION='<exact user consent message>' prisma migrate reset --force
|
||||||
|
```
|
||||||
|
|
||||||
|
The value must match the user's message exactly and must not contain added quotes or newlines. Never fabricate consent, reuse an old unrelated approval, or bypass the checkpoint by hiding agent-detection environment variables.
|
||||||
|
|
||||||
|
The MCP server has no `migrate-reset` tool. Use the shell command only after consent.
|
||||||
|
|
||||||
|
## Reference
|
||||||
|
|
||||||
|
- [Prisma ORM 7.9.0 release](https://github.com/prisma/prisma/releases/tag/7.9.0)
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
# prisma complete
|
||||||
|
|
||||||
|
Prints a shell completion script.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
prisma complete zsh
|
||||||
|
prisma complete bash
|
||||||
|
prisma complete fish
|
||||||
|
prisma complete powershell
|
||||||
|
```
|
||||||
|
|
||||||
|
For a direct global CLI installation, load the output using the shell's normal startup mechanism. For example, in zsh:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
source <(prisma complete zsh)
|
||||||
|
```
|
||||||
|
|
||||||
|
Prisma also integrates with supported package-manager completion flows. `npx` and `bunx` do not themselves provide completion; invoke the installed binary or the package manager's supported execution form such as `npm exec` or `bun x`.
|
||||||
|
|
||||||
|
## Reference
|
||||||
|
|
||||||
|
- [Prisma ORM 7.9.0 release](https://github.com/prisma/prisma/releases/tag/7.9.0)
|
||||||
@@ -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.
|
||||||
185
apps/backend/.agents/skills/prisma-cli/references/db-pull.md
Normal file
185
apps/backend/.agents/skills/prisma-cli/references/db-pull.md
Normal file
@@ -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
|
||||||
150
apps/backend/.agents/skills/prisma-cli/references/db-push.md
Normal file
150
apps/backend/.agents/skills/prisma-cli/references/db-push.md
Normal file
@@ -0,0 +1,150 @@
|
|||||||
|
# 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 |
|
||||||
|
|
||||||
|
When Prisma detects an AI agent, `--force-reset` and `--accept-data-loss` require explicit user consent. Follow `agent-safety.md`; never infer or fabricate the consent text.
|
||||||
|
|
||||||
|
### 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.
|
||||||
188
apps/backend/.agents/skills/prisma-cli/references/db-seed.md
Normal file
188
apps/backend/.agents/skills/prisma-cli/references/db-seed.md
Normal file
@@ -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
|
||||||
46
apps/backend/.agents/skills/prisma-cli/references/debug.md
Normal file
46
apps/backend/.agents/skills/prisma-cli/references/debug.md
Normal file
@@ -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
apps/backend/.agents/skills/prisma-cli/references/dev.md
Normal file
157
apps/backend/.agents/skills/prisma-cli/references/dev.md
Normal 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.
|
||||||
48
apps/backend/.agents/skills/prisma-cli/references/format.md
Normal file
48
apps/backend/.agents/skills/prisma-cli/references/format.md
Normal file
@@ -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
|
||||||
173
apps/backend/.agents/skills/prisma-cli/references/generate.md
Normal file
173
apps/backend/.agents/skills/prisma-cli/references/generate.md
Normal file
@@ -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'
|
||||||
|
```
|
||||||
139
apps/backend/.agents/skills/prisma-cli/references/init.md
Normal file
139
apps/backend/.agents/skills/prisma-cli/references/init.md
Normal file
@@ -0,0 +1,139 @@
|
|||||||
|
# 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 | - |
|
||||||
|
| `--no-skills` | Skip the best-effort installation of Prisma agent skills | - |
|
||||||
|
|
||||||
|
`prisma init` attempts to install `prisma/skills` for detected agents. This is best-effort and does not make project initialization fail. Use `--no-skills` in minimal or controlled environments.
|
||||||
|
|
||||||
|
## 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
|
||||||
39
apps/backend/.agents/skills/prisma-cli/references/mcp.md
Normal file
39
apps/backend/.agents/skills/prisma-cli/references/mcp.md
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
# 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 exposes `migrate-status`, `migrate-dev`, and Prisma Studio tooling. It does not expose the destructive `migrate-reset` tool; do not claim it is available or try to bypass that safety boundary.
|
||||||
|
- For destructive shell commands, follow `agent-safety.md` and obtain explicit user consent.
|
||||||
|
|
||||||
|
## 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
|
||||||
145
apps/backend/.agents/skills/prisma-cli/references/migrate-dev.md
Normal file
145
apps/backend/.agents/skills/prisma-cli/references/migrate-dev.md
Normal file
@@ -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
|
||||||
|
|
||||||
|
Run `prisma generate` as an explicit follow-up when you need refreshed generated artifacts. Do not rely on historical CLI help that described generators as part of `migrate dev`.
|
||||||
|
|
||||||
|
## 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,80 @@
|
|||||||
|
# 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.**
|
||||||
|
|
||||||
|
When Prisma detects an AI agent, this command is blocked until the user gives explicit consent. Follow `agent-safety.md`; `--force` skips the ordinary prompt but does not constitute user consent for an agent.
|
||||||
|
|
||||||
|
## 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.
|
||||||
137
apps/backend/.agents/skills/prisma-cli/references/studio.md
Normal file
137
apps/backend/.agents/skills/prisma-cli/references/studio.md
Normal file
@@ -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
apps/backend/.agents/skills/prisma-client-api/SKILL.md
Normal file
216
apps/backend/.agents/skills/prisma-client-api/SKILL.md
Normal 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.9.1"
|
||||||
|
---
|
||||||
|
|
||||||
|
# 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,221 @@
|
|||||||
|
# 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',
|
||||||
|
},
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
### queryPlanCacheMaxSize
|
||||||
|
|
||||||
|
Use `queryPlanCacheMaxSize` to limit the in-memory query-plan cache:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const prisma = new PrismaClient({
|
||||||
|
adapter,
|
||||||
|
queryPlanCacheMaxSize: 2_000,
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
The value must be a non-negative integer. Set it to `0` to disable query-plan caching; omit it to use Prisma's default. Treat this as a process-local memory/performance control, not a database prepared-statement setting.
|
||||||
|
|
||||||
|
## 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,198 @@
|
|||||||
|
# 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
|
||||||
|
```
|
||||||
|
|
||||||
|
Invalid JavaScript `Date` values passed to raw queries fail validation instead of being silently serialized as `null`. Validate date input at the application boundary; do not rely on `new Date(badValue)` reaching the database.
|
||||||
|
|
||||||
|
When a driver adapter returns an unmapped database-specific error, Prisma surfaces `P2039` with the adapter's preserved original code/message. If those details are missing, fix the adapter mapping rather than parsing rendered error text.
|
||||||
@@ -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 |
|
||||||
193
apps/backend/.agents/skills/prisma-compute/SKILL.md
Normal file
193
apps/backend/.agents/skills/prisma-compute/SKILL.md
Normal file
@@ -0,0 +1,193 @@
|
|||||||
|
---
|
||||||
|
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`, Compute auth/workspaces, apps/deployments/build logs/domains, 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.5.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`
|
||||||
|
- Sending feedback about an unresolvable Compute CLI failure 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.
|
||||||
|
- `runtime-respond-within-60s` - The ingress gives an app 60 seconds to start responding, then returns `504 Gateway Time-out` and cancels the request. Design handlers to answer first and run longer work under `waitUntil` or from a queue, never inside the request.
|
||||||
|
|
||||||
|
### 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.
|
||||||
|
- `sdk-snapshot-detection` - Use `detectComputeApp` for repository snapshots that are not checked out to disk; enumerate workspaces yourself and call it once per candidate app root.
|
||||||
|
|
||||||
|
## 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.
|
||||||
167
apps/backend/.agents/skills/prisma-compute/references/sdk-api.md
Normal file
167
apps/backend/.agents/skills/prisma-compute/references/sdk-api.md
Normal file
@@ -0,0 +1,167 @@
|
|||||||
|
# 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", // optional: explicit placement for a new app
|
||||||
|
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.
|
||||||
|
|
||||||
|
`region` is optional on `deploy` and `createApp`. Omit it to use the Project/platform default when creating an app; do not hard-code a region unless placement is an application requirement.
|
||||||
|
|
||||||
|
## Repository-snapshot detection
|
||||||
|
|
||||||
|
Tooling that already has an in-memory repository tree can detect a deployable app without checking files out:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { detectComputeApp } from '@prisma/compute-sdk/config'
|
||||||
|
|
||||||
|
const detected = detectComputeApp({
|
||||||
|
root: 'apps/api',
|
||||||
|
manifest: {
|
||||||
|
main: 'src/index.ts',
|
||||||
|
scripts: { start: 'bun src/index.ts' },
|
||||||
|
dependencies: { hono: '^4' },
|
||||||
|
},
|
||||||
|
filePaths: ['apps/api/package.json', 'apps/api/src/index.ts'],
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
The result contains `framework`, `frameworkName`, `buildType`, `httpPort`, `entrypoint`, and detection `evidence`, or `null` when nothing is deployable. Paths are repository-relative and unsafe absolute/parent-traversal entrypoints are rejected.
|
||||||
|
|
||||||
|
The helper detects one app root. A monorepo consumer must enumerate workspaces and call it once per candidate. Detection reads `dependencies` and `devDependencies` (not peer dependencies), recognizes config files and framework packages, and can infer Bun-backed servers from valid `start`/`serve` script entrypoints.
|
||||||
|
|
||||||
|
## 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,477 @@
|
|||||||
|
# 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`
|
||||||
|
- for `nuxt`, `astro`, and `nestjs`, prefer strategy defaults unless a custom `build` override is intentional; current configs allow the override
|
||||||
|
- 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
|
||||||
|
|
||||||
|
## Workspace plan limit reached
|
||||||
|
|
||||||
|
When the installed CLI returns `PLAN_LIMIT_REACHED`, treat it as a workspace plan restriction rather than a Compute or database outage.
|
||||||
|
|
||||||
|
For agent/CI handling, run the relevant database command with `--json` and branch on `error.code === "PLAN_LIMIT_REACHED"`. Read `error.meta.upgradeUrl`, `planName`, `workspaceId`, and `usageBlocked`; optional values may be `null`. This is a workspace plan restriction rather than a Compute/database outage. Use the canonical upgrade URL when returned or direct the user to Prisma Console. Do not retry as an outage or infer a plan limit from status codes or message text.
|
||||||
|
|
||||||
|
## 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.
|
||||||
|
|
||||||
|
## Next.js dependency missing after a successful build
|
||||||
|
|
||||||
|
Symptoms in pnpm/Bun isolated workspaces can include a deployment that builds successfully but exits before useful runtime logs, often with `Cannot find module` for `styled-jsx` or another traced dependency.
|
||||||
|
|
||||||
|
The current Compute SDK preserves in-artifact package-store symlinks and materializes only safe out-of-tree targets when staging Next standalone output. Do not manually flatten or rewrite `.next/standalone/node_modules` symlinks; that can break the isolated-store layout.
|
||||||
|
|
||||||
|
Fix:
|
||||||
|
|
||||||
|
1. Upgrade `@prisma/compute-sdk` and `@prisma/cli` to current versions.
|
||||||
|
2. Remove only the generated build artifact/cache appropriate to the project, then rebuild.
|
||||||
|
3. Confirm `output: "standalone"`, redeploy, and inspect the new deployment logs.
|
||||||
|
4. If it persists, report the package manager, workspace layout, first missing module, and SDK/CLI versions through `@prisma/cli feedback` without secrets.
|
||||||
|
|
||||||
|
## 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
|
||||||
|
- `504 Gateway Time-out` with an `openresty` body about 60s in: the ingress request timeout, not the app; see Request Timeout below
|
||||||
|
- 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>`
|
||||||
|
|
||||||
|
## Request Timeout
|
||||||
|
|
||||||
|
Symptoms:
|
||||||
|
|
||||||
|
- the public URL returns `504 Gateway Time-out` with a short `openresty` body, about 60 seconds after the request was sent
|
||||||
|
- the app's own logs show the handler running, with no timeout error
|
||||||
|
- the same route works whenever it starts responding in under 60 seconds
|
||||||
|
- application timeouts set above 60 seconds never produce a response the caller sees
|
||||||
|
|
||||||
|
Why this happens:
|
||||||
|
|
||||||
|
Compute's ingress gives an app 60 seconds to start responding, then answers the client itself and cancels the request. The deadline covers the wait for the first bytes, not how long the response takes to finish, so a response that has already started streaming is not cut off. The app is not told directly; the cancellation surfaces as the request's abort signal. Once the request is cancelled, Compute stops counting it as in flight, so the instance can scale to zero while the handler is still working.
|
||||||
|
|
||||||
|
Fix:
|
||||||
|
|
||||||
|
- respond within 60 seconds; for webhooks, return `200` or `202` before doing the work
|
||||||
|
- continue the work after the response with `waitUntil` or `KeepAwakeGuard` from `@prisma/compute`, which hold the instance awake on a best-effort basis
|
||||||
|
- for work that must not be lost, persist a job and process it from a separate trigger in steps that each fit inside one request
|
||||||
|
- keep in-request timeouts (`AbortSignal.timeout`, fetch timeouts) under 60 seconds so the app's own error handling runs first
|
||||||
|
- check `req.signal` when a handler should stop work it no longer needs to finish
|
||||||
|
- docs: https://www.prisma.io/docs/compute/request-timeout
|
||||||
|
|
||||||
|
## 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.
|
||||||
192
apps/backend/.agents/skills/prisma-database-setup/SKILL.md
Normal file
192
apps/backend/.agents/skills/prisma-database-setup/SKILL.md
Normal file
@@ -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,270 @@
|
|||||||
|
---
|
||||||
|
name: prisma-driver-adapter-implementation
|
||||||
|
description: Required reference for Prisma ORM 7 SQL driver adapter work. Use when implementing or modifying adapters, adding database drivers, or touching SqlDriverAdapter, Transaction, savepoint, result mapping, or DriverAdapterError behavior. Covers current transaction lifecycle, optional savepoint hooks, original database-error preservation, and verification.
|
||||||
|
license: MIT
|
||||||
|
metadata:
|
||||||
|
author: prisma
|
||||||
|
version: "7.9.1"
|
||||||
|
---
|
||||||
|
|
||||||
|
# Prisma SQL Driver Adapter Implementation
|
||||||
|
|
||||||
|
Use this guide with the exact `@prisma/driver-adapter-utils` version installed by the target Prisma release. Driver adapters are a protocol boundary: type-compatible code can still corrupt values, leak connections, or break transactions.
|
||||||
|
|
||||||
|
## When to Apply
|
||||||
|
|
||||||
|
- Implementing `SqlDriverAdapterFactory`, `SqlMigrationAwareDriverAdapterFactory`, `SqlDriverAdapter`, or `Transaction`
|
||||||
|
- Adding nested-transaction/savepoint support
|
||||||
|
- Mapping driver values, column metadata, bind arguments, or database errors
|
||||||
|
- Debugging `P2039`, transaction leaks, shadow-database failures, or adapter-specific query behavior
|
||||||
|
|
||||||
|
## Contract snapshot
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
interface SqlDriverAdapterFactory extends AdapterInfo {
|
||||||
|
connect(): Promise<SqlDriverAdapter>
|
||||||
|
}
|
||||||
|
|
||||||
|
interface SqlMigrationAwareDriverAdapterFactory extends SqlDriverAdapterFactory {
|
||||||
|
connectToShadowDb(): Promise<SqlDriverAdapter>
|
||||||
|
}
|
||||||
|
|
||||||
|
interface SqlDriverAdapter extends AdapterInfo {
|
||||||
|
queryRaw(query: SqlQuery): Promise<SqlResultSet>
|
||||||
|
executeRaw(query: SqlQuery): Promise<number>
|
||||||
|
executeScript(script: string): Promise<void>
|
||||||
|
startTransaction(isolationLevel?: IsolationLevel): Promise<Transaction>
|
||||||
|
getConnectionInfo?(): ConnectionInfo
|
||||||
|
dispose(): Promise<void>
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Transaction extends AdapterInfo {
|
||||||
|
readonly options: { usePhantomQuery: boolean }
|
||||||
|
queryRaw(query: SqlQuery): Promise<SqlResultSet>
|
||||||
|
executeRaw(query: SqlQuery): Promise<number>
|
||||||
|
commit(): Promise<void>
|
||||||
|
rollback(): Promise<void>
|
||||||
|
createSavepoint?(name: string): Promise<void>
|
||||||
|
rollbackToSavepoint?(name: string): Promise<void>
|
||||||
|
releaseSavepoint?(name: string): Promise<void>
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`IsolationLevel` currently includes `READ UNCOMMITTED`, `READ COMMITTED`, `REPEATABLE READ`, `SNAPSHOT`, and `SERIALIZABLE`; validate what the concrete database supports.
|
||||||
|
|
||||||
|
## Priority rules
|
||||||
|
|
||||||
|
| Priority | Rule | Impact |
|
||||||
|
|----------|------|--------|
|
||||||
|
| CRITICAL | One dedicated connection per transaction | Prevents interleaving and leaks |
|
||||||
|
| CRITICAL | `commit`/`rollback` are lifecycle cleanup hooks | Prevents duplicate COMMIT/ROLLBACK |
|
||||||
|
| CRITICAL | Savepoints live on `Transaction`, not adapter-global depth | Makes nested scopes connection-local |
|
||||||
|
| CRITICAL | Preserve original database error code/message | Enables useful `P2039` fallback |
|
||||||
|
| HIGH | Map arguments and result metadata exactly | Prevents silent value corruption |
|
||||||
|
| HIGH | Shadow databases are isolated and always cleaned up | Makes Migrate safe |
|
||||||
|
| HIGH | Dispose only resources the adapter owns | Prevents shutting down caller-owned pools |
|
||||||
|
|
||||||
|
## Query implementation
|
||||||
|
|
||||||
|
`SqlQuery` contains `sql`, `args`, and parallel `argTypes`. Map each argument using both value and `ArgType`; do not discard type/arity information. Execute in the driver's array/tuple row mode so column order is stable.
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
class ExampleQueryable {
|
||||||
|
readonly provider = 'postgres' as const
|
||||||
|
readonly adapterName = '@acme/adapter-example'
|
||||||
|
|
||||||
|
constructor(protected readonly connection: DriverConnection) {}
|
||||||
|
|
||||||
|
async queryRaw(query: SqlQuery): Promise<SqlResultSet> {
|
||||||
|
try {
|
||||||
|
const result = await this.connection.query({
|
||||||
|
text: query.sql,
|
||||||
|
values: query.args.map((value, index) =>
|
||||||
|
mapArg(value, query.argTypes[index]),
|
||||||
|
),
|
||||||
|
rowMode: 'array',
|
||||||
|
})
|
||||||
|
|
||||||
|
return {
|
||||||
|
columnNames: result.fields.map((field) => field.name),
|
||||||
|
columnTypes: result.fields.map(mapColumnType),
|
||||||
|
rows: result.rows,
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
throwAdapterError(error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async executeRaw(query: SqlQuery): Promise<number> {
|
||||||
|
try {
|
||||||
|
const result = await this.connection.execute(
|
||||||
|
query.sql,
|
||||||
|
query.args.map((value, index) => mapArg(value, query.argTypes[index])),
|
||||||
|
)
|
||||||
|
return result.rowsAffected ?? 0
|
||||||
|
} catch (error) {
|
||||||
|
throwAdapterError(error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Result mapping
|
||||||
|
|
||||||
|
Return `columnNames`, `columnTypes`, and `rows` with identical lengths/order. Map driver metadata to `ColumnTypeEnum` deliberately:
|
||||||
|
|
||||||
|
- signed integer widths to `Int32`/`Int64`; preserve 64-bit values without JS number truncation
|
||||||
|
- decimal/numeric to `Numeric` using the representation expected by Prisma
|
||||||
|
- binary to `Uint8Array`/`Bytes`
|
||||||
|
- date-only, time-only, and timestamp to `Date`, `Time`, and `DateTime`
|
||||||
|
- UUID, JSON, enum, arrays, and provider-specific unknown values to their explicit types
|
||||||
|
- unsupported native types to `DriverAdapterError({ kind: 'UnsupportedNativeDataType', type })`
|
||||||
|
|
||||||
|
Test `null`, empty arrays, array element types, big integers, decimals, byte arrays, JSON, dates, and user-defined/unknown native types.
|
||||||
|
|
||||||
|
### Script execution
|
||||||
|
|
||||||
|
`executeScript` must execute a migration script as the provider expects. Prefer the driver's native multi-statement/script facility or a real SQL parser. Naively splitting on `;` breaks functions, triggers, quoted strings, and dialect-specific blocks.
|
||||||
|
|
||||||
|
## Transaction protocol
|
||||||
|
|
||||||
|
`startTransaction` must acquire one dedicated connection, start the database transaction, apply the requested isolation level, and return a `Transaction` bound to that same connection. If setup fails, release it immediately.
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
async startTransaction(level?: IsolationLevel): Promise<Transaction> {
|
||||||
|
const connection = await this.pool.acquire()
|
||||||
|
try {
|
||||||
|
const tx = new ExampleTransaction(connection, () => connection.release())
|
||||||
|
await tx.executeRaw({ sql: 'BEGIN', args: [], argTypes: [] })
|
||||||
|
if (level) {
|
||||||
|
await tx.executeRaw({
|
||||||
|
sql: `SET TRANSACTION ISOLATION LEVEL ${validateLevel(level)}`,
|
||||||
|
args: [],
|
||||||
|
argTypes: [],
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return tx
|
||||||
|
} catch (error) {
|
||||||
|
connection.release(error)
|
||||||
|
throwAdapterError(error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Commit and rollback
|
||||||
|
|
||||||
|
Prisma coordinates the SQL `COMMIT`/`ROLLBACK` through `executeRaw`. The transaction object's `commit()` and `rollback()` methods are lifecycle hooks: detach listeners and release the dedicated connection exactly once. They must not issue a second SQL commit/rollback.
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
class ExampleTransaction extends ExampleQueryable implements Transaction {
|
||||||
|
readonly options = { usePhantomQuery: false }
|
||||||
|
#closed = false
|
||||||
|
|
||||||
|
constructor(connection: DriverConnection, private readonly release: () => void) {
|
||||||
|
super(connection)
|
||||||
|
}
|
||||||
|
|
||||||
|
async commit() { this.finish() }
|
||||||
|
async rollback() { this.finish() }
|
||||||
|
|
||||||
|
private finish() {
|
||||||
|
if (this.#closed) return
|
||||||
|
this.#closed = true
|
||||||
|
this.release()
|
||||||
|
}
|
||||||
|
|
||||||
|
async createSavepoint(name: string) {
|
||||||
|
await this.control(`SAVEPOINT ${safeSavepoint(name)}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
async rollbackToSavepoint(name: string) {
|
||||||
|
await this.control(`ROLLBACK TO SAVEPOINT ${safeSavepoint(name)}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
async releaseSavepoint(name: string) {
|
||||||
|
await this.control(`RELEASE SAVEPOINT ${safeSavepoint(name)}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
private async control(sql: string) {
|
||||||
|
await this.executeRaw({ sql, args: [], argTypes: [] })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Implement the optional savepoint methods only where the provider supports them. Validate/quote savepoint identifiers. For providers whose savepoints are intentionally no-ops, document and test that limitation.
|
||||||
|
|
||||||
|
Never keep transaction depth on the shared adapter. Parallel transactions make adapter-global depth incorrect; nested state belongs to the returned transaction connection and Prisma's savepoint calls.
|
||||||
|
|
||||||
|
## Error mapping
|
||||||
|
|
||||||
|
Wrap recognized driver failures in `DriverAdapterError`. Map known conditions to `MappedError` kinds such as constraint violations, authentication/reachability, missing table/column/database, timeouts, closed transactions, invalid input, value range, and write conflicts.
|
||||||
|
|
||||||
|
For database errors, preserve `originalCode` and `originalMessage` even when falling back to the provider-specific raw variant:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import {
|
||||||
|
DriverAdapterError,
|
||||||
|
type Error as DriverAdapterErrorObject,
|
||||||
|
type MappedError,
|
||||||
|
} from '@prisma/driver-adapter-utils'
|
||||||
|
|
||||||
|
function convertDriverError(error: DatabaseError): DriverAdapterErrorObject {
|
||||||
|
return {
|
||||||
|
originalCode: String(error.code),
|
||||||
|
originalMessage: error.message,
|
||||||
|
...mapKnownOrRaw(error),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function mapKnownOrRaw(error: DatabaseError): MappedError {
|
||||||
|
if (error.code === '23505') {
|
||||||
|
return { kind: 'UniqueConstraintViolation', constraint: parsedConstraint(error) }
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
kind: 'postgres',
|
||||||
|
code: String(error.code ?? 'N/A'),
|
||||||
|
severity: error.severity ?? 'N/A',
|
||||||
|
message: error.message,
|
||||||
|
detail: error.detail,
|
||||||
|
column: error.column,
|
||||||
|
hint: error.hint,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function throwAdapterError(error: unknown): never {
|
||||||
|
if (!isDatabaseError(error)) throw error
|
||||||
|
throw new DriverAdapterError(convertDriverError(error))
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Prisma uses preserved original details when an unmapped driver error becomes `P2039`. Do not replace every unknown exception with a fabricated `GenericJs` id; rethrow genuinely unexpected non-driver errors so programming bugs remain visible.
|
||||||
|
|
||||||
|
## Factory, ownership, and shadow database
|
||||||
|
|
||||||
|
- `connect()` returns a fresh usable adapter connection/pool wrapper.
|
||||||
|
- Track whether the factory created the pool. `dispose()` closes owned pools and only detaches listeners from caller-owned pools unless an explicit option transfers ownership.
|
||||||
|
- Implement `SqlMigrationAwareDriverAdapterFactory` only when `connectToShadowDb()` can create an isolated shadow database, connect to it, and drop it during disposal/failure cleanup.
|
||||||
|
- Never point the shadow adapter at the primary database. Quote generated identifiers and use cryptographically unique names.
|
||||||
|
- `getConnectionInfo()` should accurately report `schemaName`, `maxBindValues` when applicable, and `supportsRelationJoins`.
|
||||||
|
|
||||||
|
## Verification checklist
|
||||||
|
|
||||||
|
- [ ] Typecheck against the exact target `@prisma/driver-adapter-utils` version
|
||||||
|
- [ ] `queryRaw` preserves column order, types, nulls, and precision
|
||||||
|
- [ ] `executeRaw` reports affected rows correctly
|
||||||
|
- [ ] `executeScript` handles provider-specific multi-statement syntax
|
||||||
|
- [ ] Concurrent interactive transactions use distinct dedicated connections
|
||||||
|
- [ ] Success commits and releases once; failure rolls back and releases once
|
||||||
|
- [ ] Nested transaction tests exercise create/rollback/release savepoint hooks
|
||||||
|
- [ ] Unsupported isolation levels fail as `InvalidIsolationLevel`
|
||||||
|
- [ ] Known constraints map to structured errors
|
||||||
|
- [ ] Unmapped database errors retain original code/message and surface useful `P2039`
|
||||||
|
- [ ] Dispose ownership is tested for internal and external pools
|
||||||
|
- [ ] Shadow database creation, use, failure cleanup, and disposal are isolated
|
||||||
|
- [ ] Run Prisma Client integration/E2E tests, not only adapter unit tests
|
||||||
|
|
||||||
|
## Source references
|
||||||
|
|
||||||
|
- [Driver adapter interfaces](https://github.com/prisma/prisma/blob/v7/packages/driver-adapter-utils/src/types.ts)
|
||||||
|
- [PostgreSQL adapter transaction implementation](https://github.com/prisma/prisma/blob/v7/packages/adapter-pg/src/pg.ts)
|
||||||
|
- [PostgreSQL adapter error mapping](https://github.com/prisma/prisma/blob/v7/packages/adapter-pg/src/errors.ts)
|
||||||
92
apps/backend/.agents/skills/prisma-mongodb-upgrade/SKILL.md
Normal file
92
apps/backend/.agents/skills/prisma-mongodb-upgrade/SKILL.md
Normal file
@@ -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`
|
||||||
263
apps/backend/.agents/skills/prisma-postgres-setup/SKILL.md
Normal file
263
apps/backend/.agents/skills/prisma-postgres-setup/SKILL.md
Normal file
@@ -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` |
|
||||||
145
apps/backend/.agents/skills/prisma-postgres/SKILL.md
Normal file
145
apps/backend/.agents/skills/prisma-postgres/SKILL.md
Normal file
@@ -0,0 +1,145 @@
|
|||||||
|
---
|
||||||
|
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.9.1"
|
||||||
|
---
|
||||||
|
|
||||||
|
# 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 --help
|
||||||
|
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>`.
|
||||||
|
|
||||||
|
For automation, prefer `--json --no-interactive`, resolve ids before mutations, and verify the installed command's help because this CLI is beta.
|
||||||
|
|
||||||
|
### 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.
|
||||||
|
|
||||||
|
The SDK exposes typed workspace service-token list, create, and revoke routes. A newly created token value is returned exactly once. Let the installed SDK types or OpenAPI document settle exact beta endpoint shapes.
|
||||||
|
|
||||||
|
## 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,70 @@
|
|||||||
|
# management-api-sdk
|
||||||
|
|
||||||
|
Use `@prisma/management-api-sdk` for typed API integration with optional OAuth and token refresh.
|
||||||
|
|
||||||
|
The Platform API evolves independently from Prisma ORM. Inspect the installed package's generated `api.d.ts` for exact paths and request/response shapes.
|
||||||
|
|
||||||
|
## 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')
|
||||||
|
```
|
||||||
|
|
||||||
|
Check the generated client result before using `data`; typed clients surface HTTP failures separately. Never log a full response from connection/key creation because it may contain one-time credentials.
|
||||||
|
|
||||||
|
## Workspace service tokens
|
||||||
|
|
||||||
|
The typed client exposes routes to list, create, and revoke workspace service tokens:
|
||||||
|
|
||||||
|
- `GET /v1/workspaces/{workspaceId}/service-tokens`
|
||||||
|
- `POST /v1/workspaces/{workspaceId}/service-tokens`
|
||||||
|
- `DELETE /v1/workspaces/{workspaceId}/service-tokens/{serviceTokenId}`
|
||||||
|
|
||||||
|
Creation accepts a display `name`. The response's `data.value` is the complete token and is returned exactly once; transfer it directly to the intended secret store without logging the response. Later list calls return metadata and `valueHint`, not the token value. Treat revocation as destructive and resolve both ids explicitly.
|
||||||
|
|
||||||
|
## 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,79 @@
|
|||||||
|
# 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.
|
||||||
|
|
||||||
|
## Current resource inventory
|
||||||
|
|
||||||
|
The 1.55 OpenAPI surface includes:
|
||||||
|
|
||||||
|
- workspaces, subscriptions, workspace integrations, workspace service tokens, and current-user metadata
|
||||||
|
- projects, transfers, project databases, and project/branch environment variables
|
||||||
|
- branches under a project plus branch get/update/delete operations
|
||||||
|
- databases, usage, backups, restore, connections, and connection rotation
|
||||||
|
- apps, deployments, promotion/rollback, runtime logs, domains, and build logs
|
||||||
|
- buckets and bucket keys
|
||||||
|
- source repositories, SCM installations/install intents, and repositories
|
||||||
|
- integrations and regions
|
||||||
|
|
||||||
|
App/deployment, branch mutation, SCM, and bucket routes include experimental surfaces. Read the installed SDK types or live OpenAPI before building durable automation around them.
|
||||||
|
|
||||||
|
Connection create/rotate responses reveal credentials once. Later reads redact or omit the secret, so store the URL immediately. Use the structured direct/pooled endpoint returned by the concrete operation; do not assume a historical flat response shape.
|
||||||
|
|
||||||
|
Workspace service-token creation also returns the complete token value exactly once. List calls expose only metadata and a `valueHint`; delete revokes the token. Keep workspace and token ids opaque, and never log a create response.
|
||||||
|
|
||||||
|
Database create supports explicit project, region, branch, and source context. A source may be empty, a backup, or another database. Backup records are incremental; rely on current fields and documented units rather than old full-backup examples.
|
||||||
|
|
||||||
|
## Notes
|
||||||
|
|
||||||
|
- Management API mutation responses may include direct connection credentials; treat the entire response as secret until redacted.
|
||||||
|
- Prefer an API-provided connection string over manually assembling one from fields.
|
||||||
|
|
||||||
|
## 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
apps/backend/.agents/skills/prisma-upgrade-v7/SKILL.md
Normal file
259
apps/backend/.agents/skills/prisma-upgrade-v7/SKILL.md
Normal 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"]
|
||||||
|
}
|
||||||
|
```
|
||||||
@@ -18,4 +18,79 @@ EMAIL_SERVER_HOST=""
|
|||||||
EMAIL_SERVER_PORT="587"
|
EMAIL_SERVER_PORT="587"
|
||||||
EMAIL_SERVER_USER=""
|
EMAIL_SERVER_USER=""
|
||||||
EMAIL_SERVER_PASSWORD=""
|
EMAIL_SERVER_PASSWORD=""
|
||||||
EMAIL_FROM="Gruperly <no-reply@gruperly.com>"
|
EMAIL_FROM="Gruperly <no-reply@gruperly.com>"
|
||||||
|
|
||||||
|
# Mercado Pago (OAuth, Authorization Code + PKCE)
|
||||||
|
MP_CLIENT_ID=""
|
||||||
|
MP_CLIENT_SECRET=""
|
||||||
|
# Debe coincidir exactamente con la "Redirect URL" de la app en el panel de MP.
|
||||||
|
# El panel exige HTTPS (rechaza http://localhost): en local usá un túnel
|
||||||
|
# (p. ej. ngrok http --url=https://TU-DOMINIO.ngrok-free.app 4000) y cargá
|
||||||
|
# la URL del túnel acá y en el panel.
|
||||||
|
MP_REDIRECT_URI=""
|
||||||
|
# Clave de 32 bytes en base64 para cifrar los tokens de MP en reposo (AES-256-GCM).
|
||||||
|
# Generar con: openssl rand -base64 32
|
||||||
|
TOKEN_ENCRYPTION_KEY=""
|
||||||
|
|
||||||
|
# Suscripción a Gruperly Pro (ver docs/billing.md). Argentina la cobra con
|
||||||
|
# Suscripciones de Mercado Pago; el resto de los países, con Stripe.
|
||||||
|
# Mercado Pago: credenciales de la cuenta de MP **de Gruperly** en Argentina (no
|
||||||
|
# son las del OAuth del profesor). Sin las dos, Pro queda "no disponible" (503).
|
||||||
|
MP_PLATFORM_ACCESS_TOKEN_AR=""
|
||||||
|
MP_PLATFORM_WEBHOOK_SECRET_AR=""
|
||||||
|
# Stripe: una sola cuenta para BR, CL, CO, MX, PE y UY, cobrando en la moneda
|
||||||
|
# de cada país. Secret key (sk_test_… en local) y el signing secret del webhook
|
||||||
|
# (whsec_…; en local lo imprime `stripe listen`). Sin las dos, 503 en esos países.
|
||||||
|
STRIPE_SECRET_KEY=""
|
||||||
|
STRIPE_WEBHOOK_SECRET=""
|
||||||
|
# on = aplica los límites del plan Free. Cualquier otro valor (o vacío): todos Pro.
|
||||||
|
BILLING_ENFORCEMENT="off"
|
||||||
|
# Días que un Pro vencido (cancelado o con el cobro rechazado) sigue funcionando.
|
||||||
|
BILLING_GRACE_DAYS="7"
|
||||||
|
|
||||||
|
# Backoffice (/admin): emails del equipo de Gruperly, separados por coma. Vacío = nadie.
|
||||||
|
ADMIN_EMAILS=""
|
||||||
|
|
||||||
|
# WhatsApp: recordatorios de pago y reenganche semanales (ver docs/whatsapp.md).
|
||||||
|
# Proveedor: openwa (MVP, gateway self-hosted con QR) | kapso (API oficial de Meta).
|
||||||
|
WHATSAPP_PROVIDER="openwa"
|
||||||
|
# Pausa entre dos envíos del mismo profesor, en ms (OpenWA recomienda < 15 msg/min).
|
||||||
|
WHATSAPP_SEND_INTERVAL_MS="5000"
|
||||||
|
|
||||||
|
# OpenWA (se instala aparte). En local: docker run, ver docs/whatsapp.md.
|
||||||
|
OPENWA_API_URL="http://localhost:2785/api"
|
||||||
|
# Key OPERATOR sin allowedSessions, creada con la key ADMIN de /app/data/.api-key.
|
||||||
|
OPENWA_API_KEY=""
|
||||||
|
# Opcional. Sin webhook la vinculación funciona (el status hace polling), pero no
|
||||||
|
# llegan las confirmaciones de entrega/lectura. Si lo cargás, el secreto es obligatorio.
|
||||||
|
OPENWA_WEBHOOK_URL=""
|
||||||
|
# 16+ caracteres. Generar con: openssl rand -hex 24
|
||||||
|
OPENWA_WEBHOOK_SECRET=""
|
||||||
|
|
||||||
|
# Kapso (WHATSAPP_PROVIDER="kapso"). Las URLs tienen que ser públicas (túnel en local).
|
||||||
|
KAPSO_API_KEY=""
|
||||||
|
KAPSO_CALLBACK_URL=""
|
||||||
|
KAPSO_WEBHOOK_URL=""
|
||||||
|
# El mismo secreto del project webhook configurado en el dashboard de Kapso.
|
||||||
|
KAPSO_WEBHOOK_SECRET=""
|
||||||
|
# KAPSO_API_URL="https://api.kapso.ai"
|
||||||
|
|
||||||
|
# App de alumnos (acceso sin contraseña por link de un solo uso; ver AGENTS.md).
|
||||||
|
# Comprobantes de pago: storage privado compatible con S3 (RustFS, MinIO, R2, AWS).
|
||||||
|
# Sin estas cuatro variables, "Informar pago" responde 503 storage_not_available.
|
||||||
|
S3_ENDPOINT="http://localhost:9000"
|
||||||
|
S3_BUCKET="gruperly-receipts"
|
||||||
|
S3_ACCESS_KEY_ID=""
|
||||||
|
S3_SECRET_ACCESS_KEY=""
|
||||||
|
S3_REGION="us-east-1"
|
||||||
|
# on = URLs estilo AWS (bucket.endpoint). RustFS/MinIO usan path-style: dejalo vacío.
|
||||||
|
S3_VIRTUAL_HOSTED=""
|
||||||
|
# Días que se guarda un comprobante después de que el profe lo revisó. 0 = para siempre.
|
||||||
|
RECEIPT_RETENTION_DAYS="0"
|
||||||
|
# WebAuthn (Face ID / huella del alumno). Por defecto salen de WEB_URL; cambialos
|
||||||
|
# solo si la web se sirve desde otro origen (p. ej. un túnel para probar en el teléfono).
|
||||||
|
# WEBAUTHN_RP_ID="localhost"
|
||||||
|
# WEBAUTHN_ORIGIN="http://localhost:6173"
|
||||||
|
# Proxies delante de la API que agregan X-Forwarded-For (1 = solo nginx; 2 = Traefik + nginx).
|
||||||
|
# Define qué IP cuenta para el rate limit de "Pedir un link a mi mail".
|
||||||
|
TRUSTED_PROXY_HOPS="1"
|
||||||
|
|||||||
42
apps/backend/docker-entrypoint.sh
Executable file
42
apps/backend/docker-entrypoint.sh
Executable file
@@ -0,0 +1,42 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
# Production entrypoint for the backend: applies the migrations and starts the
|
||||||
|
# server in the same container.
|
||||||
|
#
|
||||||
|
# This is POSIX sh, not bash: the image is alpine and does not ship bash
|
||||||
|
# installed (adding it would be ~10MB for a shebang).
|
||||||
|
#
|
||||||
|
# Set RUN_MIGRATIONS=false to start without touching the database (for example,
|
||||||
|
# a database already migrated by hand, or one managed outside this deployment).
|
||||||
|
set -e
|
||||||
|
|
||||||
|
: "${DATABASE_URL:?falta DATABASE_URL}"
|
||||||
|
|
||||||
|
if [ "${RUN_MIGRATIONS:-true}" = "false" ]; then
|
||||||
|
echo "migrate: omitido (RUN_MIGRATIONS=false)"
|
||||||
|
else
|
||||||
|
attempts="${MIGRATE_ATTEMPTS:-30}"
|
||||||
|
delay="${MIGRATE_RETRY_DELAY:-5}"
|
||||||
|
i=1
|
||||||
|
|
||||||
|
# The database may still be starting up when this container is already
|
||||||
|
# running, and a deploy usually overlaps a Postgres restart.
|
||||||
|
while [ "$i" -le "$attempts" ]; do
|
||||||
|
if bun run db:deploy; then
|
||||||
|
echo "migrate: listo"
|
||||||
|
break
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ "$i" -eq "$attempts" ]; then
|
||||||
|
echo "migrate: fallo tras $attempts intentos; no se levanta el servidor" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "migrate: intento $i/$attempts fallo; reintento en ${delay}s" >&2
|
||||||
|
i=$((i + 1))
|
||||||
|
sleep "$delay"
|
||||||
|
done
|
||||||
|
fi
|
||||||
|
|
||||||
|
# exec so that Bun becomes PID 1 and receives the SIGTERM from `docker stop`
|
||||||
|
# (the server uses it to close Bun.serve and disconnect Prisma).
|
||||||
|
exec "$@"
|
||||||
@@ -9,11 +9,13 @@
|
|||||||
"build": "prisma generate && tsc",
|
"build": "prisma generate && tsc",
|
||||||
"typecheck": "tsc --noEmit",
|
"typecheck": "tsc --noEmit",
|
||||||
"test": "bun test",
|
"test": "bun test",
|
||||||
|
"test:db": "DB_TESTS=1 bun test test/db",
|
||||||
"test:watch": "bun test --watch",
|
"test:watch": "bun test --watch",
|
||||||
"lint": "biome check .",
|
"lint": "biome check .",
|
||||||
"lint:fix": "biome check . --write",
|
"lint:fix": "biome check . --write",
|
||||||
"db:generate": "prisma generate",
|
"db:generate": "prisma generate",
|
||||||
"db:migrate": "prisma migrate dev",
|
"db:migrate": "prisma migrate dev",
|
||||||
|
"db:deploy": "prisma migrate deploy",
|
||||||
"db:push": "prisma db push",
|
"db:push": "prisma db push",
|
||||||
"db:studio": "prisma studio"
|
"db:studio": "prisma studio"
|
||||||
},
|
},
|
||||||
@@ -22,11 +24,15 @@
|
|||||||
"@gruperly/shared": "workspace:*",
|
"@gruperly/shared": "workspace:*",
|
||||||
"@prisma/adapter-pg": "^7.10.0",
|
"@prisma/adapter-pg": "^7.10.0",
|
||||||
"@prisma/client": "^7.10.0",
|
"@prisma/client": "^7.10.0",
|
||||||
|
"@simplewebauthn/server": "13.3.3",
|
||||||
"better-auth": "1.7.2",
|
"better-auth": "1.7.2",
|
||||||
|
"dotenv": "^16.4.5",
|
||||||
"hono": "^4.13.3",
|
"hono": "^4.13.3",
|
||||||
|
"nanoid": "^3.3.19",
|
||||||
"nodemailer": "^9.0.6",
|
"nodemailer": "^9.0.6",
|
||||||
"pino": "^9.5.0",
|
"pino": "^9.5.0",
|
||||||
"pino-pretty": "^13.0.0",
|
"pino-pretty": "^13.0.0",
|
||||||
|
"prisma": "^7.10.0",
|
||||||
"zod": "3.24.2"
|
"zod": "3.24.2"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
@@ -35,8 +41,6 @@
|
|||||||
"@types/bun": "^1.4.0",
|
"@types/bun": "^1.4.0",
|
||||||
"@types/node": "^20.17.0",
|
"@types/node": "^20.17.0",
|
||||||
"@types/nodemailer": "^8.0.1",
|
"@types/nodemailer": "^8.0.1",
|
||||||
"dotenv": "^16.4.5",
|
|
||||||
"prisma": "^7.10.0",
|
|
||||||
"typescript": "^5.7.0"
|
"typescript": "^5.7.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
-- Rename Student model (students table) to Attendee (attendees table)
|
||||||
|
|
||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "students" RENAME TO "attendees";
|
||||||
|
|
||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "payments" RENAME COLUMN "studentId" TO "attendeeId";
|
||||||
|
|
||||||
|
-- RenameIndex
|
||||||
|
ALTER INDEX "students_groupId_idx" RENAME TO "attendees_groupId_idx";
|
||||||
|
|
||||||
|
-- RenameIndex
|
||||||
|
ALTER INDEX "payments_studentId_idx" RENAME TO "payments_attendeeId_idx";
|
||||||
|
|
||||||
|
-- RenameForeignKey
|
||||||
|
ALTER TABLE "payments" RENAME CONSTRAINT "payments_studentId_fkey" TO "payments_attendeeId_fkey";
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
-- CreateEnum
|
||||||
|
CREATE TYPE "WeekDay" AS ENUM ('MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', 'FRIDAY', 'SATURDAY', 'SUNDAY');
|
||||||
|
|
||||||
|
-- CreateEnum
|
||||||
|
CREATE TYPE "BillingType" AS ENUM ('MONTHLY', 'PER_CLASS');
|
||||||
|
|
||||||
|
-- CreateEnum
|
||||||
|
CREATE TYPE "PaymentProvider" AS ENUM ('MERCADO_PAGO', 'STRIPE');
|
||||||
|
|
||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "attendees" RENAME CONSTRAINT "students_pkey" TO "attendees_pkey";
|
||||||
|
|
||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "groups" ADD COLUMN "billingType" "BillingType",
|
||||||
|
ADD COLUMN "capacity" INTEGER,
|
||||||
|
ADD COLUMN "days" "WeekDay"[],
|
||||||
|
ADD COLUMN "dueDay" INTEGER,
|
||||||
|
ADD COLUMN "price" DECIMAL(10,2),
|
||||||
|
ADD COLUMN "time" TEXT;
|
||||||
|
|
||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "users" ADD COLUMN "onboardingCompleted" BOOLEAN NOT NULL DEFAULT false;
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "merchant_accounts" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"userId" TEXT NOT NULL,
|
||||||
|
"provider" "PaymentProvider" NOT NULL,
|
||||||
|
"accessToken" TEXT,
|
||||||
|
"sandbox" BOOLEAN NOT NULL DEFAULT true,
|
||||||
|
"connectedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "merchant_accounts_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "merchant_accounts_userId_key" ON "merchant_accounts"("userId");
|
||||||
|
|
||||||
|
-- RenameForeignKey
|
||||||
|
ALTER TABLE "attendees" RENAME CONSTRAINT "students_groupId_fkey" TO "attendees_groupId_fkey";
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "merchant_accounts" ADD CONSTRAINT "merchant_accounts_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "groups" ADD COLUMN "inviteToken" TEXT;
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "groups_inviteToken_key" ON "groups"("inviteToken");
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "group_waitlist_entries" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"groupId" TEXT NOT NULL,
|
||||||
|
"fullName" TEXT NOT NULL,
|
||||||
|
"phone" TEXT NOT NULL,
|
||||||
|
"email" TEXT,
|
||||||
|
"notes" TEXT,
|
||||||
|
"status" "WaitlistStatus" NOT NULL DEFAULT 'PENDING',
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "group_waitlist_entries_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "group_waitlist_entries_groupId_idx" ON "group_waitlist_entries"("groupId");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "group_waitlist_entries_groupId_phone_key" ON "group_waitlist_entries"("groupId", "phone");
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "group_waitlist_entries" ADD CONSTRAINT "group_waitlist_entries_groupId_fkey" FOREIGN KEY ("groupId") REFERENCES "groups"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
-- CreateEnum
|
||||||
|
CREATE TYPE "AttendanceStatus" AS ENUM ('PRESENT', 'ABSENT', 'EXCUSED');
|
||||||
|
|
||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "attendees" ADD COLUMN "notifyToken" TEXT;
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "class_sessions" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"groupId" TEXT NOT NULL,
|
||||||
|
"startsAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "class_sessions_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "attendances" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"attendeeId" TEXT NOT NULL,
|
||||||
|
"classSessionId" TEXT NOT NULL,
|
||||||
|
"status" "AttendanceStatus" NOT NULL,
|
||||||
|
"markedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "attendances_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "slot_releases" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"attendeeId" TEXT NOT NULL,
|
||||||
|
"classSessionId" TEXT NOT NULL,
|
||||||
|
"isClaimed" BOOLEAN NOT NULL DEFAULT false,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "slot_releases_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "class_sessions_groupId_startsAt_key" ON "class_sessions"("groupId", "startsAt");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "attendances_attendeeId_classSessionId_key" ON "attendances"("attendeeId", "classSessionId");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "slot_releases_attendeeId_classSessionId_key" ON "slot_releases"("attendeeId", "classSessionId");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "attendees_notifyToken_key" ON "attendees"("notifyToken");
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "class_sessions" ADD CONSTRAINT "class_sessions_groupId_fkey" FOREIGN KEY ("groupId") REFERENCES "groups"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "attendances" ADD CONSTRAINT "attendances_attendeeId_fkey" FOREIGN KEY ("attendeeId") REFERENCES "attendees"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "attendances" ADD CONSTRAINT "attendances_classSessionId_fkey" FOREIGN KEY ("classSessionId") REFERENCES "class_sessions"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "slot_releases" ADD CONSTRAINT "slot_releases_attendeeId_fkey" FOREIGN KEY ("attendeeId") REFERENCES "attendees"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "slot_releases" ADD CONSTRAINT "slot_releases_classSessionId_fkey" FOREIGN KEY ("classSessionId") REFERENCES "class_sessions"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- Backfill: tokens de aviso de ausencia para alumnos existentes
|
||||||
|
UPDATE "attendees" SET "notifyToken" = gen_random_uuid()::text WHERE "notifyToken" IS NULL;
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
-- CreateEnum
|
||||||
|
CREATE TYPE "AttendeeStatus" AS ENUM ('ACTIVE', 'PAUSED', 'DROPPED');
|
||||||
|
|
||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "attendees" ADD COLUMN "status" "AttendeeStatus" NOT NULL DEFAULT 'ACTIVE';
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
-- CreateEnum
|
||||||
|
CREATE TYPE "PreRegistrationStatus" AS ENUM ('PENDING', 'APPROVED', 'REJECTED');
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "group_pre_registrations" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"groupId" TEXT NOT NULL,
|
||||||
|
"fullName" TEXT NOT NULL,
|
||||||
|
"phone" TEXT NOT NULL,
|
||||||
|
"email" TEXT,
|
||||||
|
"status" "PreRegistrationStatus" NOT NULL DEFAULT 'PENDING',
|
||||||
|
"reviewedAt" TIMESTAMP(3),
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "group_pre_registrations_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "group_pre_registrations_groupId_idx" ON "group_pre_registrations"("groupId");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "group_pre_registrations_groupId_phone_key" ON "group_pre_registrations"("groupId", "phone");
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "group_pre_registrations" ADD CONSTRAINT "group_pre_registrations_groupId_fkey" FOREIGN KEY ("groupId") REFERENCES "groups"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
@@ -0,0 +1,128 @@
|
|||||||
|
-- Rename camelCase columns to snake_case without recreating them or losing data.
|
||||||
|
|
||||||
|
-- accounts
|
||||||
|
ALTER TABLE "accounts" RENAME COLUMN "userId" TO "user_id";
|
||||||
|
ALTER TABLE "accounts" RENAME COLUMN "providerId" TO "provider_id";
|
||||||
|
ALTER TABLE "accounts" RENAME COLUMN "accountId" TO "account_id";
|
||||||
|
ALTER TABLE "accounts" RENAME COLUMN "accessToken" TO "access_token";
|
||||||
|
ALTER TABLE "accounts" RENAME COLUMN "refreshToken" TO "refresh_token";
|
||||||
|
ALTER TABLE "accounts" RENAME COLUMN "idToken" TO "id_token";
|
||||||
|
ALTER TABLE "accounts" RENAME COLUMN "accessTokenExpiresAt" TO "access_token_expires_at";
|
||||||
|
ALTER TABLE "accounts" RENAME COLUMN "refreshTokenExpiresAt" TO "refresh_token_expires_at";
|
||||||
|
ALTER TABLE "accounts" RENAME COLUMN "createdAt" TO "created_at";
|
||||||
|
ALTER TABLE "accounts" RENAME COLUMN "updatedAt" TO "updated_at";
|
||||||
|
|
||||||
|
-- attendances
|
||||||
|
ALTER TABLE "attendances" RENAME COLUMN "attendeeId" TO "attendee_id";
|
||||||
|
ALTER TABLE "attendances" RENAME COLUMN "classSessionId" TO "class_session_id";
|
||||||
|
ALTER TABLE "attendances" RENAME COLUMN "markedAt" TO "marked_at";
|
||||||
|
|
||||||
|
-- attendees
|
||||||
|
ALTER TABLE "attendees" RENAME COLUMN "groupId" TO "group_id";
|
||||||
|
ALTER TABLE "attendees" RENAME COLUMN "fullName" TO "full_name";
|
||||||
|
ALTER TABLE "attendees" RENAME COLUMN "guardianName" TO "guardian_name";
|
||||||
|
ALTER TABLE "attendees" RENAME COLUMN "guardianPhone" TO "guardian_phone";
|
||||||
|
ALTER TABLE "attendees" RENAME COLUMN "notifyToken" TO "notify_token";
|
||||||
|
ALTER TABLE "attendees" RENAME COLUMN "createdAt" TO "created_at";
|
||||||
|
ALTER TABLE "attendees" RENAME COLUMN "updatedAt" TO "updated_at";
|
||||||
|
|
||||||
|
-- class_sessions
|
||||||
|
ALTER TABLE "class_sessions" RENAME COLUMN "groupId" TO "group_id";
|
||||||
|
ALTER TABLE "class_sessions" RENAME COLUMN "startsAt" TO "starts_at";
|
||||||
|
ALTER TABLE "class_sessions" RENAME COLUMN "createdAt" TO "created_at";
|
||||||
|
ALTER TABLE "class_sessions" RENAME COLUMN "updatedAt" TO "updated_at";
|
||||||
|
|
||||||
|
-- group_members
|
||||||
|
ALTER TABLE "group_members" RENAME COLUMN "groupId" TO "group_id";
|
||||||
|
ALTER TABLE "group_members" RENAME COLUMN "userId" TO "user_id";
|
||||||
|
ALTER TABLE "group_members" RENAME COLUMN "joinedAt" TO "joined_at";
|
||||||
|
|
||||||
|
-- group_pre_registrations
|
||||||
|
ALTER TABLE "group_pre_registrations" RENAME COLUMN "groupId" TO "group_id";
|
||||||
|
ALTER TABLE "group_pre_registrations" RENAME COLUMN "fullName" TO "full_name";
|
||||||
|
ALTER TABLE "group_pre_registrations" RENAME COLUMN "reviewedAt" TO "reviewed_at";
|
||||||
|
ALTER TABLE "group_pre_registrations" RENAME COLUMN "createdAt" TO "created_at";
|
||||||
|
ALTER TABLE "group_pre_registrations" RENAME COLUMN "updatedAt" TO "updated_at";
|
||||||
|
|
||||||
|
-- group_waitlist_entries
|
||||||
|
ALTER TABLE "group_waitlist_entries" RENAME COLUMN "groupId" TO "group_id";
|
||||||
|
ALTER TABLE "group_waitlist_entries" RENAME COLUMN "fullName" TO "full_name";
|
||||||
|
ALTER TABLE "group_waitlist_entries" RENAME COLUMN "createdAt" TO "created_at";
|
||||||
|
ALTER TABLE "group_waitlist_entries" RENAME COLUMN "updatedAt" TO "updated_at";
|
||||||
|
|
||||||
|
-- groups
|
||||||
|
ALTER TABLE "groups" RENAME COLUMN "billingType" TO "billing_type";
|
||||||
|
ALTER TABLE "groups" RENAME COLUMN "dueDay" TO "due_day";
|
||||||
|
ALTER TABLE "groups" RENAME COLUMN "inviteToken" TO "invite_token";
|
||||||
|
ALTER TABLE "groups" RENAME COLUMN "createdById" TO "created_by_id";
|
||||||
|
ALTER TABLE "groups" RENAME COLUMN "createdAt" TO "created_at";
|
||||||
|
ALTER TABLE "groups" RENAME COLUMN "updatedAt" TO "updated_at";
|
||||||
|
|
||||||
|
-- invitations
|
||||||
|
ALTER TABLE "invitations" RENAME COLUMN "organizationId" TO "organization_id";
|
||||||
|
ALTER TABLE "invitations" RENAME COLUMN "inviterId" TO "inviter_id";
|
||||||
|
ALTER TABLE "invitations" RENAME COLUMN "expiresAt" TO "expires_at";
|
||||||
|
ALTER TABLE "invitations" RENAME COLUMN "createdAt" TO "created_at";
|
||||||
|
|
||||||
|
-- members
|
||||||
|
ALTER TABLE "members" RENAME COLUMN "organizationId" TO "organization_id";
|
||||||
|
ALTER TABLE "members" RENAME COLUMN "userId" TO "user_id";
|
||||||
|
ALTER TABLE "members" RENAME COLUMN "createdAt" TO "created_at";
|
||||||
|
|
||||||
|
-- merchant_accounts
|
||||||
|
ALTER TABLE "merchant_accounts" RENAME COLUMN "userId" TO "user_id";
|
||||||
|
ALTER TABLE "merchant_accounts" RENAME COLUMN "accessToken" TO "access_token";
|
||||||
|
ALTER TABLE "merchant_accounts" RENAME COLUMN "connectedAt" TO "connected_at";
|
||||||
|
ALTER TABLE "merchant_accounts" RENAME COLUMN "createdAt" TO "created_at";
|
||||||
|
ALTER TABLE "merchant_accounts" RENAME COLUMN "updatedAt" TO "updated_at";
|
||||||
|
|
||||||
|
-- organizations
|
||||||
|
ALTER TABLE "organizations" RENAME COLUMN "createdAt" TO "created_at";
|
||||||
|
ALTER TABLE "organizations" RENAME COLUMN "updatedAt" TO "updated_at";
|
||||||
|
|
||||||
|
-- passkeys
|
||||||
|
ALTER TABLE "passkeys" RENAME COLUMN "publicKey" TO "public_key";
|
||||||
|
ALTER TABLE "passkeys" RENAME COLUMN "credentialID" TO "credential_id";
|
||||||
|
ALTER TABLE "passkeys" RENAME COLUMN "userId" TO "user_id";
|
||||||
|
ALTER TABLE "passkeys" RENAME COLUMN "deviceType" TO "device_type";
|
||||||
|
ALTER TABLE "passkeys" RENAME COLUMN "backedUp" TO "backed_up";
|
||||||
|
ALTER TABLE "passkeys" RENAME COLUMN "createdAt" TO "created_at";
|
||||||
|
|
||||||
|
-- payments
|
||||||
|
ALTER TABLE "payments" RENAME COLUMN "groupId" TO "group_id";
|
||||||
|
ALTER TABLE "payments" RENAME COLUMN "attendeeId" TO "attendee_id";
|
||||||
|
ALTER TABLE "payments" RENAME COLUMN "dueDate" TO "due_date";
|
||||||
|
ALTER TABLE "payments" RENAME COLUMN "paidAt" TO "paid_at";
|
||||||
|
ALTER TABLE "payments" RENAME COLUMN "createdAt" TO "created_at";
|
||||||
|
ALTER TABLE "payments" RENAME COLUMN "updatedAt" TO "updated_at";
|
||||||
|
|
||||||
|
-- sessions
|
||||||
|
ALTER TABLE "sessions" RENAME COLUMN "userId" TO "user_id";
|
||||||
|
ALTER TABLE "sessions" RENAME COLUMN "expiresAt" TO "expires_at";
|
||||||
|
ALTER TABLE "sessions" RENAME COLUMN "ipAddress" TO "ip_address";
|
||||||
|
ALTER TABLE "sessions" RENAME COLUMN "userAgent" TO "user_agent";
|
||||||
|
ALTER TABLE "sessions" RENAME COLUMN "activeOrganizationId" TO "active_organization_id";
|
||||||
|
ALTER TABLE "sessions" RENAME COLUMN "createdAt" TO "created_at";
|
||||||
|
ALTER TABLE "sessions" RENAME COLUMN "updatedAt" TO "updated_at";
|
||||||
|
|
||||||
|
-- slot_releases
|
||||||
|
ALTER TABLE "slot_releases" RENAME COLUMN "attendeeId" TO "attendee_id";
|
||||||
|
ALTER TABLE "slot_releases" RENAME COLUMN "classSessionId" TO "class_session_id";
|
||||||
|
ALTER TABLE "slot_releases" RENAME COLUMN "isClaimed" TO "is_claimed";
|
||||||
|
ALTER TABLE "slot_releases" RENAME COLUMN "createdAt" TO "created_at";
|
||||||
|
|
||||||
|
-- users
|
||||||
|
ALTER TABLE "users" RENAME COLUMN "emailVerified" TO "email_verified";
|
||||||
|
ALTER TABLE "users" RENAME COLUMN "onboardingCompleted" TO "onboarding_completed";
|
||||||
|
ALTER TABLE "users" RENAME COLUMN "createdAt" TO "created_at";
|
||||||
|
ALTER TABLE "users" RENAME COLUMN "updatedAt" TO "updated_at";
|
||||||
|
|
||||||
|
-- verifications
|
||||||
|
ALTER TABLE "verifications" RENAME COLUMN "expiresAt" TO "expires_at";
|
||||||
|
ALTER TABLE "verifications" RENAME COLUMN "createdAt" TO "created_at";
|
||||||
|
ALTER TABLE "verifications" RENAME COLUMN "updatedAt" TO "updated_at";
|
||||||
|
|
||||||
|
-- waitlist_entries
|
||||||
|
ALTER TABLE "waitlist_entries" RENAME COLUMN "userId" TO "user_id";
|
||||||
|
ALTER TABLE "waitlist_entries" RENAME COLUMN "createdAt" TO "created_at";
|
||||||
|
ALTER TABLE "waitlist_entries" RENAME COLUMN "updatedAt" TO "updated_at";
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
-- Mercado Pago OAuth (Authorization Code + PKCE). Replaces the simulated
|
||||||
|
-- payment setup, where a fake access token was stored in plaintext.
|
||||||
|
|
||||||
|
-- CreateEnum
|
||||||
|
CREATE TYPE "MpAccountStatus" AS ENUM ('ACTIVE', 'REQUIRES_REAUTH', 'REVOKED');
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "mp_accounts" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"owner_id" TEXT NOT NULL,
|
||||||
|
"mp_user_id" TEXT NOT NULL,
|
||||||
|
"access_token_enc" TEXT NOT NULL,
|
||||||
|
"refresh_token_enc" TEXT NOT NULL,
|
||||||
|
"expires_at" TIMESTAMP(3) NOT NULL,
|
||||||
|
"scope" TEXT,
|
||||||
|
"live_mode" BOOLEAN NOT NULL DEFAULT false,
|
||||||
|
"status" "MpAccountStatus" NOT NULL DEFAULT 'ACTIVE',
|
||||||
|
"connected_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "mp_accounts_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "mp_oauth_states" (
|
||||||
|
"state" TEXT NOT NULL,
|
||||||
|
"owner_id" TEXT NOT NULL,
|
||||||
|
"code_verifier" TEXT NOT NULL,
|
||||||
|
"return_to" TEXT NOT NULL,
|
||||||
|
"expires_at" TIMESTAMP(3) NOT NULL,
|
||||||
|
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "mp_oauth_states_pkey" PRIMARY KEY ("state")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "mp_accounts_status_expiresAt_idx" ON "mp_accounts"("status", "expires_at");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "mp_accounts_ownerId_key" ON "mp_accounts"("owner_id");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "mp_accounts_mpUserId_key" ON "mp_accounts"("mp_user_id");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "mp_oauth_states_expiresAt_idx" ON "mp_oauth_states"("expires_at");
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "mp_accounts" ADD CONSTRAINT "mp_accounts_ownerId_fkey" FOREIGN KEY ("owner_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- DropTable
|
||||||
|
DROP TABLE "merchant_accounts";
|
||||||
|
|
||||||
|
-- DropEnum
|
||||||
|
DROP TYPE "PaymentProvider";
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
-- Country of the professor (onboarding) + Mercado Pago Checkout Pro payment links.
|
||||||
|
|
||||||
|
-- AlterTable (users)
|
||||||
|
ALTER TABLE "users" ADD COLUMN "country_code" TEXT;
|
||||||
|
|
||||||
|
-- AlterTable (payments)
|
||||||
|
ALTER TABLE "payments" ADD COLUMN "description" TEXT;
|
||||||
|
ALTER TABLE "payments" ADD COLUMN "checkout_url" TEXT;
|
||||||
|
ALTER TABLE "payments" ADD COLUMN "mp_preference_id" TEXT;
|
||||||
|
ALTER TABLE "payments" ADD COLUMN "mp_payment_id" TEXT;
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "payments_mp_preference_id_key" ON "payments"("mp_preference_id");
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
-- WhatsApp messaging: linked accounts (provider-agnostic), Kapso templates,
|
||||||
|
-- outbound message log and webhook dedupe; plus the per-group automation switches.
|
||||||
|
|
||||||
|
-- CreateEnum
|
||||||
|
CREATE TYPE "MessagingProviderId" AS ENUM ('OPENWA', 'KAPSO');
|
||||||
|
|
||||||
|
-- CreateEnum
|
||||||
|
CREATE TYPE "WhatsappAccountStatus" AS ENUM ('PENDING', 'ACTIVE', 'DISCONNECTED');
|
||||||
|
|
||||||
|
-- CreateEnum
|
||||||
|
CREATE TYPE "WhatsappMessageKind" AS ENUM ('PAYMENT_REMINDER', 'REENGAGEMENT');
|
||||||
|
|
||||||
|
-- CreateEnum
|
||||||
|
CREATE TYPE "OutboundMessageStatus" AS ENUM ('QUEUED', 'SENT', 'DELIVERED', 'READ', 'FAILED', 'SKIPPED');
|
||||||
|
|
||||||
|
-- CreateEnum
|
||||||
|
CREATE TYPE "WhatsappTemplateStatus" AS ENUM ('PENDING', 'APPROVED', 'REJECTED', 'DISABLED');
|
||||||
|
|
||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "groups" ADD COLUMN "auto_payment_reminders" BOOLEAN NOT NULL DEFAULT false,
|
||||||
|
ADD COLUMN "auto_reengagement" BOOLEAN NOT NULL DEFAULT false;
|
||||||
|
|
||||||
|
-- AlterTable (pre-existing drift: the schema already declares this default)
|
||||||
|
ALTER TABLE "payments" ALTER COLUMN "currency" SET DEFAULT 'ARS';
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "whatsapp_accounts" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"owner_id" TEXT NOT NULL,
|
||||||
|
"provider" "MessagingProviderId" NOT NULL,
|
||||||
|
"status" "WhatsappAccountStatus" NOT NULL DEFAULT 'PENDING',
|
||||||
|
"external_id" TEXT,
|
||||||
|
"display_phone_number" TEXT,
|
||||||
|
"provider_data" JSONB,
|
||||||
|
"connected_at" TIMESTAMP(3),
|
||||||
|
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "whatsapp_accounts_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "whatsapp_templates" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"account_id" TEXT NOT NULL,
|
||||||
|
"kind" "WhatsappMessageKind" NOT NULL,
|
||||||
|
"name" TEXT NOT NULL,
|
||||||
|
"language" TEXT NOT NULL,
|
||||||
|
"meta_template_id" TEXT,
|
||||||
|
"status" "WhatsappTemplateStatus" NOT NULL DEFAULT 'PENDING',
|
||||||
|
"rejected_reason" TEXT,
|
||||||
|
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "whatsapp_templates_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "outbound_messages" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"owner_id" TEXT NOT NULL,
|
||||||
|
"group_id" TEXT NOT NULL,
|
||||||
|
"attendee_id" TEXT NOT NULL,
|
||||||
|
"payment_id" TEXT,
|
||||||
|
"kind" "WhatsappMessageKind" NOT NULL,
|
||||||
|
"provider" "MessagingProviderId" NOT NULL,
|
||||||
|
"period_key" TEXT NOT NULL,
|
||||||
|
"to_phone" TEXT NOT NULL,
|
||||||
|
"provider_message_id" TEXT,
|
||||||
|
"status" "OutboundMessageStatus" NOT NULL DEFAULT 'QUEUED',
|
||||||
|
"error_code" TEXT,
|
||||||
|
"error_message" TEXT,
|
||||||
|
"sent_at" TIMESTAMP(3),
|
||||||
|
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "outbound_messages_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "whatsapp_webhook_events" (
|
||||||
|
"provider" "MessagingProviderId" NOT NULL,
|
||||||
|
"dedupe_key" TEXT NOT NULL,
|
||||||
|
"received_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "whatsapp_webhook_events_pkey" PRIMARY KEY ("provider","dedupe_key")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "whatsapp_accounts_ownerId_key" ON "whatsapp_accounts"("owner_id");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "whatsapp_accounts_provider_externalId_key" ON "whatsapp_accounts"("provider", "external_id");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "whatsapp_templates_status_idx" ON "whatsapp_templates"("status");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "whatsapp_templates_accountId_kind_key" ON "whatsapp_templates"("account_id", "kind");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "outbound_messages_attendeeId_kind_createdAt_idx" ON "outbound_messages"("attendee_id", "kind", "created_at");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "outbound_messages_groupId_createdAt_idx" ON "outbound_messages"("group_id", "created_at");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "outbound_messages_kind_attendeeId_periodKey_key" ON "outbound_messages"("kind", "attendee_id", "period_key");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "outbound_messages_provider_providerMessageId_key" ON "outbound_messages"("provider", "provider_message_id");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "whatsapp_webhook_events_receivedAt_idx" ON "whatsapp_webhook_events"("received_at");
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "whatsapp_accounts" ADD CONSTRAINT "whatsapp_accounts_ownerId_fkey" FOREIGN KEY ("owner_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "whatsapp_templates" ADD CONSTRAINT "whatsapp_templates_accountId_fkey" FOREIGN KEY ("account_id") REFERENCES "whatsapp_accounts"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "outbound_messages" ADD CONSTRAINT "outbound_messages_groupId_fkey" FOREIGN KEY ("group_id") REFERENCES "groups"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "outbound_messages" ADD CONSTRAINT "outbound_messages_attendeeId_fkey" FOREIGN KEY ("attendee_id") REFERENCES "attendees"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "outbound_messages" ADD CONSTRAINT "outbound_messages_paymentId_fkey" FOREIGN KEY ("payment_id") REFERENCES "payments"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
-- CreateEnum
|
||||||
|
CREATE TYPE "SubscriptionStatus" AS ENUM ('PENDING', 'AUTHORIZED', 'PAUSED', 'CANCELLED');
|
||||||
|
|
||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "users" ADD COLUMN "plan_selected_at" TIMESTAMP(3);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "billing_subscriptions" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"user_id" TEXT NOT NULL,
|
||||||
|
"country_code" TEXT NOT NULL,
|
||||||
|
"currency" TEXT NOT NULL,
|
||||||
|
"amount" DECIMAL(12,2) NOT NULL,
|
||||||
|
"payer_email" TEXT NOT NULL,
|
||||||
|
"mp_preapproval_id" TEXT,
|
||||||
|
"status" "SubscriptionStatus" NOT NULL DEFAULT 'PENDING',
|
||||||
|
"requested_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"authorized_at" TIMESTAMP(3),
|
||||||
|
"next_payment_date" TIMESTAMP(3),
|
||||||
|
"paid_through" TIMESTAMP(3),
|
||||||
|
"last_synced_at" TIMESTAMP(3),
|
||||||
|
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "billing_subscriptions_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "billing_charges" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"subscription_id" TEXT NOT NULL,
|
||||||
|
"mp_authorized_payment_id" TEXT NOT NULL,
|
||||||
|
"amount" DECIMAL(12,2) NOT NULL,
|
||||||
|
"currency" TEXT NOT NULL,
|
||||||
|
"status" TEXT NOT NULL,
|
||||||
|
"paid_at" TIMESTAMP(3),
|
||||||
|
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "billing_charges_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "billing_webhook_events" (
|
||||||
|
"country_code" TEXT NOT NULL,
|
||||||
|
"dedupe_key" TEXT NOT NULL,
|
||||||
|
"received_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "billing_webhook_events_pkey" PRIMARY KEY ("country_code","dedupe_key")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "billing_subscriptions_userId_key" ON "billing_subscriptions"("user_id");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "billing_subscriptions_mpPreapprovalId_key" ON "billing_subscriptions"("mp_preapproval_id");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "billing_subscriptions_status_lastSyncedAt_idx" ON "billing_subscriptions"("status", "last_synced_at");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "billing_charges_mpAuthorizedPaymentId_key" ON "billing_charges"("mp_authorized_payment_id");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "billing_charges_subscriptionId_createdAt_idx" ON "billing_charges"("subscription_id", "created_at");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "billing_webhook_events_receivedAt_idx" ON "billing_webhook_events"("received_at");
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "billing_subscriptions" ADD CONSTRAINT "billing_subscriptions_userId_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "billing_charges" ADD CONSTRAINT "billing_charges_subscriptionId_fkey" FOREIGN KEY ("subscription_id") REFERENCES "billing_subscriptions"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
-- Pro billing behind a provider port: Mercado Pago (AR) or Stripe (the rest).
|
||||||
|
-- Columns are renamed, not dropped, so existing Mercado Pago rows keep their ids.
|
||||||
|
|
||||||
|
-- CreateEnum
|
||||||
|
CREATE TYPE "BillingProviderId" AS ENUM ('MERCADO_PAGO', 'STRIPE');
|
||||||
|
|
||||||
|
-- billing_subscriptions: provider + provider-neutral ids
|
||||||
|
ALTER TABLE "billing_subscriptions" ADD COLUMN "provider" "BillingProviderId" NOT NULL DEFAULT 'MERCADO_PAGO';
|
||||||
|
ALTER TABLE "billing_subscriptions" ADD COLUMN "checkout_ref" TEXT;
|
||||||
|
ALTER TABLE "billing_subscriptions" RENAME COLUMN "mp_preapproval_id" TO "external_id";
|
||||||
|
ALTER INDEX "billing_subscriptions_mpPreapprovalId_key" RENAME TO "billing_subscriptions_externalId_key";
|
||||||
|
CREATE UNIQUE INDEX "billing_subscriptions_checkoutRef_key" ON "billing_subscriptions"("checkout_ref");
|
||||||
|
|
||||||
|
-- billing_charges: provider-neutral id and normalized status
|
||||||
|
ALTER TABLE "billing_charges" RENAME COLUMN "mp_authorized_payment_id" TO "external_id";
|
||||||
|
ALTER INDEX "billing_charges_mpAuthorizedPaymentId_key" RENAME TO "billing_charges_externalId_key";
|
||||||
|
UPDATE "billing_charges"
|
||||||
|
SET "status" = CASE
|
||||||
|
WHEN "status" = 'approved' THEN 'approved'
|
||||||
|
WHEN "status" IN ('rejected', 'cancelled', 'refunded', 'charged_back') THEN 'rejected'
|
||||||
|
ELSE 'pending'
|
||||||
|
END;
|
||||||
|
|
||||||
|
-- billing_webhook_events: dedupe per sending account (`mp:<CC>` or `stripe`)
|
||||||
|
ALTER TABLE "billing_webhook_events" RENAME COLUMN "country_code" TO "source";
|
||||||
|
UPDATE "billing_webhook_events" SET "source" = 'mp:' || "source";
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
-- CreateEnum
|
||||||
|
CREATE TYPE "StudentAlertKind" AS ENUM ('ATTENDANCE', 'PAYMENT');
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "attendee_alert_resolutions" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"attendee_id" TEXT NOT NULL,
|
||||||
|
"kind" "StudentAlertKind" NOT NULL,
|
||||||
|
"signature" TEXT NOT NULL,
|
||||||
|
"resolved_by_id" TEXT NOT NULL,
|
||||||
|
"resolved_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "attendee_alert_resolutions_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "attendee_alert_resolutions_attendee_id_kind_key" ON "attendee_alert_resolutions"("attendee_id", "kind");
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "attendee_alert_resolutions" ADD CONSTRAINT "attendee_alert_resolutions_attendee_id_fkey" FOREIGN KEY ("attendee_id") REFERENCES "attendees"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user