From 7149a46547195726eaee26a94cce914fe3388486 Mon Sep 17 00:00:00 2001 From: Ankur Datta <64993082+ankur-arch@users.noreply.github.com> Date: Mon, 11 May 2026 16:41:09 +0200 Subject: [PATCH] feat: add versioning --- .gitignore | 1 + .../next/add-to-existing-project/meta.json | 4 + .../next/add-to-existing-project/mongodb.mdx | 199 +++++++++++++ .../add-to-existing-project/postgresql.mdx | 207 +++++++++++++ apps/docs/content/docs/orm/next/index.mdx | 172 +++++++++++ apps/docs/content/docs/orm/next/meta.json | 12 + .../docs/orm/next/quickstart/meta.json | 4 + .../docs/orm/next/quickstart/mongodb.mdx | 273 +++++++++++++++++ .../docs/orm/next/quickstart/postgresql.mdx | 281 ++++++++++++++++++ apps/docs/src/lib/version.ts | 4 +- 10 files changed, 1155 insertions(+), 2 deletions(-) create mode 100644 apps/docs/content/docs/orm/next/add-to-existing-project/meta.json create mode 100644 apps/docs/content/docs/orm/next/add-to-existing-project/mongodb.mdx create mode 100644 apps/docs/content/docs/orm/next/add-to-existing-project/postgresql.mdx create mode 100644 apps/docs/content/docs/orm/next/index.mdx create mode 100644 apps/docs/content/docs/orm/next/meta.json create mode 100644 apps/docs/content/docs/orm/next/quickstart/meta.json create mode 100644 apps/docs/content/docs/orm/next/quickstart/mongodb.mdx create mode 100644 apps/docs/content/docs/orm/next/quickstart/postgresql.mdx diff --git a/.gitignore b/.gitignore index 6cd1410a81..d974a2a963 100644 --- a/.gitignore +++ b/.gitignore @@ -40,3 +40,4 @@ next-env.d.ts # opensrc - source code for packages opensrc .env +prisma-next/ diff --git a/apps/docs/content/docs/orm/next/add-to-existing-project/meta.json b/apps/docs/content/docs/orm/next/add-to-existing-project/meta.json new file mode 100644 index 0000000000..84c814653c --- /dev/null +++ b/apps/docs/content/docs/orm/next/add-to-existing-project/meta.json @@ -0,0 +1,4 @@ +{ + "title": "Add to Existing Project", + "pages": ["postgresql", "mongodb"] +} diff --git a/apps/docs/content/docs/orm/next/add-to-existing-project/mongodb.mdx b/apps/docs/content/docs/orm/next/add-to-existing-project/mongodb.mdx new file mode 100644 index 0000000000..82b6ec84f3 --- /dev/null +++ b/apps/docs/content/docs/orm/next/add-to-existing-project/mongodb.mdx @@ -0,0 +1,199 @@ +--- +title: MongoDB +description: Add Prisma Next to an existing MongoDB project. +url: /orm/next/add-to-existing-project/mongodb +metaTitle: Add Prisma Next to an existing MongoDB project +metaDescription: Add Prisma Next to an existing MongoDB project. +badge: early-access +--- + +This guide shows how to add Prisma Next to a project that already exists and already talks to MongoDB. The first goal is simple: initialize Prisma Next, describe the collections you want to work with, emit the generated artifacts, and then run a couple of queries. + +:::warning[Prisma Next is still in development] + +Prisma Next is not ready for production yet. Prisma ORM 7 is still the recommended choice for production applications today. + +::: + +## Prerequisites + +Before you start, make sure you can already reach the MongoDB deployment this project uses today. + +- Node.js 24 or newer +- npm +- An existing MongoDB 6.0 or newer deployment + +For local development, use a replica set. MongoDB Atlas already gives you that. + +## 1. Make sure you can run the example script + +This first step keeps the rest of the guide smooth by making sure the small TypeScript examples can run locally. + +If your project already runs TypeScript scripts, you can skip this step. + +Otherwise, install the script tooling: + +```npm +npm install --save-dev typescript tsx @types/node +``` + +Then make sure `package.json` contains `"type": "module"`: + +```json title="package.json" +{ + "type": "module" +} +``` + +## 2. Initialize Prisma Next + +Now that the project can run the examples, this step adds the Prisma Next files without changing your existing application code yet. + +From the root of your existing project, run: + +```npm +npx prisma-next init --write-env +``` + +When Prisma Next asks a few setup questions: + +- choose `MongoDB` +- choose `PSL` +- keep the default schema path, `prisma/contract.prisma` + +## 3. Set your database connection string + +With the Prisma Next files in place, the next step is to point them at the same MongoDB deployment your app already uses. + +Update `.env` with the connection string for the MongoDB deployment your app already uses: + +```text title=".env" +DATABASE_URL="mongodb://127.0.0.1:27017/my-app?replicaSet=rs0" +``` + +## 4. Describe the collections you want Prisma Next to know about + +This is the key adoption step for MongoDB, because you decide which part of the existing database Prisma Next should model first. + +PostgreSQL has `contract infer`. MongoDB does not, so this step is manual. + +Open `prisma/contract.prisma` and make it match the collections you want Prisma Next to query first. If your existing database already has `users` and `posts` collections with `email`, `name`, `title`, and `authorId`, the starter contract is already a useful first draft: + +```prisma title="prisma/contract.prisma" +model User { + id ObjectId @id @map("_id") + email String @unique + name String? + posts Post[] + @@map("users") +} + +model Post { + id ObjectId @id @map("_id") + title String + content String? + author User @relation(fields: [authorId], references: [id]) + authorId ObjectId + @@map("posts") +} +``` + +You do not need to model every collection on day one. Start with the part of the database you want to read and write first. + +## 5. Emit the generated artifacts + +Once the contract looks right, this step turns it into the generated files the runtime and query APIs use. + +Run: + +```npm +npx prisma-next contract emit +``` + +This refreshes `prisma/contract.json` and `prisma/contract.d.ts` so the runtime and query APIs are aligned with the contract you just reviewed. + +## 6. Run a simple high-level query + +With the emitted artifacts in place, you can test the higher-level API first and confirm Prisma Next can read the existing collections. + +Create a `script.ts` file: + +```typescript title="script.ts" +import "dotenv/config"; +import { db } from "./prisma/db"; + +async function main() { + const user = await db.orm.users.where({ email: "existing@example.com" }).first(); + console.log(user); + + await db.close(); +} + +main().catch((error) => { + console.error(error); + process.exit(1); +}); +``` + +Run it: + +```npm +npx tsx script.ts +``` + +## 7. Run a simple low-level query + +After the ORM example, this step shows the lower-level MongoDB pipeline builder against the same existing collections. + +Replace `script.ts` with this version: + +```typescript title="script.ts" +import "dotenv/config"; +import { db } from "./prisma/db"; + +async function main() { + const runtime = await db.runtime(); + const plan = db.query + .from("users") + .match((fields) => fields.email.eq("existing@example.com")) + .project("email", "name") + .build(); + + const rows = await runtime.execute(plan); + console.log(rows); + + await db.close(); +} + +main().catch((error) => { + console.error(error); + process.exit(1); +}); +``` + +Run it again: + +```npm +npx tsx script.ts +``` + +## 8. Commands you will use next + +Once Prisma Next is connected to the existing collections, these are the MongoDB commands you will keep using as the project evolves. + +Once Prisma Next is in the project, these are the MongoDB commands to remember: + +```npm +npx prisma-next contract emit +``` + +Run this after you change `prisma/contract.prisma`. + +```npm +npx prisma-next migration plan --name add-user-bio +npx prisma-next migration apply +``` + +Use these when you want Prisma Next to manage a schema change for the collections in your contract. + +You do not need to create a migration just to start reading collections that already exist. Create a migration when you are ready for Prisma Next to own a change. diff --git a/apps/docs/content/docs/orm/next/add-to-existing-project/postgresql.mdx b/apps/docs/content/docs/orm/next/add-to-existing-project/postgresql.mdx new file mode 100644 index 0000000000..1b9dc70291 --- /dev/null +++ b/apps/docs/content/docs/orm/next/add-to-existing-project/postgresql.mdx @@ -0,0 +1,207 @@ +--- +title: Postgres +description: Add Prisma Next to an existing PostgreSQL project. +url: /orm/next/add-to-existing-project/postgresql +metaTitle: Add Prisma Next to an existing Postgres project +metaDescription: Add Prisma Next to an existing PostgreSQL project. +badge: early-access +--- + +This guide shows how to add Prisma Next to a project that already exists and already talks to PostgreSQL. The idea is to keep the first pass small: initialize Prisma Next, infer a contract from the live schema, sign the database, and then run a couple of queries. + +:::warning[Prisma Next is still in development] + +Prisma Next is not ready for production yet. Prisma ORM 7 is still the recommended choice for production applications today. + +::: + +## Prerequisites + +Before you start, make sure you can already reach the PostgreSQL database this project uses today. + +- Node.js 24 or newer +- npm +- An existing PostgreSQL database + +## 1. Make sure you can run the example script + +This first step keeps the rest of the guide smooth by making sure the small TypeScript examples can run locally. + +If your project already runs TypeScript scripts, you can skip this step. + +Otherwise, install the script tooling: + +```npm +npm install --save-dev typescript tsx @types/node +``` + +Then make sure `package.json` contains `"type": "module"`: + +```json title="package.json" +{ + "type": "module" +} +``` + +## 2. Initialize Prisma Next + +Now that the project can run the examples, this step adds the Prisma Next files without changing your existing application code yet. + +From the root of your existing project, run: + +```npm +npx prisma-next init --write-env +``` + +When Prisma Next asks a few setup questions: + +- choose `PostgreSQL` +- choose `PSL` +- keep the default schema path, `prisma/contract.prisma` + +## 3. Set your database connection string + +With the Prisma Next files in place, the next step is to point them at the same database your app already uses. + +Update `.env` with the connection string for the database your app already uses: + +```text title=".env" +DATABASE_URL="postgres://username:password@host:5432/database?sslmode=require" +``` + +## 4. Infer a starter contract from the live database + +This step gives you a starting contract by reading the schema that already exists in PostgreSQL. + +Run: + +```npm +npx prisma-next contract infer --output ./prisma/contract.prisma +``` + +This reads the live PostgreSQL schema and writes a first draft of `prisma/contract.prisma`. + +Open that file and review it before you go on. This is the moment to clean up model names, keep only the tables you want Prisma Next to know about first, and make the file easier to read. + +## 5. Emit the generated artifacts + +Once the contract looks right, this step turns it into the generated files the runtime and CLI use. + +After you are happy with the contract, run: + +```npm +npx prisma-next contract emit +``` + +This refreshes `prisma/contract.json` and `prisma/contract.d.ts` so the runtime and query APIs are aligned with the contract you just reviewed. + +## 6. Sign the database + +After the artifacts are emitted, this step records that the current database matches that contract. + +Now record that the live database matches the emitted contract: + +```npm +npx prisma-next db sign +``` + +This step matters in two common cases: + +- the database has never been signed by Prisma Next before +- the database was signed earlier, but under an older contract hash + +## 7. Run a simple high-level query + +With the database signed, you can test the higher-level API first and confirm Prisma Next is reading the existing schema correctly. + +Create a `script.ts` file: + +```typescript title="script.ts" +import "dotenv/config"; +import { db } from "./prisma/db"; + +async function main() { + const runtime = await db.connect({ url: process.env.DATABASE_URL! }); + + const users = await db.orm.User + .select("id", "email", "name") + .take(2) + .all(); + + console.log(users); + + await runtime.close(); +} + +main().catch((error) => { + console.error(error); + process.exit(1); +}); +``` + +Run it: + +```npm +npx tsx script.ts +``` + +## 8. Run a simple low-level query + +After the ORM example, this step shows the lower-level SQL builder against the same existing schema. + +Replace `script.ts` with this version: + +```typescript title="script.ts" +import "dotenv/config"; +import { db } from "./prisma/db"; + +async function main() { + const runtime = await db.connect({ url: process.env.DATABASE_URL! }); + + const plan = db.sql.user + .select("id", "email", "name") + .limit(2) + .build(); + + const rows = await db.runtime().execute(plan); + console.log(rows); + + await runtime.close(); +} + +main().catch((error) => { + console.error(error); + process.exit(1); +}); +``` + +Run it again: + +```npm +npx tsx script.ts +``` + +## 9. Commands you will use next + +Once Prisma Next is connected to the existing database, these are the PostgreSQL commands you will keep using as the project evolves. + +Once Prisma Next is in the project, these are the PostgreSQL commands to remember: + +```npm +npx prisma-next contract emit +``` + +Run this after you change `prisma/contract.prisma`. + +```npm +npx prisma-next db update +``` + +Use this when you want Prisma Next to update the live database directly so it matches the latest contract. + +```npm +npx prisma-next migration plan --name add-user-bio +npx prisma-next migration apply +``` + +Use these when you want checked-in migration packages instead of a direct database update. diff --git a/apps/docs/content/docs/orm/next/index.mdx b/apps/docs/content/docs/orm/next/index.mdx new file mode 100644 index 0000000000..eace8b9fbd --- /dev/null +++ b/apps/docs/content/docs/orm/next/index.mdx @@ -0,0 +1,172 @@ +--- +title: Prisma Next +description: 'Learn what Prisma Next is, why it exists, and how its main pieces fit together.' +url: /orm/next +metaTitle: What is Prisma Next? +metaDescription: Learn what Prisma Next is, why it exists, and how its main pieces fit together. +badge: early-access +--- + +Prisma Next is the next foundation for Prisma ORM. The goal is simple: describe your data once, keep that description in version control, and use it to drive both your queries and your database changes. + +:::warning[Prisma Next is still in development] + +Prisma Next is not ready for production yet. Prisma ORM 7 is still the recommended choice for production applications today. + +::: + +If you want the broader story first, read [The Next Evolution of Prisma ORM](https://www.prisma.io/blog/the-next-evolution-of-prisma-orm). + +## Why Prisma Next exists + +Prisma Next keeps the part of Prisma that feels approachable. You still describe your data in one place, and you still get a typed way to query it from TypeScript. + +The main change is how much of that workflow becomes explicit. Prisma Next treats your schema as a contract that can be emitted, inspected, compared, and verified. That helps with a few practical problems: + +- it is easier to see what your app expects from the database +- it is easier to choose how database changes should be applied +- it is easier for tools, CI, and AI assistants to work from the same source of truth + +So the big idea is not "more features first." The big idea is a clearer foundation that makes the rest of the workflow easier to reason about. + +## The main pieces to know + +The easiest way to understand Prisma Next is to follow the workflow from setup, to contract, to runtime, and then to database changes. + +### `prisma-next init` + +`prisma-next init` is the starting point. It scaffolds the files Prisma Next needs so you do not have to guess the shape of the project or wire the basics by hand. + +In the guides below, `init` creates a contract file, generated artifacts, a small runtime entrypoint, and a config file for the CLI. That means you can move from "empty folder" to "working project structure" in one step, then spend your time editing the contract instead of setting up plumbing. + +In practice, the generated pieces are: + +- `prisma/contract.prisma` for the contract you edit +- `prisma/contract.json` and `prisma/contract.d.ts` for emitted artifacts +- `prisma/db.ts` for the runtime client +- `prisma-next.config.ts` for CLI configuration + +### Your contract and emitted artifacts + +The contract is the center of the workflow. It describes the models, fields, and relations your application expects. That part is close to what many Prisma users already know. + +What is new is that Prisma Next treats the emitted output as a first-class artifact. When you run `prisma-next contract emit`, Prisma Next turns the contract into machine-readable JSON and matching TypeScript types. The JSON is useful for tooling and verification. The TypeScript types are useful for the runtime and query surfaces. + +That split matters because it gives different parts of the system a dependable artifact to work from. Humans edit the contract. Tooling and runtimes consume the emitted output. + +### The runtime client + +Once the contract is emitted, you create a runtime client from it. This is where Prisma Next starts to feel concrete. + +In the PostgreSQL demo app inside the Prisma Next repo, the runtime is created in `examples/prisma-next-demo/src/prisma/db.ts` like this: + +```typescript title="prisma-next/examples/prisma-next-demo/src/prisma/db.ts" +import pgvector from '@prisma-next/extension-pgvector/runtime'; +import { createTelemetryMiddleware } from '@prisma-next/middleware-telemetry'; +import postgres from '@prisma-next/postgres/runtime'; +import { budgets, lints } from '@prisma-next/sql-runtime'; +import type { Contract } from './contract.d'; +import contractJson from './contract.json' with { type: 'json' }; + +export const db = postgres({ + contractJson, + extensions: [pgvector], + middleware: [ + createTelemetryMiddleware(), + lints(), + budgets({ + maxRows: 10_000, + defaultTableRows: 10_000, + tableRows: { user: 10_000, post: 10_000 }, + maxLatencyMs: 1_000, + }), + ], +}); +``` + +This is a good example of what Prisma Next is aiming for. The contract is the core input, then you compose in extras like middleware, budgets, or extension packs around it. + +The MongoDB examples follow the same idea. In `examples/mongo-blog-leaderboard/src/db.ts`, the runtime is created from the emitted contract with a Mongo-specific runtime entrypoint: + +```typescript title="prisma-next/examples/mongo-blog-leaderboard/src/db.ts" +import mongo from '@prisma-next/mongo/runtime'; +import { ifDefined } from '@prisma-next/utils/defined'; +import type { Contract } from './contract'; +import contractJson from './contract.json' with { type: 'json' }; + +export function createClient(options: { url: string; dbName?: string }) { + return mongo({ + contractJson, + url: options.url, + ...ifDefined('dbName', options.dbName), + }); +} +``` + +So even though the databases are different, the shape is familiar: emit a contract, load it, then create a runtime client for that database family. + +### Two query styles + +Prisma Next gives you two ways to work because not every query wants the same level of abstraction. + +For day-to-day work, the high-level ORM API is usually the easiest path. In the retail store example in the Prisma Next repo, a Mongo helper that reads one user can stay very small: + +```typescript title="prisma-next/examples/retail-store/src/data/users.ts" +export function findUserById(db: Db, id: string) { + return db.orm.users.where({ _id: id }).first(); +} +``` + +This is the "just let me work with models" side of Prisma Next. + +When you want a more explicit query plan, Prisma Next also gives you a lower-level builder. In the PostgreSQL demo, `examples/prisma-next-demo/src/queries/get-users.ts` builds a SQL plan and then executes it: + +```typescript title="prisma-next/examples/prisma-next-demo/src/queries/get-users.ts" +import { db } from '../prisma/db'; + +export async function getUsers(limit = 10) { + const plan = db.sql.user.select('id', 'email', 'createdAt', 'kind').limit(limit).build(); + return db.runtime().execute(plan); +} +``` + +MongoDB has an equivalent lower-level surface, but it uses `db.query` instead of `db.sql`. In the retail store example, pagination is written like this: + +```typescript title="prisma-next/examples/retail-store/src/data/products.ts" +export async function findProductsPaginated(db: Db, skip: number, take: number): Promise { + const plan = db.query.from('products').sort({ _id: 1 }).skip(skip).limit(take).build(); + return collectResults(db, plan); +} +``` + +That is the basic mental model: + +- use `db.orm` when you want the higher-level model API +- use `db.sql` for PostgreSQL when you want an explicit SQL plan +- use `db.query` for MongoDB when you want an explicit pipeline + +### Database change commands + +Prisma Next can apply contract changes in more than one way, and this is one of the most important parts to understand. + +For PostgreSQL, you can use direct database reconciliation commands like `db init` and `db update`. That path is helpful when you want Prisma Next to bring a database in line with the contract directly. PostgreSQL can also use checked-in migration packages with `migration plan` and `migration apply`, which is useful when you want a reviewable change record in version control. + +For MongoDB, the guides below focus on the checked-in migration flow. That means you plan a migration package, review it, and then apply it. + +For existing projects, there is one more piece to know on the PostgreSQL side: `contract infer` and `db sign`. `contract infer` gives you a starter contract from a live schema. `db sign` records that the live database matches the emitted contract so Prisma Next can verify future work against it. + +If you want the background on why Prisma Next is approaching changes this way, start with [Rethinking Database Migrations](https://www.prisma.io/blog/rethinking-database-migrations). For more detail on the Prisma Next workflow itself, see [TypeScript Migrations in Prisma Next](https://www.prisma.io/blog/typescript-migrations-in-prisma-next) and [Data Migrations in Prisma Next](https://www.prisma.io/blog/data-migrations-in-prisma-next). + +## Choose your path + +The guides below are split by both starting point and database so each path can stay specific and easy to follow. + +If you are starting fresh, use one of these quickstarts: + +- [Quickstart for PostgreSQL](/orm/next/quickstart/postgresql) +- [Quickstart for MongoDB](/orm/next/quickstart/mongodb) + +If you want to add Prisma Next to an app that already exists, use one of these: + +- [Add Prisma Next to an existing PostgreSQL project](/orm/next/add-to-existing-project/postgresql) +- [Add Prisma Next to an existing MongoDB project](/orm/next/add-to-existing-project/mongodb) diff --git a/apps/docs/content/docs/orm/next/meta.json b/apps/docs/content/docs/orm/next/meta.json new file mode 100644 index 0000000000..38106636ee --- /dev/null +++ b/apps/docs/content/docs/orm/next/meta.json @@ -0,0 +1,12 @@ +{ + "title": "Next", + "defaultOpen": true, + "root": true, + "pages": [ + "---Introduction---", + "index", + "---Getting started---", + "quickstart", + "add-to-existing-project" + ] +} diff --git a/apps/docs/content/docs/orm/next/quickstart/meta.json b/apps/docs/content/docs/orm/next/quickstart/meta.json new file mode 100644 index 0000000000..3a7edc76ec --- /dev/null +++ b/apps/docs/content/docs/orm/next/quickstart/meta.json @@ -0,0 +1,4 @@ +{ + "title": "Quickstart", + "pages": ["postgresql", "mongodb"] +} diff --git a/apps/docs/content/docs/orm/next/quickstart/mongodb.mdx b/apps/docs/content/docs/orm/next/quickstart/mongodb.mdx new file mode 100644 index 0000000000..d0ca9c4a03 --- /dev/null +++ b/apps/docs/content/docs/orm/next/quickstart/mongodb.mdx @@ -0,0 +1,273 @@ +--- +title: MongoDB +description: Set up Prisma Next from scratch with MongoDB. +url: /orm/next/quickstart/mongodb +metaTitle: 'Quickstart: Prisma Next with MongoDB' +metaDescription: Set up Prisma Next from scratch with MongoDB. +badge: early-access +--- + +[MongoDB](https://www.mongodb.com/) is a document database. In this guide, you will create a small Prisma Next project from scratch, connect it to MongoDB, create the first migration package, apply it, and run both a high-level and a low-level query. + +:::warning[Prisma Next is still in development] + +Prisma Next is not ready for production yet. Prisma ORM 7 is still the recommended choice for production applications today. + +::: + +## Prerequisites + +Before you start, make sure your machine can run the Prisma Next CLI and can connect to a MongoDB deployment that matches the assumptions in this guide. + +- Node.js 24 or newer +- npm +- A MongoDB 6.0 or newer deployment + +For local development, use a replica set. MongoDB Atlas already gives you that. A single standalone `mongod` is not the setup this guide assumes. + +## 1. Create a new project + +This gives you a clean folder so it is easy to see which files Prisma Next creates for you. + +Start with an empty folder: + +```shell +mkdir hello-prisma-next-mongo +cd hello-prisma-next-mongo +``` + +Create a `package.json`: + +```npm +npm init -y +``` + +## 2. Initialize Prisma Next + +This is the setup step where Prisma Next writes the starting files we will use for the rest of the guide. + +Run: + +```npm +npx prisma-next init --write-env +``` + +When Prisma Next asks a few setup questions: + +- choose `MongoDB` +- choose `PSL` +- keep the default schema path, `prisma/contract.prisma` + +This creates the Prisma Next files for you, including `prisma/contract.prisma`, `prisma/db.ts`, `prisma-next.config.ts`, and a starter `.env` file. + +## 3. Add script tooling for the examples + +We add this now so the query examples later run without any extra setup in the middle of the guide. + +The query examples in this guide use a small TypeScript script. Install the tools for that now: + +```npm +npm install --save-dev typescript tsx @types/node +``` + +Then open `package.json` and add `"type": "module"`: + +```json title="package.json" +{ + "type": "module" +} +``` + +`prisma-next init` already created a `tsconfig.json`, so you do not need to create one by hand. + +## 4. Add your MongoDB connection string + +Now that the project files exist, the next step is to point them at the MongoDB deployment you want to use. + +Update `.env` with your MongoDB connection string: + +```text title=".env" +DATABASE_URL="mongodb://127.0.0.1:27017/prisma_next?replicaSet=rs0" +``` + +If you are using MongoDB Atlas, your value will usually start with `mongodb+srv://...`. + +## 5. Review the starter contract + +Before Prisma Next plans any changes, it helps to look at the contract it is about to use. + +Open `prisma/contract.prisma`. After `init`, the starter contract looks like this: + +```prisma title="prisma/contract.prisma" +model User { + id ObjectId @id @map("_id") + email String @unique + name String? + posts Post[] + @@map("users") +} + +model Post { + id ObjectId @id @map("_id") + title String + content String? + author User @relation(fields: [authorId], references: [id]) + authorId ObjectId + @@map("posts") +} +``` + +That is enough for the first run, so you can keep it as-is. + +## 6. Create and apply the first migration package + +This is the first database-facing step, so it is where the contract turns into MongoDB collections and indexes. + +For MongoDB, this guide uses the checked-in migration flow from the start: + +```npm +npx prisma-next migration plan --name init +npx prisma-next migration apply +``` + +That creates the `users` and `posts` collections, adds the `users.email` unique index, and records the migration history for later changes. + +## 7. Run a simple high-level query + +With the collections in place, you can test the higher-level API first and confirm the setup is working end to end. + +Create a `script.ts` file: + +```typescript title="script.ts" +import "dotenv/config"; +import { db } from "./prisma/db"; + +async function main() { + const createdUser = await db.orm.users.create({ + email: `alice+${Date.now()}@example.com`, + name: "Alice", + }); + + console.log(createdUser); + + await db.close(); +} + +main().catch((error) => { + console.error(error); + process.exit(1); +}); +``` + +Run it: + +```npm +npx tsx script.ts +``` + +This is the high-level path. You work with the `users` collection through the ORM surface. + +## 8. Run a simple low-level query + +After the ORM example, this step shows the lower-level MongoDB pipeline builder against the same contract and database. + +Replace `script.ts` with this version: + +```typescript title="script.ts" +import "dotenv/config"; +import { db } from "./prisma/db"; + +async function main() { + const email = `alice+${Date.now()}@example.com`; + + await db.orm.users.create({ + email, + name: "Alice", + }); + + const runtime = await db.runtime(); + const plan = db.query + .from("users") + .match((fields) => fields.email.eq(email)) + .project("email", "name") + .build(); + + const rows = await runtime.execute(plan); + console.log(rows); + + await db.close(); +} + +main().catch((error) => { + console.error(error); + process.exit(1); +}); +``` + +Run it again: + +```npm +npx tsx script.ts +``` + +This is the lower-level path. You build a typed MongoDB pipeline yourself and then execute it. + +## 9. Commands you will use next + +Once the first query works, these are the MongoDB commands you will keep reaching for as the project grows. + +After the first setup, these are the MongoDB commands to remember: + +```npm +npx prisma-next contract emit +``` + +Run this after you change `prisma/contract.prisma`. + +```npm +npx prisma-next migration plan --name add-user-bio +npx prisma-next migration apply +``` + +Use these to create and apply the next contract-driven change. + +This guide uses the migration package workflow on purpose. It gives you a clear, reviewable record of what changed. + +## Want the full Prisma Next docs right now? + +If you want to keep going after this quickstart, the Prisma Next repo already has more examples, demos, and internal docs than we have brought over here so far. Those materials will be cleaned up and moved into the main docs closer to GA. + +Until then, clone the repo and use it as the source of truth for deeper MongoDB examples: + +```shell +git clone https://github.com/prisma/prisma-next.git +cd prisma-next +``` + +For MongoDB, the most useful places to start are: + +- [`README.md`](https://github.com/prisma/prisma-next/blob/main/README.md) +- [`examples/mongo-demo`](https://github.com/prisma/prisma-next/tree/main/examples/mongo-demo) +- [`examples/mongo-blog-leaderboard`](https://github.com/prisma/prisma-next/tree/main/examples/mongo-blog-leaderboard) +- [`docs`](https://github.com/prisma/prisma-next/tree/main/docs) + +If you want help from an assistant after cloning the repo, paste this prompt: + +```text +I cloned the Prisma Next repo locally at ./prisma-next. + +Database: MongoDB +My exact question: +Examples: +- How do I add a new field and ship it with migration plan and migration apply? +- How do I write this read with db.query instead of db.orm? +- How do I model my existing users and posts collections in contract.prisma? + +Please use README.md, docs/, examples/mongo-demo/, and examples/mongo-blog-leaderboard/ as the source of truth. +Please answer with: +1. The exact commands I should run +2. The exact files I should open or edit +3. A minimal code example that matches the repo style +4. Any caveats if the repo and public docs differ +5. The specific repo files you used +``` diff --git a/apps/docs/content/docs/orm/next/quickstart/postgresql.mdx b/apps/docs/content/docs/orm/next/quickstart/postgresql.mdx new file mode 100644 index 0000000000..d589e3175e --- /dev/null +++ b/apps/docs/content/docs/orm/next/quickstart/postgresql.mdx @@ -0,0 +1,281 @@ +--- +title: Postgres +description: Set up Prisma Next from scratch with PostgreSQL. +url: /orm/next/quickstart/postgresql +metaTitle: 'Quickstart: Prisma Next with Postgres' +metaDescription: Set up Prisma Next from scratch with PostgreSQL. +badge: early-access +--- + +[PostgreSQL](https://www.postgresql.org/) is a relational database. In this guide, you will create a small Prisma Next project from scratch, create a PostgreSQL database with `create-db`, create the first tables, and run both a high-level and a low-level query. + +:::warning[Prisma Next is still in development] + +Prisma Next is not ready for production yet. Prisma ORM 7 is still the recommended choice for production applications today. + +::: + +## Prerequisites + +Before you start, make sure your machine can run the Prisma Next CLI and the small TypeScript scripts used later in the guide. + +- Node.js 24 or newer +- npm + +## 1. Create a new project + +This gives you a clean folder so it is easy to see which files Prisma Next creates for you. + +Start with an empty folder: + +```shell +mkdir hello-prisma-next +cd hello-prisma-next +``` + +Create a `package.json`: + +```npm +npm init -y +``` + +## 2. Initialize Prisma Next + +This is the setup step where Prisma Next writes the starting files we will use for the rest of the guide. + +Run: + +```npm +npx prisma-next init --write-env +``` + +When Prisma Next asks a few setup questions: + +- choose `PostgreSQL` +- choose `PSL` +- keep the default schema path, `prisma/contract.prisma` + +This creates the Prisma Next files for you, including `prisma/contract.prisma`, `prisma/db.ts`, `prisma-next.config.ts`, and a starter `.env` file. + +## 3. Add script tooling for the examples + +We add this now so the query examples later run without any extra setup in the middle of the guide. + +The query examples in this guide use a small TypeScript script. Install the tools for that now: + +```npm +npm install --save-dev typescript tsx @types/node +``` + +Then open `package.json` and add `"type": "module"`: + +```json title="package.json" +{ + "type": "module" +} +``` + +`prisma-next init` already created a `tsconfig.json`, so you do not need to create one by hand. + +## 4. Create a PostgreSQL database + +Now that the project files exist, the next step is to create a real database for Prisma Next to connect to. + +Now create a temporary PostgreSQL database: + +```npm +npx create-db@latest +``` + +The command prints a `postgres://...` connection string. Copy that value into `.env`: + +```text title=".env" +DATABASE_URL="postgres://username:password@db.prisma.io:5432/postgres?sslmode=require" +``` + +## 5. Review the starter contract + +Before Prisma Next changes the database, it helps to look at the contract it is about to apply. + +Open `prisma/contract.prisma`. After `init`, the starter contract looks like this: + +```prisma title="prisma/contract.prisma" +model User { + id Int @id @default(autoincrement()) + email String @unique + name String? + posts Post[] + createdAt DateTime @default(now()) +} + +model Post { + id Int @id @default(autoincrement()) + title String + content String? + author User @relation(fields: [authorId], references: [id]) + authorId Int + createdAt DateTime @default(now()) +} +``` + +That is enough for the first run, so you can keep it as-is. + +## 6. Create the first tables + +This is the first database-facing step, so it is where the contract turns into real PostgreSQL tables. + +Run: + +```npm +npx prisma-next db init +``` + +This bootstraps the database to match the current contract and signs the database so Prisma Next knows which contract it matches. + +## 7. Run a simple high-level query + +With the tables in place, you can test the higher-level API first and confirm the setup is working end to end. + +Create a `script.ts` file: + +```typescript title="script.ts" +import "dotenv/config"; +import { db } from "./prisma/db"; + +async function main() { + const runtime = await db.connect({ url: process.env.DATABASE_URL! }); + + const createdUser = await db.orm.User + .select("id", "email", "name", "createdAt") + .create({ + email: `alice+${Date.now()}@example.com`, + name: "Alice", + }); + + console.log(createdUser); + + await runtime.close(); +} + +main().catch((error) => { + console.error(error); + process.exit(1); +}); +``` + +Run it: + +```npm +npx tsx script.ts +``` + +This is the high-level path. You work with the `User` model and let Prisma Next handle the SQL planning for you. + +## 8. Run a simple low-level query + +After the ORM example, this step shows the lower-level SQL builder against the same contract and database. + +Replace `script.ts` with this version: + +```typescript title="script.ts" +import "dotenv/config"; +import { db } from "./prisma/db"; + +async function main() { + const runtime = await db.connect({ url: process.env.DATABASE_URL! }); + const email = `alice+${Date.now()}@example.com`; + + await db.orm.User.create({ + email, + name: "Alice", + }); + + const plan = db.sql.user + .select("id", "email", "name", "createdAt") + .where((fields, fns) => fns.eq(fields.email, email)) + .build(); + + const rows = await db.runtime().execute(plan); + console.log(rows); + + await runtime.close(); +} + +main().catch((error) => { + console.error(error); + process.exit(1); +}); +``` + +Run it again: + +```npm +npx tsx script.ts +``` + +This is the lower-level path. You build a typed SQL plan yourself and then execute it. + +## 9. Commands you will use next + +Once the first query works, these are the PostgreSQL commands you will keep reaching for as the project grows. + +After the first setup, these are the PostgreSQL commands to remember: + +```npm +npx prisma-next contract emit +``` + +Run this after you change `prisma/contract.prisma`. + +```npm +npx prisma-next db update +``` + +Use this when you want Prisma Next to update the live database directly so it matches the latest contract. + +```npm +npx prisma-next migration plan --name add-user-bio +npx prisma-next migration apply +``` + +Use these when you want checked-in migration packages instead of a direct database update. + +PostgreSQL supports both workflows. Many teams pick one and stay consistent: either direct reconciliation with `db init` and `db update`, or checked-in migration packages with `migration plan` and `migration apply`. + +## Want the full Prisma Next docs right now? + +If you want to keep going after this quickstart, the Prisma Next repo already has more examples, demos, and internal docs than we have brought over here so far. Those materials will be cleaned up and moved into the main docs closer to GA. + +Until then, clone the repo and use it as the source of truth for deeper examples: + +```shell +git clone https://github.com/prisma/prisma-next.git +cd prisma-next +``` + +For PostgreSQL, the most useful places to start are: + +- [`README.md`](https://github.com/prisma/prisma-next/blob/main/README.md) +- [`examples/prisma-next-demo`](https://github.com/prisma/prisma-next/tree/main/examples/prisma-next-demo) +- [`docs`](https://github.com/prisma/prisma-next/tree/main/docs) + +If you want help from an assistant after cloning the repo, paste this prompt: + +```text +I cloned the Prisma Next repo locally at ./prisma-next. + +Database: PostgreSQL +My exact question: +Examples: +- How do I add a Profile table and query it with db.orm? +- How do I choose between db update and migration plan for this change? +- How do I write the same read using db.sql instead of db.orm? + +Please use README.md, docs/, and examples/prisma-next-demo/ as the source of truth. +Please answer with: +1. The exact commands I should run +2. The exact files I should open or edit +3. A minimal code example that matches the repo style +4. Any caveats if the repo and public docs differ +5. The specific repo files you used +``` diff --git a/apps/docs/src/lib/version.ts b/apps/docs/src/lib/version.ts index a868ef86ca..2db70c3829 100644 --- a/apps/docs/src/lib/version.ts +++ b/apps/docs/src/lib/version.ts @@ -152,7 +152,7 @@ export function getOrmVersionFromRoute(route?: string | string[]): Version | nul export function getOrmVersions(tree: PageTree.Root): Version[] { const ormNode = findOrmNode(tree as TreeNode); - const versions = new Set(); + const versions = new Set(["next", "v6"]); for (const child of ormNode?.children ?? []) { const version = getVersionFromNode(child); @@ -161,5 +161,5 @@ export function getOrmVersions(tree: PageTree.Root): Version[] { } } - return [LATEST_VERSION, "v6", ...Array.from(versions).sort(compareVersionsDescending)]; + return [LATEST_VERSION, ...Array.from(versions).sort(compareVersionsDescending)]; }