diff --git a/.github/workflows/config/.linkspector.yml b/.github/workflows/config/.linkspector.yml deleted file mode 100644 index 0d06293a36..0000000000 --- a/.github/workflows/config/.linkspector.yml +++ /dev/null @@ -1,19 +0,0 @@ -dirs: - - content -useGitIgnore: true -ignorePatterns: - - pattern: "^/.*" # local links are not checked - - pattern: "^http://localhost.*" # Localhost links are not checked - - pattern: "^https://packagecontrol.*" # Package control links are not checked (it was 500ing at time of writing) - - pattern: "^https://(www|dash).cloudflare.com.*" # Cloudflare links return 403 at time of writing - -fileExtensions: - - mdx - - md -modifiedFilesOnly: false -aliveStatusCodes: - - 200 - - 201 - - 204 - - 304 - - 403 diff --git a/.github/workflows/linkspector.yml b/.github/workflows/linkspector.yml deleted file mode 100644 index e428cf19b6..0000000000 --- a/.github/workflows/linkspector.yml +++ /dev/null @@ -1,18 +0,0 @@ -name: Linkspector -on: [pull_request] -jobs: - check-links: - name: runner / linkspector - runs-on: ubuntu-22.04 - permissions: - contents: write - steps: - - uses: actions/checkout@v4 - - name: Run linkspector - uses: umbrelladocs/action-linkspector@v1.3.7 - with: - github_token: ${{ secrets.github_token }} - reporter: github-pr-check - fail_on_error: true - filter_mode: nofilter - config_file: .github/workflows/config/.linkspector.yml \ No newline at end of file diff --git a/.github/workflows/lychee.yml b/.github/workflows/lychee.yml index 0b705f533c..4664852761 100644 --- a/.github/workflows/lychee.yml +++ b/.github/workflows/lychee.yml @@ -33,6 +33,7 @@ jobs: --exclude 'http://localhost.*' --exclude 'https://localhost.*' --exclude 'https://cockroachlabs.com' + --exclude 'https://www.gnu.org' --exclude '^/.*' './**/*.md' './**/*.mdx' workingDirectory: "content" @@ -58,6 +59,7 @@ jobs: --exclude 'http://localhost.*' --exclude 'https://localhost.*' --exclude 'https://cockroachlabs.com' + --exclude 'https://www.gnu.org' --exclude '^/.*' './**/*.md' './**/*.mdx' workingDirectory: "content" @@ -95,7 +97,7 @@ jobs: fi - name: 📝 Comment Broken Links - if: ${{ always() && github.event.pull_request.head.repo.fork == false }} + if: ${{ always() && github.event.pull_request.head.repo.fork == false && (steps.lychee.outputs.exit_code != 0 || (steps.lychee-retry.conclusion != 'skipped' && steps.lychee-retry.outputs.exit_code != 0)) }} uses: peter-evans/create-or-update-comment@v4 with: issue-number: ${{ github.event.pull_request.number }} diff --git a/cSpell.json b/cSpell.json index 5a422bc426..f3040ad1de 100644 --- a/cSpell.json +++ b/cSpell.json @@ -158,7 +158,8 @@ "Buildpacks", "Sevalla's", "Dataguide", - "justinellingwood" + "justinellingwood", + "Millis" ], "patterns": [ { @@ -212,4 +213,4 @@ "HTML Tags" ], "ignorePaths": [] -} \ No newline at end of file +} diff --git a/content/100-getting-started/01-quickstart-prismaPostgres.mdx b/content/100-getting-started/01-quickstart-prismaPostgres.mdx deleted file mode 100644 index 404c632267..0000000000 --- a/content/100-getting-started/01-quickstart-prismaPostgres.mdx +++ /dev/null @@ -1,159 +0,0 @@ ---- -title: 'Quickstart with Prisma Postgres' -sidebar_label: 'Quickstart' -metaTitle: 'Quickstart with TypeScript & Prisma Postgres' -metaDescription: 'Get started with Prisma ORM in 5 minutes. You will learn how to run migrations and send queries with a Prisma Postgres database.' -search: true -sidebar_class_name: hidden-sidebar -dbSwitcher: ['prismaPostgres', 'sqlite'] -slugSwitch: /getting-started/quickstart- -sidebar_custom_props: { badge: '5 min' } -community_section: true ---- - -In this Quickstart guide, you'll learn how to get started from scratch with Prisma ORM and a **Prisma Postgres** database in a plain **TypeScript** project. It covers the following workflows: - -- Creating a [Prisma Postgres](https://www.prisma.io/postgres?utm_source=docs) database -- Schema migrations and queries (via [Prisma ORM](https://www.prisma.io/orm)) -- Connection pooling and caching (via [Prisma Accelerate](https://www.prisma.io/accelerate)) - -:::note - -If you want to use Prisma Postgres with another ORM or database library (like Drizzle ORM, TypeORM or Kysely), you can follow the instructions [here](/postgres/introduction/getting-started#connect-via-any-database-library--tool). - -::: - -## Prerequisites - -To successfully complete this tutorial, you need: -- a [Prisma Data Platform](https://console.prisma.io/) (PDP) account -- [Node.js](https://nodejs.org/en/) installed on your machine (see [system requirements](/orm/reference/system-requirements) for officially supported versions) - -## 1. Set up a Prisma Postgres database in the Platform Console - -Follow these steps to create your Prisma Postgres database: - -1. Log in to [Prisma Data Platform](https://console.prisma.io/) and open the Console. -1. In a [workspace](/platform/about#workspace) of your choice, click the **New project** button. -1. Type a name for your project in the **Name** field, e.g. **hello-ppg**. -1. In the **Prisma Postgres** section, click the **Get started** button. -1. In the **Region** dropdown, select the region that's closest to your current location, e.g. **US East (N. Virginia)**. -1. Click the **Create project** button. - -At this point, you'll be redirected to the **Database** page where you will need to wait for a few seconds while the status of your database changes from **`PROVISIONING`** to **`CONNECTED`**. - -Once the green **`CONNECTED`** label appears, your database is ready to use! - -## 2. Download example and install dependencies - -Copy the `try-prisma` command that's shown in the Console, paste it into your terminal and execute it. - -For reference, this is what the command looks like: - -```terminal -npx try-prisma@latest \ - --template databases/prisma-postgres \ - --name hello-prisma \ - --install npm -``` - -Once the `try-prisma` command has terminated, navigate into the project directory: - -```terminal -cd hello-prisma -``` - -## 3. Set database connection URL - -The connection to your database is configured via an environment variable in a `.env` file. - -First, rename the existing `.env.example` file to just `.env`: - -```terminal -mv .env.example .env -``` - -Then, in your project environment in the Platform console, find your database credentials in the **Set up database access** section, copy the `DATABASE_URL` environment variable and paste them into the `.env` file. - -For reference, the file should now look similar to this: - -```bash no-copy -DATABASE_URL="prisma+postgres://accelerate.prisma-data.net/?api_key=ey...." -``` - -## 4. Create database tables (with a schema migration) - -Next, you need to create the tables in your database. You can do this by creating and executing a schema migration with the following command of the Prisma CLI: - -```terminal -npx prisma migrate dev --name init -``` - -This will map the `User` and `Post` models that are defined in your [Prisma schema](/orm/prisma-schema/) to your database. You can also review the SQL migration that was executed and created the tables in the newly created `prisma/migrations` directory. - -## 5. Execute queries with Prisma ORM - -The [`src/queries.ts`](https://github.com/prisma/prisma-examples/blob/latest/databases/prisma-postgres/src/queries.ts) script contains a number of CRUD queries that will write and read data in your database. You can execute it by running the following command in your terminal: - -```terminal -npm run queries -``` - -Once the script has completed, you can inspect the logs in your terminal or use Prisma Studio to explore what records have been created in the database: - -```terminal -npx prisma studio -``` - -## 6. Explore caching with Prisma Accelerate - -The [`src/caching.ts`](https://github.com/prisma/prisma-examples/blob/latest/databases/prisma-postgres/src/caching.ts) script contains a sample query that uses [Stale-While-Revalidate](/postgres/database/caching#stale-while-revalidate-swr) (SWR) and [Time-To-Live](/postgres/database/caching#time-to-live-ttl) (TTL) to cache a database query using Prisma Accelerate. You can execute it as follows: - -```terminal -npm run caching -``` - -Take note of the time that it took to execute the query, e.g.: - -```no-copy -The query took 2009.2467149999998ms. -``` - -Now, run the script again: - -```terminal -npm run caching -``` - -You'll notice that the time the query took will be a lot shorter this time, e.g.: - -```no-copy -The query took 300.5655280000001ms. -``` - -## 7. Next steps - -In this Quickstart guide, you have learned how to get started with Prisma ORM in a plain TypeScript project. Feel free to explore the Prisma Client API a bit more on your own, e.g. by including filtering, sorting, and pagination options in the `findMany` query or exploring more operations like `update` and `delete` queries. - -### Explore the data in Prisma Studio - -Prisma ORM comes with a built-in GUI to view and edit the data in your database. You can open it using the following command: - -```terminal -npx prisma studio -``` - -With Prisma Postgres, you can also directly use Prisma Studio inside the [Console](https://console.prisma.io) by selecting the **Studio** tab in your project. - -### Build a fullstack app with Next.js - -Learn how to use Prisma Postgres in a fullstack app: - -- [Build a fullstack app with Next.js 15](/guides/nextjs) -- [Next.js 15 example app](https://github.com/prisma/nextjs-prisma-postgres-demo) (including authentication) - -### Explore ready-to-run Prisma ORM examples - -Check out the [`prisma-examples`](https://github.com/prisma/prisma-examples/) repository on GitHub to see how Prisma ORM can be used with your favorite library. The repo contains examples with Express, NestJS, GraphQL as well as fullstack examples with Next.js and Vue.js, and a lot more. - -These examples use SQLite by default but you can follow the instructions in the project README to switch to Prisma Postgres in a few simple steps. \ No newline at end of file diff --git a/content/100-getting-started/01-quickstart-sqlite.mdx b/content/100-getting-started/01-quickstart-sqlite.mdx deleted file mode 100644 index 79feb9783b..0000000000 --- a/content/100-getting-started/01-quickstart-sqlite.mdx +++ /dev/null @@ -1,465 +0,0 @@ ---- -title: 'Quickstart with SQLite' -sidebar_label: 'Quickstart' -metaTitle: 'Quickstart with TypeScript & SQLite' -metaDescription: 'Get started with Prisma ORM in 5 minutes. You will learn how to send queries to a SQLite database in a plain TypeScript script using Prisma Client.' -search: true -sidebar_class_name: hidden-sidebar -dbSwitcher: ['prismaPostgres', 'sqlite'] -slugSwitch: /getting-started/quickstart- -sidebar_custom_props: { badge: '5 min' } -community_section: true ---- - -In this Quickstart guide, you'll learn how to get started with Prisma ORM from scratch using a plain **TypeScript** project and a local **SQLite** database file. It covers **data modeling**, **migrations** and **querying** a database. - -If you want to use Prisma ORM with your own PostgreSQL, MySQL, MongoDB or any other supported database, go here instead: - -- [Start with Prisma ORM from scratch](/getting-started/setup-prisma/start-from-scratch/relational-databases-typescript-postgresql) -- [Add Prisma ORM to an existing project](/getting-started/setup-prisma/add-to-existing-project/relational-databases-typescript-postgresql) - -## Prerequisites - -You need [Node.js](https://nodejs.org/en/) installed on your machine (see [system requirements](/orm/reference/system-requirements) for officially supported versions). - -## 1. Create TypeScript project and set up Prisma ORM - -As a first step, create a project directory and navigate into it: - -```terminal -mkdir hello-prisma -cd hello-prisma -``` - -Next, initialize a TypeScript project using npm: - -```terminal -npm init -y -npm install typescript tsx @types/node --save-dev -``` - -This creates a `package.json` with an initial setup for your TypeScript app. - -:::info - -See [installation instructions](/orm/tools/prisma-cli#installation) to learn how to install Prisma using a different package manager. - -::: - -Now, initialize TypeScript: - -```terminal -npx tsc --init -``` - -Then, install the Prisma CLI as a development dependency in the project: - -```terminal -npm install prisma --save-dev -``` - -Finally, set up Prisma ORM with the `init` command of the Prisma CLI: - -```terminal -npx prisma init --datasource-provider sqlite --output ../generated/prisma -``` - -This creates a new `prisma` directory with a `schema.prisma` file and configures SQLite as your database. You're now ready to model your data and create your database with some tables. - -## 2. Model your data in the Prisma schema - -The Prisma schema provides an intuitive way to model data. Add the following models to your `schema.prisma` file: - -```prisma file=prisma/schema.prisma showLineNumbers -model User { - id Int @id @default(autoincrement()) - email String @unique - name String? - posts Post[] -} - -model Post { - id Int @id @default(autoincrement()) - title String - content String? - published Boolean @default(false) - author User @relation(fields: [authorId], references: [id]) - authorId Int -} -``` - -Models in the Prisma schema have two main purposes: - -- Represent the tables in the underlying database -- Serve as foundation for the generated Prisma Client API - -In the next section, you will map these models to database tables using Prisma Migrate. - -## 3. Run a migration to create your database tables with Prisma Migrate - -At this point, you have a Prisma schema but no database yet. Run the following command in your terminal to create the SQLite database and the `User` and `Post` tables represented by your models: - -```terminal -npx prisma migrate dev --name init -``` - -This command did three things: - -1. It created a new SQL migration file for this migration in the `prisma/migrations` directory. -2. It executed the SQL migration file against the database. -3. It ran `prisma generate` under the hood (which installed the `@prisma/client` package and generated a tailored Prisma Client API based on your models). - -Because the SQLite database file didn't exist before, the command also created it inside the `prisma` directory with the name `dev.db` as defined via the environment variable in the `.env` file. - -Congratulations, you now have your database and tables ready. Let's go and learn how you can send some queries to read and write data! - -## 4. Explore how to send queries to your database with Prisma Client - -To get started with Prisma Client, you need to install the `@prisma/client` package: - -```terminal copy -npm install @prisma/client -``` - -The install command invokes `prisma generate` for you which reads your Prisma schema and generates a version of Prisma Client that is _tailored_ to your models. - -To send queries to the database, you will need a TypeScript file to execute your Prisma Client queries. Create a new file called `script.ts` for this purpose: - -```terminal -touch script.ts -``` - -Then, paste the following boilerplate into it: - -```ts file=script.ts showLineNumbers -import { PrismaClient } from './generated/prisma' - -const prisma = new PrismaClient() - -async function main() { - // ... you will write your Prisma Client queries here -} - -main() - .then(async () => { - await prisma.$disconnect() - }) - .catch(async (e) => { - console.error(e) - await prisma.$disconnect() - process.exit(1) - }) -``` - -This code contains a `main` function that's invoked at the end of the script. It also instantiates `PrismaClient` which represents the query interface to your database. - -### 4.1. Create a new `User` record - -Let's start with a small query to create a new `User` record in the database and log the resulting object to the console. Add the following code to your `script.ts` file: - -```ts file=script.ts highlight=6-12;add showLineNumbers -import { PrismaClient } from './generated/prisma' - -const prisma = new PrismaClient() - -async function main() { - // add-start - const user = await prisma.user.create({ - data: { - name: 'Alice', - email: 'alice@prisma.io', - }, - }) - console.log(user) - // add-end -} - -main() - .then(async () => { - await prisma.$disconnect() - }) - .catch(async (e) => { - console.error(e) - await prisma.$disconnect() - process.exit(1) - }) -``` - -Instead of copying the code, you can type it out in your editor to experience the autocompletion Prisma Client provides. You can also actively invoke the autocompletion by pressing the CTRL+SPACE keys on your keyboard. - -Next, execute the script with the following command: - - - - - -```terminal -npx tsx script.ts -``` - - - - -```code no-copy -{ id: 1, email: 'alice@prisma.io', name: 'Alice' } -``` - - - - - -Great job, you just created your first database record with Prisma Client! 🎉 - -In the next section, you'll learn how to read data from the database. - -### 4.2. Retrieve all `User` records - -Prisma Client offers various queries to read data from your database. In this section, you'll use the `findMany` query that returns _all_ the records in the database for a given model. - -Delete the previous Prisma Client query and add the new `findMany` query instead: - -```ts file=script.ts highlight=6-7;add showLineNumbers -import { PrismaClient } from './generated/prisma' - -const prisma = new PrismaClient() - -async function main() { - // add-start - const users = await prisma.user.findMany() - console.log(users) - // add-end -} - -main() - .then(async () => { - await prisma.$disconnect() - }) - .catch(async (e) => { - console.error(e) - await prisma.$disconnect() - process.exit(1) - }) -``` - -Execute the script again: - - - - - -```terminal -npx tsx script.ts -``` - - - - - -```code no-copy -[{ id: 1, email: 'alice@prisma.io', name: 'Alice' }] -``` - - - - - -Notice how the single `User` object is now enclosed with square brackets in the console. That's because the `findMany` returned an array with a single object inside. - -### 4.3. Explore relation queries with Prisma Client - -One of the main features of Prisma Client is the ease of working with [relations](/orm/prisma-schema/data-model/relations). In this section, you'll learn how to create a `User` and a `Post` record in a nested write query. Afterwards, you'll see how you can retrieve the relation from the database using the `include` option. - -First, adjust your script to include the nested query: - -```ts file=script.ts highlight=6-24;add showLineNumbers -import { PrismaClient } from './generated/prisma' - -const prisma = new PrismaClient() - -async function main() { - // add-start - const user = await prisma.user.create({ - data: { - name: 'Bob', - email: 'bob@prisma.io', - posts: { - create: [ - { - title: 'Hello World', - published: true - }, - { - title: 'My second post', - content: 'This is still a draft' - } - ], - }, - }, - }) - console.log(user) - // add-end -} - -main() - .then(async () => { - await prisma.$disconnect() - }) - .catch(async (e) => { - console.error(e) - await prisma.$disconnect() - process.exit(1) - }) -``` - -Run the query by executing the script again: - - - - - -```terminal -npx tsx script.ts -``` - - - - - -```code no-copy -{ id: 2, email: 'bob@prisma.io', name: 'Bob' } -``` - - - - - -By default, Prisma Client only returns _scalar_ fields in the result objects of a query. That's why, even though you also created a new `Post` record for the new `User` record, the console only printed an object with three scalar fields: `id`, `email` and `name`. - -In order to also retrieve the `Post` records that belong to a `User`, you can use the `include` option via the `posts` relation field: - -```ts file=script.ts highlight=6-11;add showLineNumbers -import { PrismaClient } from './generated/prisma' - -const prisma = new PrismaClient() - -async function main() { -// add-start - const usersWithPosts = await prisma.user.findMany({ - include: { - posts: true, - }, - }) - console.dir(usersWithPosts, { depth: null }) - // add-end -} - -main() - .then(async () => { - await prisma.$disconnect() - }) - .catch(async (e) => { - console.error(e) - await prisma.$disconnect() - process.exit(1) - }) -``` - -Run the script again to see the results of the nested read query: - - - - - -```terminal -npx tsx script.ts -``` - - - - - -```code no-copy -[ - { id: 1, email: 'alice@prisma.io', name: 'Alice', posts: [] }, - { - id: 2, - email: 'bob@prisma.io', - name: 'Bob', - posts: [ - { - id: 1, - title: 'Hello World', - content: null, - published: true, - authorId: 2 - }, - { - id: 2, - title: 'My second post', - content: 'This is still a draft', - published: false, - authorId: 2 - } - ] - } -] -``` - - - - - -This time, you're seeing two `User` objects being printed. Both of them have a `posts` field (which is empty for `"Alice"` and populated with two `Post` objects for `"Bob"`) that represents the `Post` records associated with them. - -Notice that the objects in the `usersWithPosts` array are fully typed as well. This means you will get autocompletion and the TypeScript compiler will prevent you from accidentally typing them. - -## 5. Next steps - -In this Quickstart guide, you have learned how to get started with Prisma ORM in a plain TypeScript project. Feel free to explore the Prisma Client API a bit more on your own, e.g. by including filtering, sorting, and pagination options in the `findMany` query or exploring more operations like `update` and `delete` queries. - -### Explore the data in Prisma Studio - -Prisma ORM comes with a built-in GUI to view and edit the data in your database. You can open it using the following command: - -```terminal -npx prisma studio -``` - -### Set up Prisma ORM with your own database - -If you want to move forward with Prisma ORM using your own PostgreSQL, MySQL, MongoDB or any other supported database, follow the Set Up Prisma ORM guides: - -- [Start with Prisma ORM from scratch](/getting-started/setup-prisma/start-from-scratch/relational-databases-typescript-postgresql) -- [Add Prisma ORM to an existing project](/getting-started/setup-prisma/add-to-existing-project) - -### Get query insights and analytics with Prisma Optimize - -[Prisma Optimize](/optimize) helps you generate insights and provides recommendations that can help you make your database queries faster. - -Optimize aims to help developers of all skill levels write efficient database queries, reducing database load and making applications more responsive. - -### Explore ready-to-run Prisma ORM examples - -Check out the [`prisma-examples`](https://github.com/prisma/prisma-examples/) repository on GitHub to see how Prisma ORM can be used with your favorite library. The repo contains examples with Express, NestJS, GraphQL as well as fullstack examples with Next.js and Vue.js, and a lot more. - -### Speed up your database queries with Prisma Accelerate - -[Prisma Accelerate](/accelerate) is a connection pooler and global database cache that can drastically speed up your database queries. Check out the [Speed Test](https://accelerate-speed-test.prisma.io/) or try Accelerate with your favorite framework: - -| Demo | Description | -| ----------------------------------------------- | -------------------------------------------------------------------------- | -| [`nextjs-starter`](https://github.com/prisma/prisma-examples/tree/latest/accelerate/nextjs-starter) | A Next.js project using Prisma Accelerate's caching and connection pooling | -| [`svelte-starter`](https://github.com/prisma/prisma-examples/tree/latest/accelerate/svelte-starter) | A SvelteKit project using Prisma Accelerate's caching and connection pooling | -| [`solidstart-starter`](https://github.com/prisma/prisma-examples/tree/latest/accelerate/solidstart-starter) | A Solidstart project using Prisma Accelerate's caching and connection pooling | -| [`remix-starter`](https://github.com/prisma/prisma-examples/tree/latest/accelerate/remix-starter) | A Remix project using Prisma Accelerate's caching and connection pooling | -| [`nuxt-starter`](https://github.com/prisma/prisma-examples/tree/latest/accelerate/nuxtjs-starter) | A Nuxt.js project using Prisma Accelerate's caching and connection pooling | -| [`astro-starter`](https://github.com/prisma/prisma-examples/tree/latest/accelerate/astro-starter) | An Astro project using Prisma Accelerate's caching and connection pooling | - - -### Build an app with Prisma ORM - -The Prisma blog features comprehensive tutorials about Prisma ORM, check out our latest ones: - -- [Build a fullstack app with Next.js](https://www.youtube.com/watch?v=QXxy8Uv1LnQ&ab_channel=ByteGrad) -- [Build a fullstack app with Remix](https://www.prisma.io/blog/fullstack-remix-prisma-mongodb-1-7D0BfTXBmB6r) (5 parts, including videos) -- [Build a REST API with NestJS](https://www.prisma.io/blog/nestjs-prisma-rest-api-7D056s1BmOL0) \ No newline at end of file diff --git a/content/100-getting-started/02-prisma-orm/100-quickstart/100-prisma-postgres.mdx b/content/100-getting-started/02-prisma-orm/100-quickstart/100-prisma-postgres.mdx new file mode 100644 index 0000000000..c73c259d73 --- /dev/null +++ b/content/100-getting-started/02-prisma-orm/100-quickstart/100-prisma-postgres.mdx @@ -0,0 +1,276 @@ +--- +title: 'Quickstart with Prisma ORM and Prisma Postgres' +sidebar_label: 'Prisma Postgres' +metaTitle: 'Quickstart: Prisma ORM with Prisma Postgres (5 min)' +metaDescription: 'Create a new TypeScript project from scratch by connecting Prisma ORM to Prisma Postgres and generating a Prisma Client for database access.' +sidebar_custom_props: { badge: '5 min' } +--- + +import Prerequisites from '../../_components/_prerequisites.mdx' +import CreateProject from '../../_components/_create-project.mdx' +import ExploreData from '../../_components/_explore-data.mdx' +import NextSteps from '../../_components/_next-steps.mdx' + +[Prisma Postgres](/postgres) is a fully managed PostgreSQL database that scales to zero and integrates smoothly with both Prisma ORM and Prisma Studio. In this guide, you will learn how to set up a new TypeScript project from scratch, connect it to Prisma Postgres using Prisma ORM, and generate a Prisma Client for easy, type-safe access to your database. + +## Prerequisites + + + +## 1. Create a new project + + + +## 2. Install required dependencies + +Install the packages needed for this quickstart: + +```terminal +npm install prisma @types/node --save-dev +npm install @prisma/client @prisma/adapter-pg dotenv +``` + +Here's what each package does: + +- **`prisma`** - The Prisma CLI for running commands like `prisma init`, `prisma migrate`, and `prisma generate` +- **`@prisma/client`** - The Prisma Client library for querying your database +- **`@prisma/adapter-pg`** - The [`node-postgres` driver adapter](/orm/overview/databases/postgresql#using-the-node-postgres-driver) that connects Prisma Client to your database +- **`dotenv`** - Loads environment variables from your `.env` file + +## 3. Configure ESM support + +Update `tsconfig.json` for ESM compatibility: + +```json file=tsconfig.json +{ + "compilerOptions": { + "module": "ESNext", + "moduleResolution": "node", + "target": "ES2023", + "strict": true, + "esModuleInterop": true, + "ignoreDeprecations": "6.0" + } +} +``` + +Update `package.json` to enable ESM: + +```json file=package.json +{ + // add-start + "type": "module", + // add-end +} +``` + +## 4. Initialize Prisma ORM and create a Prisma Postgres database + +You can now invoke the Prisma CLI by prefixing it with `npx`: + +```terminal +npx prisma +``` + +Next, set up your Prisma ORM project by creating your [Prisma Schema](/orm/prisma-schema) file with the following command: + +```terminal +npx prisma init --db --output ../generated/prisma +``` + +:::info + +You'll need to answer a few questions while setting up your Prisma Postgres database. Select the region closest to your location and a memorable name for your database. + +::: + +This command does a few things: + +- Creates a `prisma/` directory with a `schema.prisma` file containing your database connection and schema models +- Creates a new Prisma Postgres database (when using `--db` flag) +- Creates a `.env` file in the root directory for environment variables +- Generates the Prisma Client in the `generated/prisma/` directory +- Creates a `prisma.config.ts` file for Prisma configuration + +The generated `prisma.config.ts` file looks like this: + +```typescript file=prisma.config.ts +import { defineConfig, env } from 'prisma/config' + +export default defineConfig({ + schema: 'prisma/schema.prisma', + migrations: { + path: 'prisma/migrations', + }, + datasource: { + url: env('DATABASE_URL'), + }, +}) +``` + +Add `dotenv` to `prisma.config.ts` so that Prisma can load environment variables from your `.env` file: + +```typescript file=prisma.config.ts +// add-start +import 'dotenv/config' +// add-end +import { defineConfig, env } from 'prisma/config' + +export default defineConfig({ + schema: 'prisma/schema.prisma', + migrations: { + path: 'prisma/migrations', + }, + datasource: { + url: env('DATABASE_URL'), + }, +}) +``` + +The generated schema uses [the ESM-first `prisma-client` generator](/orm/prisma-schema/overview/generators#prisma-client) with a custom output path: + +```prisma file=prisma/schema.prisma +generator client { + provider = "prisma-client" + output = "../generated/prisma" +} + +datasource db { + provider = "postgresql" +} +``` + +## 5. Define your data model + +Open `prisma/schema.prisma` and add the following models: + +```prisma file=prisma/schema.prisma +generator client { + provider = "prisma-client" + output = "../generated/prisma" +} + +datasource db { + provider = "postgresql" +} + +//add-start +model User { + id Int @id @default(autoincrement()) + email String @unique + name String? + posts Post[] +} + +model Post { + id Int @id @default(autoincrement()) + title String + content String? + published Boolean @default(false) + author User @relation(fields: [authorId], references: [id]) + authorId Int +} +//add-end +``` + +## 6. Create and apply your first migration + +Create your first migration to set up the database tables: + +```terminal +npx prisma migrate dev --name init +``` + +This command creates the database tables based on your schema. + +Now run the following command to generate the Prisma Client: + +```terminal +npx prisma generate +``` + +## 7. Instantiate Prisma Client + +Now that you have all the dependencies installed, you can instantiate Prisma Client. You need to pass an instance of Prisma ORM's driver adapter to the `PrismaClient` constructor: + +```typescript file=lib/prisma.ts +import "dotenv/config"; +import { PrismaPg } from '@prisma/adapter-pg' +import { PrismaClient } from '../generated/prisma/client' + +const connectionString = `${process.env.DATABASE_URL}` + +const adapter = new PrismaPg({ connectionString }) +const prisma = new PrismaClient({ adapter }) + +export { prisma } +``` + +## 8. Write your first query + +Create a `script.ts` file to test your setup: + +```typescript file=script.ts +import { prisma } from './lib/prisma' + +async function main() { + // Create a new user with a post + const user = await prisma.user.create({ + data: { + name: 'Alice', + email: 'alice@prisma.io', + posts: { + create: { + title: 'Hello World', + content: 'This is my first post!', + published: true, + }, + }, + }, + include: { + posts: true, + }, + }) + console.log('Created user:', user) + + // Fetch all users with their posts + const allUsers = await prisma.user.findMany({ + include: { + posts: true, + }, + }) + console.log('All users:', JSON.stringify(allUsers, null, 2)) +} + +main() + .then(async () => { + await prisma.$disconnect() + }) + .catch(async (e) => { + console.error(e) + await prisma.$disconnect() + process.exit(1) + }) +``` + +Run the script: + +```terminal +npx tsx script.ts +``` + +You should see the created user and all users printed to the console! + +## 9. Explore your data with Prisma Studio + + + +## Next steps + + + +## More info + +- [Prisma Postgres documentation](/postgres) +- [Prisma Config reference](/orm/reference/prisma-config-reference) +- [Database connection management](/orm/prisma-client/setup-and-configuration/databases-connections) diff --git a/content/100-getting-started/02-prisma-orm/100-quickstart/200-sqlite.mdx b/content/100-getting-started/02-prisma-orm/100-quickstart/200-sqlite.mdx new file mode 100644 index 0000000000..b4dcb6abf4 --- /dev/null +++ b/content/100-getting-started/02-prisma-orm/100-quickstart/200-sqlite.mdx @@ -0,0 +1,278 @@ +--- +title: 'Quickstart with Prisma ORM and SQLite' +sidebar_label: 'SQLite' +metaTitle: 'Quickstart: Prisma ORM with SQLite (5 min)' +metaDescription: 'Create a new TypeScript project from scratch by connecting Prisma ORM to SQLite and generating a Prisma Client for database access.' +sidebar_custom_props: { badge: '5 min' } +--- + +import Prerequisites from '../../_components/_prerequisites.mdx' +import CreateProject from '../../_components/_create-project.mdx' +import ExploreData from '../../_components/_explore-data.mdx' +import NextSteps from '../../_components/_next-steps.mdx' + +[SQLite](https://sqlite.org) is a lightweight, file-based database that's perfect for development, prototyping, and small applications. It requires no setup and stores data in a local file. + +In this guide, you will learn how to set up a new TypeScript project from scratch, connect it to SQLite using Prisma ORM, and generate a Prisma Client for easy, type-safe access to your database. + +## Prerequisites + + + +## 1. Create a new project + + + +## 2. Install required dependencies + +Install the packages needed for this quickstart: + +```terminal +npm install prisma @types/node --save-dev +npm install @prisma/client @prisma/adapter-better-sqlite3 dotenv +``` + +Here's what each package does: + +- **`prisma`** - The Prisma CLI for running commands like `prisma init`, `prisma migrate`, and `prisma generate` +- **`@prisma/client`** - The Prisma Client library for querying your database +- **`@prisma/adapter-better-sqlite3`** - The SQLite driver adapter that connects Prisma Client to your database +- **`dotenv`** - Loads environment variables from your `.env` file + +## 3. Configure ESM support + +Update `tsconfig.json` for ESM compatibility: + +```json file=tsconfig.json +{ + "compilerOptions": { + "module": "ESNext", + "moduleResolution": "node", + "target": "ES2023", + "strict": true, + "esModuleInterop": true, + "ignoreDeprecations": "6.0" + } +} +``` + +Update `package.json` to enable ESM: + +```json file=package.json +{ + // add-start + "type": "module", + // add-end +} +``` + +## 4. Initialize Prisma ORM + +You can now invoke the Prisma CLI by prefixing it with `npx`: + +```terminal +npx prisma +``` + +Next, set up your Prisma ORM project by creating your [Prisma Schema](/orm/prisma-schema) file with the following command: + +```terminal +npx prisma init --datasource-provider sqlite --output ../generated/prisma +``` + +This command does a few things: + +- Creates a `prisma/` directory with a `schema.prisma` file containing your database connection and schema models +- Creates a `.env` file in the root directory for environment variables +- Generates the Prisma Client in the `generated/prisma/` directory +- Creates a `prisma.config.ts` file for Prisma configuration + +The generated `prisma.config.ts` file looks like this: + +```typescript file=prisma.config.ts +import { defineConfig, env } from 'prisma/config' + +export default defineConfig({ + schema: 'prisma/schema.prisma', + migrations: { + path: 'prisma/migrations', + }, + datasource: { + url: env('DATABASE_URL'), + }, +}) +``` + +Add `dotenv` to `prisma.config.ts` so that Prisma can load environment variables from your `.env` file: + +```typescript file=prisma.config.ts +// add-start +import 'dotenv/config' +// add-end +import { defineConfig, env } from 'prisma/config' + +export default defineConfig({ + schema: 'prisma/schema.prisma', + migrations: { + path: 'prisma/migrations', + }, + datasource: { + url: env('DATABASE_URL'), + }, +}) +``` + +The generated schema uses [the ESM-first `prisma-client` generator](/orm/prisma-schema/overview/generators#prisma-client) with a custom output path: + +```prisma file=prisma/schema.prisma +generator client { + provider = "prisma-client" + output = "../generated/prisma" +} + +datasource db { + provider = "sqlite" +} +``` + +A `.env` file should be created with the following value: + +```env file=.env +DATABASE_URL="file:./dev.db" +``` + +## 5. Define your data model + +Open `prisma/schema.prisma` and add the following models: + +```prisma file=prisma/schema.prisma +generator client { + provider = "prisma-client" + output = "../generated/prisma" +} + +datasource db { + provider = "sqlite" + url = env("DATABASE_URL") +} + +//add-start +model User { + id Int @id @default(autoincrement()) + email String @unique + name String? + posts Post[] +} + +model Post { + id Int @id @default(autoincrement()) + title String + content String? + published Boolean @default(false) + author User @relation(fields: [authorId], references: [id]) + authorId Int +} +//add-end +``` + +## 6. Create and apply your first migration + +Create your first migration to set up the database tables: + +```terminal +npx prisma migrate dev --name init +``` + +This command creates the database tables based on your schema. + +Now run the following command to generate the Prisma Client: + +```terminal +npx prisma generate +``` + +## 7. Instantiate Prisma Client + +Now that you have all the dependencies installed, you can instantiate Prisma Client. You need to pass an instance of Prisma ORM's driver adapter to the `PrismaClient` constructor: + +```typescript file=lib/prisma.ts +import "dotenv/config"; +import { PrismaBetterSqlite3 } from "@prisma/adapter-better-sqlite3"; +import { PrismaClient } from "../generated/prisma/client"; + +const connectionString = `${process.env.DATABASE_URL}`; + +const adapter = new PrismaBetterSqlite3({ url: connectionString }); +const prisma = new PrismaClient({ adapter }); + +export { prisma }; +``` + +## 8. Write your first query + +Create a `script.ts` file to test your setup: + +```typescript file=script.ts +import { prisma } from './lib/prisma' + +async function main() { + // Create a new user with a post + const user = await prisma.user.create({ + data: { + name: 'Alice', + email: 'alice@prisma.io', + posts: { + create: { + title: 'Hello World', + content: 'This is my first post!', + published: true, + }, + }, + }, + include: { + posts: true, + }, + }) + console.log('Created user:', user) + + // Fetch all users with their posts + const allUsers = await prisma.user.findMany({ + include: { + posts: true, + }, + }) + console.log('All users:', JSON.stringify(allUsers, null, 2)) +} + +main() + .then(async () => { + await prisma.$disconnect() + }) + .catch(async (e) => { + console.error(e) + await prisma.$disconnect() + process.exit(1) + }) +``` + +Run the script: + +```terminal +npx tsx script.ts +``` + +You should see the created user and all users printed to the console! + +## 9. Explore your data with Prisma Studio + + + +## Next steps + + + +## More info + +- [SQLite database connector](/orm/overview/databases/sqlite) +- [Prisma Config reference](/orm/reference/prisma-config-reference) +- [Database connection management](/orm/prisma-client/setup-and-configuration/databases-connections) diff --git a/content/100-getting-started/02-prisma-orm/100-quickstart/300-postgresql.mdx b/content/100-getting-started/02-prisma-orm/100-quickstart/300-postgresql.mdx new file mode 100644 index 0000000000..53f3352521 --- /dev/null +++ b/content/100-getting-started/02-prisma-orm/100-quickstart/300-postgresql.mdx @@ -0,0 +1,292 @@ +--- +title: 'Quickstart with Prisma ORM and PostgreSQL' +sidebar_label: 'PostgreSQL' +metaTitle: 'Quickstart: Prisma ORM with PostgreSQL (10 min)' +metaDescription: 'Create a new TypeScript project from scratch by connecting Prisma ORM to PostgreSQL and generating a Prisma Client for database access.' +sidebar_custom_props: { badge: '10 min' } +--- + +import Prerequisites from '../../_components/_prerequisites.mdx' +import CreateProject from '../../_components/_create-project.mdx' +import ExploreData from '../../_components/_explore-data.mdx' +import NextSteps from '../../_components/_next-steps.mdx' + +[PostgreSQL](https://www.postgresql.org) is a powerful, open-source relational database. In this guide, you will learn how to set up a new TypeScript project from scratch, connect it to PostgreSQL using Prisma ORM, and generate a Prisma Client for easy, type-safe access to your database. + +## Prerequisites + + + +You also need: + +- A [PostgreSQL](https://www.postgresql.org/) database server running and accessible +- Database connection details (host, port, username, password, database name) + +:::tip Need a PostgreSQL database? + +If you don't already have a PostgreSQL database, follow the quickstart to set up a production-ready [Prisma Postgres](/getting-started/prisma-orm/quickstart/prisma-postgres) database with Prisma ORM in a new project. + +::: + +## 1. Create a new project + + + +## 2. Install required dependencies + +Install the packages needed for this quickstart: + +```terminal +npm install prisma @types/node --save-dev +npm install @prisma/client @prisma/adapter-pg dotenv +``` + +Here's what each package does: + +- **`prisma`** - The Prisma CLI for running commands like `prisma init`, `prisma migrate`, and `prisma generate` +- **`@prisma/client`** - The Prisma Client library for querying your database +- **`@prisma/adapter-pg`** - The [`node-postgres` driver adapter](/orm/overview/databases/postgresql#using-the-node-postgres-driver) that connects Prisma Client to your database +- **`dotenv`** - Loads environment variables from your `.env` file + +## 3. Configure ESM support + +Update `tsconfig.json` for ESM compatibility: + +```json file=tsconfig.json +{ + "compilerOptions": { + "module": "ESNext", + "moduleResolution": "node", + "target": "ES2023", + "strict": true, + "esModuleInterop": true, + "ignoreDeprecations": "6.0" + } +} +``` + +Update `package.json` to enable ESM: + +```json file=package.json +{ + // add-start + "type": "module", + // add-end +} +``` + +## 4. Initialize Prisma ORM + +You can now invoke the Prisma CLI by prefixing it with `npx`: + +```terminal +npx prisma +``` + +Next, set up your Prisma ORM project by creating your [Prisma Schema](/orm/prisma-schema) file with the following command: + +```terminal +npx prisma init --datasource-provider postgresql --output ../generated/prisma +``` + +This command does a few things: + +- Creates a `prisma/` directory with a `schema.prisma` file containing your database connection and schema models +- Creates a `.env` file in the root directory for environment variables +- Generates the Prisma Client in the `generated/prisma/` directory +- Creates a `prisma.config.ts` file for Prisma configuration + +The generated `prisma.config.ts` file looks like this: + +```typescript file=prisma.config.ts +import { defineConfig, env } from 'prisma/config' + +export default defineConfig({ + schema: 'prisma/schema.prisma', + migrations: { + path: 'prisma/migrations', + }, + datasource: { + url: env('DATABASE_URL'), + }, +}) +``` + +Add `dotenv` to `prisma.config.ts` so that Prisma can load environment variables from your `.env` file: + +```typescript file=prisma.config.ts +// add-start +import 'dotenv/config' +// add-end +import { defineConfig, env } from 'prisma/config' + +export default defineConfig({ + schema: 'prisma/schema.prisma', + migrations: { + path: 'prisma/migrations', + }, + datasource: { + url: env('DATABASE_URL'), + }, +}) +``` + +The generated schema uses [the ESM-first `prisma-client` generator](/orm/prisma-schema/overview/generators#prisma-client) with a custom output path: + +```prisma file=prisma/schema.prisma +generator client { + provider = "prisma-client" + output = "../generated/prisma" +} + +datasource db { + provider = "postgresql" +} +``` + +Update your `.env` file with your PostgreSQL connection string: + +```env file=.env +DATABASE_URL="postgresql://username:password@localhost:5432/mydb?schema=public" +``` + +Replace the placeholders with your actual database credentials: +- `username`: Your PostgreSQL username +- `password`: Your PostgreSQL password +- `localhost:5432`: Your PostgreSQL host and port +- `mydb`: Your database name + +## 5. Define your data model + +Open `prisma/schema.prisma` and add the following models: + +```prisma file=prisma/schema.prisma +generator client { + provider = "prisma-client" + output = "../generated/prisma" +} + +datasource db { + provider = "postgresql" +} + +//add-start +model User { + id Int @id @default(autoincrement()) + email String @unique + name String? + posts Post[] +} + +model Post { + id Int @id @default(autoincrement()) + title String + content String? + published Boolean @default(false) + author User @relation(fields: [authorId], references: [id]) + authorId Int +} +//add-end +``` + +## 6. Create and apply your first migration + +Create your first migration to set up the database tables: + +```terminal +npx prisma migrate dev --name init +``` + +This command creates the database tables based on your schema. + +Now run the following command to generate the Prisma Client: + +```terminal +npx prisma generate +``` + +## 7. Instantiate Prisma Client + +Now that you have all the dependencies installed, you can instantiate Prisma Client. You need to pass an instance of Prisma ORM's driver adapter to the `PrismaClient` constructor: + +```typescript file=lib/prisma.ts +import "dotenv/config"; +import { PrismaPg } from '@prisma/adapter-pg' +import { PrismaClient } from '../generated/prisma/client' + +const connectionString = `${process.env.DATABASE_URL}` + +const adapter = new PrismaPg({ connectionString }) +const prisma = new PrismaClient({ adapter }) + +export { prisma } +``` + +## 8. Write your first query + +Create a `script.ts` file to test your setup: + +```typescript file=script.ts +import { prisma } from './lib/prisma' + +async function main() { + // Create a new user with a post + const user = await prisma.user.create({ + data: { + name: 'Alice', + email: 'alice@prisma.io', + posts: { + create: { + title: 'Hello World', + content: 'This is my first post!', + published: true, + }, + }, + }, + include: { + posts: true, + }, + }) + console.log('Created user:', user) + + // Fetch all users with their posts + const allUsers = await prisma.user.findMany({ + include: { + posts: true, + }, + }) + console.log('All users:', JSON.stringify(allUsers, null, 2)) +} + +main() + .then(async () => { + await prisma.$disconnect() + }) + .catch(async (e) => { + console.error(e) + await prisma.$disconnect() + process.exit(1) + }) +``` + +Run the script: + +```terminal +npx tsx script.ts +``` + +You should see the created user and all users printed to the console! + +## 9. Explore your data with Prisma Studio + + + +## Next steps + + + +## More info + +- [PostgreSQL database connector](/orm/overview/databases/postgresql) +- [Prisma Config reference](/orm/reference/prisma-config-reference) +- [Database connection management](/orm/prisma-client/setup-and-configuration/databases-connections) diff --git a/content/100-getting-started/02-prisma-orm/100-quickstart/400-mysql.mdx b/content/100-getting-started/02-prisma-orm/100-quickstart/400-mysql.mdx new file mode 100644 index 0000000000..8edc3e72df --- /dev/null +++ b/content/100-getting-started/02-prisma-orm/100-quickstart/400-mysql.mdx @@ -0,0 +1,300 @@ +--- +title: 'Quickstart with Prisma ORM and MySQL' +sidebar_label: 'MySQL' +metaTitle: 'Quickstart: Prisma ORM with MySQL (10 min)' +metaDescription: 'Create a new TypeScript project from scratch by connecting Prisma ORM to MySQL and generating a Prisma Client for database access.' +sidebar_custom_props: { badge: '10 min' } +--- + +import Prerequisites from '../../_components/_prerequisites.mdx' +import CreateProject from '../../_components/_create-project.mdx' +import ExploreData from '../../_components/_explore-data.mdx' +import NextSteps from '../../_components/_next-steps.mdx' + +[MySQL](https://www.mysql.com) is a popular open-source relational database. In this guide, you will learn how to set up a new TypeScript project from scratch, connect it to MySQL using Prisma ORM, and generate a Prisma Client for easy, type-safe access to your database. + +:::note + +This guide also applies to **MariaDB**, which is MySQL-compatible. + +::: + +## Prerequisites + + + +You also need: + +- A [MySQL](https://www.mysql.com/) database server running and accessible +- Database connection details (host, port, username, password, database name) + + + +## 2. Install required dependencies + +Install the packages needed for this quickstart: + +```terminal +npm install prisma @types/node --save-dev +npm install @prisma/client @prisma/adapter-mariadb dotenv +``` + +Here's what each package does: + +- **`prisma`** - The Prisma CLI for running commands like `prisma init`, `prisma migrate`, and `prisma generate` +- **`@prisma/client`** - The Prisma Client library for querying your database +- **`@prisma/adapter-mariadb`** - The MySQL/MariaDB driver adapter that connects Prisma Client to your database +- **`dotenv`** - Loads environment variables from your `.env` file + +## 3. Configure ESM support + +Update `tsconfig.json` for ESM compatibility: + +```json file=tsconfig.json +{ + "compilerOptions": { + "module": "ESNext", + "moduleResolution": "node", + "target": "ES2023", + "strict": true, + "esModuleInterop": true, + "ignoreDeprecations": "6.0" + } +} +``` + +Update `package.json` to enable ESM: + +```json file=package.json +{ + // add-start + "type": "module", + // add-end +} +``` + +## 4. Initialize Prisma ORM + +You can now invoke the Prisma CLI by prefixing it with `npx`: + +```terminal +npx prisma +``` + +Next, set up your Prisma ORM project by creating your [Prisma Schema](/orm/prisma-schema) file with the following command: + +```terminal +npx prisma init --datasource-provider mysql --output ../generated/prisma +``` + +This command does a few things: + +- Creates a `prisma/` directory with a `schema.prisma` file containing your database connection and schema models +- Creates a `.env` file in the root directory for environment variables +- Generates the Prisma Client in the `generated/prisma/` directory +- Creates a `prisma.config.ts` file for Prisma configuration + +The generated `prisma.config.ts` file looks like this: + +```typescript file=prisma.config.ts +import { defineConfig, env } from 'prisma/config' + +export default defineConfig({ + schema: 'prisma/schema.prisma', + migrations: { + path: 'prisma/migrations', + }, + datasource: { + url: env('DATABASE_URL'), + }, +}) +``` + +Add `dotenv` to `prisma.config.ts` so that Prisma can load environment variables from your `.env` file: + +```typescript file=prisma.config.ts +// add-start +import 'dotenv/config' +// add-end +import { defineConfig, env } from 'prisma/config' + +export default defineConfig({ + schema: 'prisma/schema.prisma', + migrations: { + path: 'prisma/migrations', + }, + datasource: { + url: env('DATABASE_URL'), + }, +}) +``` + +The generated schema uses [the ESM-first `prisma-client` generator](/orm/prisma-schema/overview/generators#prisma-client) with a custom output path: + +```prisma file=prisma/schema.prisma +generator client { + provider = "prisma-client" + output = "../generated/prisma" +} + +datasource db { + provider = "mysql" +} +``` + +Update your `.env` file with your MySQL connection string details: + +```env file=.env +DATABASE_URL="mysql://username:password@localhost:3306/mydb" +//add-start +DATABASE_USER="username" +DATABASE_PASSWORD="password" +DATABASE_NAME="mydb" +DATABASE_HOST="localhost" +DATABASE_PORT=3306 +//add-end +``` + +Replace the placeholders with your actual database credentials: +- `username`: Your MySQL username +- `password`: Your MySQL password +- `localhost:3306`: Your MySQL host and port +- `mydb`: Your database name + +## 5. Define your data model + +Open `prisma/schema.prisma` and add the following models: + +```prisma file=prisma/schema.prisma +generator client { + provider = "prisma-client" + output = "../generated/prisma" +} + +datasource db { + provider = "mysql" +} + +//add-start +model User { + id Int @id @default(autoincrement()) + email String @unique + name String? + posts Post[] +} + +model Post { + id Int @id @default(autoincrement()) + title String + content String? @db.Text + published Boolean @default(false) + author User @relation(fields: [authorId], references: [id]) + authorId Int +} +//add-end +``` + +## 6. Create and apply your first migration + +Create your first migration to set up the database tables: + +```terminal +npx prisma migrate dev --name init +``` + +This command creates the database tables based on your schema. + +Now run the following command to generate the Prisma Client: + +```terminal +npx prisma generate +``` + +## 7. Instantiate Prisma Client + +Now that you have all the dependencies installed, you can instantiate Prisma Client. You need to pass an instance of Prisma ORM's driver adapter to the `PrismaClient` constructor: + +```typescript file=lib/prisma.ts +import "dotenv/config"; +import { PrismaMariaDb } from '@prisma/adapter-mariadb'; +import { PrismaClient } from '../generated/prisma/client'; + +const adapter = new PrismaMariaDb({ + host: process.env.DATABASE_HOST, + user: process.env.DATABASE_USER, + password: process.env.DATABASE_PASSWORD, + database: process.env.DATABASE_NAME, + connectionLimit: 5 +}); +const prisma = new PrismaClient({ adapter }); + +export { prisma } +``` + +## 8. Write your first query + +Create a `script.ts` file to test your setup: + +```typescript file=script.ts +import { prisma } from './lib/prisma' + +async function main() { + const user = await prisma.user.create({ + data: { + name: 'Alice', + email: 'alice@prisma.io', + posts: { + create: { + title: 'Hello World', + content: 'This is my first post!', + published: true, + }, + }, + }, + include: { + posts: true, + }, + }) + console.log('Created user:', user) + + // Fetch all users with their posts + const allUsers = await prisma.user.findMany({ + include: { + posts: true, + }, + }) + console.log('All users:', JSON.stringify(allUsers, null, 2)) +} + +main() + .then(async () => { + await prisma.$disconnect() + }) + .catch(async (e) => { + console.error(e) + await prisma.$disconnect() + process.exit(1) + }) +``` + +Run the script: + +```terminal +npx tsx script.ts +``` + +You should see the created user and all users printed to the console! + +## 9. Explore your data with Prisma Studio + + + +## Next steps + + + +## More info + +- [MySQL database connector](/orm/overview/databases/mysql) +- [Prisma Config reference](/orm/reference/prisma-config-reference) +- [Database connection management](/orm/prisma-client/setup-and-configuration/databases-connections) diff --git a/content/100-getting-started/02-prisma-orm/100-quickstart/500-sql-server.mdx b/content/100-getting-started/02-prisma-orm/100-quickstart/500-sql-server.mdx new file mode 100644 index 0000000000..f78be99bca --- /dev/null +++ b/content/100-getting-started/02-prisma-orm/100-quickstart/500-sql-server.mdx @@ -0,0 +1,309 @@ +--- +title: 'Quickstart with Prisma ORM and SQL Server' +sidebar_label: 'SQL Server' +metaTitle: 'Quickstart: Prisma ORM with SQL Server (10 min)' +metaDescription: 'Create a new TypeScript project from scratch by connecting Prisma ORM to SQL Server and generating a Prisma Client for database access.' +sidebar_custom_props: { badge: '10 min' } +--- + +import Prerequisites from '../../_components/_prerequisites.mdx' +import CreateProject from '../../_components/_create-project.mdx' +import ExploreData from '../../_components/_explore-data.mdx' +import NextSteps from '../../_components/_next-steps.mdx' + +[Microsoft SQL Server](https://www.microsoft.com/en-us/sql-server) is an enterprise-grade relational database. In this guide, you will learn how to set up a new TypeScript project from scratch, connect it to SQL Server using Prisma ORM, and generate a Prisma Client for easy, type-safe access to your database. + +## Prerequisites + + + +You also need: + +- A [Microsoft SQL Server](https://learn.microsoft.com/en-us/sql/?view=sql-server-ver16) database + - [Microsoft SQL Server on Linux for Docker](/orm/overview/databases/sql-server/sql-server-docker) + - [Microsoft SQL Server on Windows (local)](/orm/overview/databases/sql-server/sql-server-local) +- Database connection details (host, port, username, password, database name) + +## 1. Create a new project + + + +## 2. Install required dependencies + +Install the packages needed for this quickstart: + +```terminal +npm install prisma @types/node --save-dev +npm install @prisma/client @prisma/adapter-mssql dotenv +``` + +Here's what each package does: + +- **`prisma`** - The Prisma CLI for running commands like `prisma init`, `prisma migrate`, and `prisma generate` +- **`@prisma/client`** - The Prisma Client library for querying your database +- **`@prisma/adapter-mssql`** - The SQL Server driver adapter that connects Prisma Client to your database +- **`dotenv`** - Loads environment variables from your `.env` file + +## 3. Configure ESM support + +Update `tsconfig.json` for ESM compatibility: + +```json file=tsconfig.json +{ + "compilerOptions": { + "module": "ESNext", + "moduleResolution": "node", + "target": "ES2023", + "strict": true, + "esModuleInterop": true, + "ignoreDeprecations": "6.0" + } +} +``` + +Update `package.json` to enable ESM: + +```json file=package.json +{ + // add-start + "type": "module", + // add-end +} +``` + +## 4. Initialize Prisma ORM + +You can now invoke the Prisma CLI by prefixing it with `npx`: + +```terminal +npx prisma +``` + +Next, set up your Prisma ORM project by creating your [Prisma Schema](/orm/prisma-schema) file with the following command: + +```terminal +npx prisma init --datasource-provider sqlserver --output ../generated/prisma +``` + +This command does a few things: + +- Creates a `prisma/` directory with a `schema.prisma` file containing your database connection and schema models +- Creates a `.env` file in the root directory for environment variables +- Generates the Prisma Client in the `generated/prisma/` directory +- Creates a `prisma.config.ts` file for Prisma configuration + +The generated `prisma.config.ts` file looks like this: + +```typescript file=prisma.config.ts +import { defineConfig, env } from 'prisma/config' + +export default defineConfig({ + schema: 'prisma/schema.prisma', + migrations: { + path: 'prisma/migrations', + }, + datasource: { + url: env('DATABASE_URL'), + }, +}) +``` + +Add `dotenv` to `prisma.config.ts` so that Prisma can load environment variables from your `.env` file: + +```typescript file=prisma.config.ts +// add-start +import 'dotenv/config' +// add-end +import { defineConfig, env } from 'prisma/config' + +export default defineConfig({ + schema: 'prisma/schema.prisma', + migrations: { + path: 'prisma/migrations', + }, + datasource: { + url: env('DATABASE_URL'), + }, +}) +``` + +The generated schema uses [the ESM-first `prisma-client` generator](/orm/prisma-schema/overview/generators#prisma-client) with a custom output path: + +```prisma file=prisma/schema.prisma +generator client { + provider = "prisma-client" + output = "../generated/prisma" +} + +datasource db { + provider = "sqlserver" +} +``` + +Update your `.env` file with your SQL Server connection string details: + +```env file=.env +DATABASE_URL="sqlserver://localhost:1433;database=mydb;user=username;password=password;encrypt=true" +//add-start +DB_USER="username" +DB_PASSWORD="password" +DB_NAME="mydb" +HOST="localhost" +//add-end +``` + +Replace the placeholders with your actual database credentials: + +- `localhost:1433`: Your SQL Server host and port +- `mydb`: Your database name +- `username`: Your SQL Server username +- `password`: Your SQL Server password + +## 5. Define your data model + +Open `prisma/schema.prisma` and add the following models: + +```prisma file=prisma/schema.prisma +generator client { + provider = "prisma-client" + output = "../generated/prisma" +} + +datasource db { + provider = "sqlserver" +} + +//add-start +model User { + id Int @id @default(autoincrement()) + email String @unique + name String? + posts Post[] +} + +model Post { + id Int @id @default(autoincrement()) + title String + content String? + published Boolean @default(false) + author User @relation(fields: [authorId], references: [id]) + authorId Int +} +//add-end +``` + +## 6. Create and apply your first migration + +Create your first migration to set up the database tables: + +```terminal +npx prisma migrate dev --name init +``` + +This command creates the database tables based on your schema. + +Now run the following command to generate the Prisma Client: + +```terminal +npx prisma generate +``` + +## 7. Instantiate Prisma Client + +Now that you have all the dependencies installed, you can instantiate Prisma Client. You need to pass an instance of Prisma ORM's driver adapter to the `PrismaClient` constructor: + +```typescript file=lib/prisma.ts +import "dotenv/config"; +import { PrismaMSSQL } from '@prisma/adapter-mssql'; +import { PrismaClient } from '../generated/prisma/client'; + +const sqlConfig = { + user: process.env.DB_USER, + password: process.env.DB_PASSWORD, + database: process.env.DB_NAME, + server: process.env.HOST, + pool: { + max: 10, + min: 0, + idleTimeoutMillis: 30000 + }, + options: { + encrypt: true, // for azure + trustServerCertificate: false // change to true for local dev / self-signed certs + } +} + +const adapter = new PrismaMSSQL(sqlConfig) +const prisma = new PrismaClient({ adapter }); + +export { prisma } +``` + +## 8. Write your first query + +Create a `script.ts` file to test your setup: + +```typescript file=script.ts +import { prisma } from './lib/prisma' + +async function main() { + // Create a new user with a post + const user = await prisma.user.create({ + data: { + name: 'Alice', + email: 'alice@prisma.io', + posts: { + create: { + title: 'Hello World', + content: 'This is my first post!', + published: true, + }, + }, + }, + include: { + posts: true, + }, + }) + console.log('Created user:', user) + + // Fetch all users with their posts + const allUsers = await prisma.user.findMany({ + include: { + posts: true, + }, + }) + console.log('All users:', JSON.stringify(allUsers, null, 2)) +} + +main() + .then(async () => { + await prisma.$disconnect() + }) + .catch(async (e) => { + console.error(e) + await prisma.$disconnect() + process.exit(1) + }) +``` + +Run the script: + +```terminal +npx tsx script.ts +``` + +You should see the created user and all users printed to the console! + +## 9. Explore your data with Prisma Studio + + + +## Next steps + + + +## More info + +- [SQL Server database connector](/orm/overview/databases/sql-server) +- [Prisma Config reference](/orm/reference/prisma-config-reference) +- [Database connection management](/orm/prisma-client/setup-and-configuration/databases-connections) diff --git a/content/100-getting-started/02-prisma-orm/100-quickstart/600-planetscale.mdx b/content/100-getting-started/02-prisma-orm/100-quickstart/600-planetscale.mdx new file mode 100644 index 0000000000..d6c4752fb5 --- /dev/null +++ b/content/100-getting-started/02-prisma-orm/100-quickstart/600-planetscale.mdx @@ -0,0 +1,311 @@ +--- +title: 'Quickstart with Prisma ORM and PlanetScale' +sidebar_label: 'PlanetScale' +metaTitle: 'Quickstart: Prisma ORM with PlanetScale MySQL (10 min)' +metaDescription: 'Create a new TypeScript project from scratch by connecting Prisma ORM to PlanetScale MySQL and generating a Prisma Client for database access.' +sidebar_custom_props: { badge: '10 min' } +--- + +import Prerequisites from '../../_components/_prerequisites.mdx' +import CreateProject from '../../_components/_create-project.mdx' +import ExploreData from '../../_components/_explore-data.mdx' +import NextSteps from '../../_components/_next-steps.mdx' + +[PlanetScale](https://planetscale.com) is a serverless database platform. This guide covers **PlanetScale MySQL**. In this guide, you will learn how to set up a new TypeScript project from scratch, connect it to PlanetScale MySQL using Prisma ORM, and generate a Prisma Client for easy, type-safe access to your database. + +:::note + +PlanetScale also offers PostgreSQL databases. If you're using **PlanetScale PostgreSQL**, follow the [PostgreSQL quickstart guide](/getting-started/prisma-orm/quickstart/postgresql) instead. + +::: + +## Prerequisites + + + +You also need: + +- A [PlanetScale](https://planetscale.com) database +- Database connection string from PlanetScale + +## 1. Create a new project + + + +## 2. Install required dependencies + +Install the packages needed for this quickstart: + +```terminal +npm install prisma @types/node --save-dev +npm install @prisma/client @prisma/adapter-planetscale undici dotenv +``` + +Here's what each package does: + +- **`prisma`** - The Prisma CLI for running commands like `prisma init`, `prisma migrate`, and `prisma generate` +- **`@prisma/client`** - The Prisma Client library for querying your database +- **`@prisma/adapter-planetscale`** - The PlanetScale driver adapter that connects Prisma Client to your database +- **`undici`** - A fast HTTP/1.1 client required by the PlanetScale adapter +- **`dotenv`** - Loads environment variables from your `.env` file + +## 3. Configure ESM support + +Update `tsconfig.json` for ESM compatibility: + +```json file=tsconfig.json +{ + "compilerOptions": { + "module": "ESNext", + "moduleResolution": "node", + "target": "ES2023", + "strict": true, + "esModuleInterop": true, + "ignoreDeprecations": "6.0" + } +} +``` + +Update `package.json` to enable ESM: + +```json file=package.json +{ + // add-start + "type": "module", + // add-end +} +``` + +## 4. Initialize Prisma ORM + +You can now invoke the Prisma CLI by prefixing it with `npx`: + +```terminal +npx prisma +``` + +Next, set up your Prisma ORM project by creating your [Prisma Schema](/orm/prisma-schema) file with the following command: + +```terminal +npx prisma init --datasource-provider mysql --output ../generated/prisma +``` + +This command does a few things: + +- Creates a `prisma/` directory with a `schema.prisma` file containing your database connection and schema models +- Creates a `.env` file in the root directory for environment variables +- Generates the Prisma Client in the `generated/prisma/` directory +- Creates a `prisma.config.ts` file for Prisma configuration + +The generated `prisma.config.ts` file looks like this: + +```typescript file=prisma.config.ts +import { defineConfig, env } from 'prisma/config' + +export default defineConfig({ + schema: 'prisma/schema.prisma', + migrations: { + path: 'prisma/migrations', + }, + datasource: { + url: env('DATABASE_URL'), + }, +}) +``` + +Add `dotenv` to `prisma.config.ts` so that Prisma can load environment variables from your `.env` file: + +```typescript file=prisma.config.ts +// add-start +import 'dotenv/config' +// add-end +import { defineConfig, env } from 'prisma/config' + +export default defineConfig({ + schema: 'prisma/schema.prisma', + migrations: { + path: 'prisma/migrations', + }, + datasource: { + url: env('DATABASE_URL'), + }, +}) +``` + +The generated schema uses [the ESM-first `prisma-client` generator](/orm/prisma-schema/overview/generators#prisma-client) with a custom output path: + +```prisma file=prisma/schema.prisma +generator client { + provider = "prisma-client" + output = "../generated/prisma" +} + +datasource db { + provider = "mysql" +} +``` + +Update your schema to include `relationMode = "prisma"` for PlanetScale: + +```prisma file=prisma/schema.prisma +generator client { + provider = "prisma-client" + output = "../generated/prisma" +} + +datasource db { + provider = "mysql" + relationMode = "prisma" +} +``` + +Update your `.env` file with your PlanetScale connection string: + +```env file=.env +DATABASE_URL="mysql://username:password@host.connect.psdb.cloud/mydb?sslaccept=strict" +``` + +Replace with your actual PlanetScale connection string from your database dashboard. + +## 5. Define your data model + +Open `prisma/schema.prisma` and add the following models: + +```prisma file=prisma/schema.prisma +generator client { + provider = "prisma-client" + output = "../generated/prisma" +} + +datasource db { + provider = "mysql" + relationMode = "prisma" +} + +//add-start +model User { + id Int @id @default(autoincrement()) + email String @unique + name String? + posts Post[] +} + +model Post { + id Int @id @default(autoincrement()) + title String + content String? @db.Text + published Boolean @default(false) + author User @relation(fields: [authorId], references: [id]) + authorId Int + + @@index([authorId]) +} +//add-end +``` + +:::note + +Note the `@@index([authorId])` on the `Post` model. PlanetScale requires indexes on foreign keys when using `relationMode = "prisma"`. + +::: + +## 6. Push your schema to PlanetScale + +PlanetScale uses a branching workflow instead of traditional migrations. Push your schema directly: + +```terminal +npx prisma db push +``` + +This command creates the database tables based on your schema. + +Now run the following command to generate the Prisma Client: + +```terminal +npx prisma generate +``` + +## 7. Instantiate Prisma Client + +Now that you have all the dependencies installed, you can instantiate Prisma Client. You need to pass an instance of Prisma ORM's driver adapter to the `PrismaClient` constructor: + +```typescript file=lib/prisma.ts +import "dotenv/config"; +import { PrismaPlanetScale } from '@prisma/adapter-planetscale' +import { PrismaClient } from '../generated/prisma/client' +import { fetch as undiciFetch } from 'undici' + +const adapter = new PrismaPlanetScale({ url: process.env.DATABASE_URL, fetch: undiciFetch }) +const prisma = new PrismaClient({ adapter }) + +export { prisma } +``` + +## 8. Write your first query + +Create a `script.ts` file to test your setup: + +```typescript file=script.ts +import { prisma } from './lib/prisma' + +async function main() { + // Create a new user with a post + const user = await prisma.user.create({ + data: { + name: 'Alice', + email: 'alice@prisma.io', + posts: { + create: { + title: 'Hello World', + content: 'This is my first post!', + published: true, + }, + }, + }, + include: { + posts: true, + }, + }) + console.log('Created user:', user) + + // Fetch all users with their posts + const allUsers = await prisma.user.findMany({ + include: { + posts: true, + }, + }) + console.log('All users:', JSON.stringify(allUsers, null, 2)) +} + +main() + .then(async () => { + await prisma.$disconnect() + }) + .catch(async (e) => { + console.error(e) + await prisma.$disconnect() + process.exit(1) + }) +``` + +Run the script: + +```terminal +npx tsx script.ts +``` + +You should see the created user and all users printed to the console! + +## 9. Explore your data with Prisma Studio + + + +## Next steps + + + +## More info + +- [PlanetScale database connector](/orm/overview/databases/planetscale) +- [Prisma Config reference](/orm/reference/prisma-config-reference) +- [Database connection management](/orm/prisma-client/setup-and-configuration/databases-connections) diff --git a/content/100-getting-started/02-prisma-orm/100-quickstart/700-cockroachdb.mdx b/content/100-getting-started/02-prisma-orm/100-quickstart/700-cockroachdb.mdx new file mode 100644 index 0000000000..8768122e43 --- /dev/null +++ b/content/100-getting-started/02-prisma-orm/100-quickstart/700-cockroachdb.mdx @@ -0,0 +1,282 @@ +--- +title: 'Quickstart with Prisma ORM and CockroachDB' +sidebar_label: 'CockroachDB' +metaTitle: 'Quickstart: Prisma ORM with CockroachDB (10 min)' +metaDescription: 'Create a new TypeScript project from scratch by connecting Prisma ORM to CockroachDB and generating a Prisma Client for database access.' +sidebar_custom_props: { badge: '10 min' } +--- + +import Prerequisites from '../../_components/_prerequisites.mdx' +import CreateProject from '../../_components/_create-project.mdx' +import ExploreData from '../../_components/_explore-data.mdx' +import NextSteps from '../../_components/_next-steps.mdx' + +[CockroachDB](https://www.cockroachlabs.com) is a distributed SQL database built for cloud applications. In this guide, you will learn how to set up a new TypeScript project from scratch, connect it to CockroachDB using Prisma ORM, and generate a Prisma Client for easy, type-safe access to your database. + +## Prerequisites + + + +You also need: + +- A [CockroachDB](https://www.cockroachlabs.com/) database +- Database connection string from CockroachDB + +## 1. Create a new project + + + +## 2. Install required dependencies + +Install the packages needed for this quickstart: + +```terminal +npm install prisma @types/node --save-dev +npm install @prisma/client @prisma/adapter-pg dotenv +``` + +Here's what each package does: + +- **`prisma`** - The Prisma CLI for running commands like `prisma init`, `prisma migrate`, and `prisma generate` +- **`@prisma/client`** - The Prisma Client library for querying your database +- **`@prisma/adapter-pg`** - The [`node-postgres` driver adapter](/orm/overview/databases/postgresql#using-the-node-postgres-driver) that connects Prisma Client to your database (CockroachDB is PostgreSQL-compatible) +- **`dotenv`** - Loads environment variables from your `.env` file + +## 3. Configure ESM support + +Update `tsconfig.json` for ESM compatibility: + +```json file=tsconfig.json +{ + "compilerOptions": { + "module": "ESNext", + "moduleResolution": "node", + "target": "ES2023", + "strict": true, + "esModuleInterop": true, + "ignoreDeprecations": "6.0" + } +} +``` + +Update `package.json` to enable ESM: + +```json file=package.json +{ + // add-start + "type": "module", + // add-end +} +``` + +## 4. Initialize Prisma ORM + +You can now invoke the Prisma CLI by prefixing it with `npx`: + +```terminal +npx prisma +``` + +Next, set up your Prisma ORM project by creating your [Prisma Schema](/orm/prisma-schema) file with the following command: + +```terminal +npx prisma init --datasource-provider cockroachdb --output ../generated/prisma +``` + +This command does a few things: + +- Creates a `prisma/` directory with a `schema.prisma` file containing your database connection and schema models +- Creates a `.env` file in the root directory for environment variables +- Generates the Prisma Client in the `generated/prisma/` directory +- Creates a `prisma.config.ts` file for Prisma configuration + +The generated `prisma.config.ts` file looks like this: + +```typescript file=prisma.config.ts +import { defineConfig, env } from 'prisma/config' + +export default defineConfig({ + schema: 'prisma/schema.prisma', + migrations: { + path: 'prisma/migrations', + }, + datasource: { + url: env('DATABASE_URL'), + }, +}) +``` + +Add `dotenv` to `prisma.config.ts` so that Prisma can load environment variables from your `.env` file: + +```typescript file=prisma.config.ts +// add-start +import 'dotenv/config' +// add-end +import { defineConfig, env } from 'prisma/config' + +export default defineConfig({ + schema: 'prisma/schema.prisma', + migrations: { + path: 'prisma/migrations', + }, + datasource: { + url: env('DATABASE_URL'), + }, +}) +``` + +The generated schema uses [the ESM-first `prisma-client` generator](/orm/prisma-schema/overview/generators#prisma-client) with a custom output path: + +```prisma file=prisma/schema.prisma +generator client { + provider = "prisma-client" + output = "../generated/prisma" +} + +datasource db { + provider = "cockroachdb" +} +``` + +Update your `.env` file with your CockroachDB connection string: + +```env file=.env +DATABASE_URL="postgresql://username:password@host:26257/mydb?sslmode=require" +``` + +Replace with your actual CockroachDB connection string from your cluster dashboard. + +## 5. Define your data model + +Open `prisma/schema.prisma` and add the following models: + +```prisma file=prisma/schema.prisma +generator client { + provider = "prisma-client" + output = "../generated/prisma" +} + +datasource db { + provider = "cockroachdb" +} + +//add-start +model User { + id Int @id @default(autoincrement()) + email String @unique + name String? + posts Post[] +} + +model Post { + id Int @id @default(autoincrement()) + title String + content String? + published Boolean @default(false) + author User @relation(fields: [authorId], references: [id]) + authorId Int +} +//add-end +``` + +## 6. Create and apply your first migration + +Create your first migration to set up the database tables: + +```terminal +npx prisma migrate dev --name init +``` + +This command creates the database tables based on your schema. + +Now run the following command to generate the Prisma Client: + +```terminal +npx prisma generate +``` + +## 7. Instantiate Prisma Client + +Now that you have all the dependencies installed, you can instantiate Prisma Client. You need to pass an instance of Prisma ORM's driver adapter to the `PrismaClient` constructor: + +```typescript file=lib/prisma.ts +import "dotenv/config"; +import { PrismaPg } from '@prisma/adapter-pg' +import { PrismaClient } from '../generated/prisma/client' + +const connectionString = `${process.env.DATABASE_URL}` + +const adapter = new PrismaPg({ connectionString }) +const prisma = new PrismaClient({ adapter }) + +export { prisma } +``` + +## 8. Write your first query + +Create a `script.ts` file to test your setup: + +```typescript file=script.ts +import { prisma } from './lib/prisma' + +async function main() { + // Create a new user with a post + const user = await prisma.user.create({ + data: { + name: 'Alice', + email: 'alice@prisma.io', + posts: { + create: { + title: 'Hello World', + content: 'This is my first post!', + published: true, + }, + }, + }, + include: { + posts: true, + }, + }) + console.log('Created user:', user) + + // Fetch all users with their posts + const allUsers = await prisma.user.findMany({ + include: { + posts: true, + }, + }) + console.log('All users:', JSON.stringify(allUsers, null, 2)) +} + +main() + .then(async () => { + await prisma.$disconnect() + }) + .catch(async (e) => { + console.error(e) + await prisma.$disconnect() + process.exit(1) + }) +``` + +Run the script: + +```terminal +npx tsx script.ts +``` + +You should see the created user and all users printed to the console! + +## 9. Explore your data with Prisma Studio + + + +## Next steps + + + +## More info + +- [CockroachDB database connector](/orm/overview/databases/cockroachdb) +- [Prisma Config reference](/orm/reference/prisma-config-reference) +- [Database connection management](/orm/prisma-client/setup-and-configuration/databases-connections) diff --git a/content/100-getting-started/02-prisma-orm/100-quickstart/800-mongodb.mdx b/content/100-getting-started/02-prisma-orm/100-quickstart/800-mongodb.mdx new file mode 100644 index 0000000000..a3594ba48e --- /dev/null +++ b/content/100-getting-started/02-prisma-orm/100-quickstart/800-mongodb.mdx @@ -0,0 +1,302 @@ +--- +title: 'Quickstart with Prisma ORM and MongoDB' +sidebar_label: 'MongoDB' +metaTitle: 'Quickstart: Prisma ORM with MongoDB (10 min)' +metaDescription: 'Create a new TypeScript project from scratch by connecting Prisma ORM to MongoDB and generating a Prisma Client for database access.' +sidebar_custom_props: { badge: '10 min' } +--- + +import Prerequisites from '../../_components/_prerequisites.mdx' +import CreateProject from '../../_components/_create-project.mdx' +import ExploreData from '../../_components/_explore-data.mdx' +import NextSteps from '../../_components/_next-steps.mdx' + +[MongoDB](https://www.mongodb.com) is a popular NoSQL document database. In this guide, you will learn how to set up a new TypeScript project from scratch, connect it to MongoDB using Prisma ORM, and generate a Prisma Client for easy, type-safe access to your database. + +:::warning[Do not upgrade to Prisma ORM v7 if you are using MongoDB] + +Prisma ORM v7 is not yet compatible with MongoDB. Please use Prisma ORM v6 instead. Support for MongoDB is coming in a future release. + +::: + +## Prerequisites + + + +You also need: + +- A [MongoDB](https://www.mongodb.com/) database accessible via connection string + +## 1. Create a new project + + + +## 2. Install required dependencies + +Install the packages needed for this quickstart: + +```terminal +npm install prisma @types/node --save-dev +npm install @prisma/client dotenv +``` + +Here's what each package does: + +- **`prisma`** - The Prisma CLI for running commands like `prisma init`, `prisma db push`, and `prisma generate` +- **`@prisma/client`** - The Prisma Client library for querying your database +- **`dotenv`** - Loads environment variables from your `.env` file + +:::note + +MongoDB doesn't require driver adapters since Prisma ORM connects directly to MongoDB. + +::: + +## 3. Configure ESM support + +Update `tsconfig.json` for ESM compatibility: + +```json file=tsconfig.json +{ + "compilerOptions": { + "module": "ESNext", + "moduleResolution": "node", + "target": "ES2023", + "strict": true, + "esModuleInterop": true, + "ignoreDeprecations": "6.0" + } +} +``` + +Update `package.json` to enable ESM: + +```json file=package.json +{ + // add-start + "type": "module", + // add-end +} +``` + +## 4. Initialize Prisma ORM + +You can now invoke the Prisma CLI by prefixing it with `npx`: + +```terminal +npx prisma +``` + +Next, set up your Prisma ORM project by creating your [Prisma Schema](/orm/prisma-schema) file with the following command: + +```terminal +npx prisma init --datasource-provider mongodb --output ../generated/prisma +``` + +This command does a few things: + +- Creates a `prisma/` directory with a `schema.prisma` file containing your database connection and schema models +- Creates a `.env` file in the root directory for environment variables +- Generates the Prisma Client in the `generated/prisma/` directory +- Creates a `prisma.config.ts` file for Prisma configuration + +The generated `prisma.config.ts` file looks like this: + +```typescript file=prisma.config.ts +import { defineConfig, env } from 'prisma/config' + +export default defineConfig({ + schema: 'prisma/schema.prisma', + migrations: { + path: 'prisma/migrations', + }, + engine: "classic", + datasource: { + url: env('DATABASE_URL'), + }, +}) +``` + +Add `dotenv` to `prisma.config.ts` so that Prisma can load environment variables from your `.env` file: + +```typescript file=prisma.config.ts +// add-start +import 'dotenv/config' +// add-end +import { defineConfig, env } from 'prisma/config' + +export default defineConfig({ + schema: 'prisma/schema.prisma', + migrations: { + path: 'prisma/migrations', + }, + engine: "classic", + datasource: { + url: env('DATABASE_URL'), + }, +}) +``` + +The generated schema uses [the ESM-first `prisma-client` generator](/orm/prisma-schema/overview/generators#prisma-client) with a custom output path: + +```prisma file=prisma/schema.prisma +generator client { + provider = "prisma-client" + output = "../generated/prisma" +} + +datasource db { + provider = "mongodb" + url = env("DATABASE_URL") +} +``` + +Update your `.env` file with your MongoDB connection string: + +```env file=.env +DATABASE_URL="mongodb+srv://username:password@cluster.mongodb.net/mydb" +``` + +Replace with your actual MongoDB connection string. + +## 5. Define your data model + +Open `prisma/schema.prisma` and add the following models: + +```prisma file=prisma/schema.prisma +generator client { + provider = "prisma-client" + output = "../generated/prisma" +} + +datasource db { + provider = "mongodb" + url = env("DATABASE_URL") +} + +//add-start +model User { + id String @id @default(auto()) @map("_id") @db.ObjectId + email String @unique + name String? + posts Post[] +} + +model Post { + id String @id @default(auto()) @map("_id") @db.ObjectId + title String + content String? + published Boolean @default(false) + author User @relation(fields: [authorId], references: [id]) + authorId String @db.ObjectId +} +//add-end +``` + +## 6. Push your schema to MongoDB + +Since MongoDB doesn't use migrations, push your schema directly: + +```terminal +npx prisma db push +``` + +This command creates the collections based on your schema. + +Now run the following command to generate the Prisma Client: + +```terminal +npx prisma generate +``` + +## 7. Instantiate Prisma Client + +Now that you have all the dependencies installed, you can instantiate Prisma Client: + +```typescript file=lib/prisma.ts +import "dotenv/config"; +import { PrismaClient } from '../generated/prisma/client' + +const prisma = new PrismaClient() + +export { prisma } +``` + +## 8. Write your first query + +Create a `script.ts` file to test your setup: + +```typescript file=script.ts +import { prisma } from './lib/prisma' + +async function main() { + // Create a new user with a post + const user = await prisma.user.create({ + data: { + name: 'Alice', + email: 'alice@prisma.io', + posts: { + create: { + title: 'Hello World', + content: 'This is my first post!', + published: true, + }, + }, + }, + include: { + posts: true, + }, + }) + console.log('Created user:', user) + + // Fetch all users with their posts + const allUsers = await prisma.user.findMany({ + include: { + posts: true, + }, + }) + console.log('All users:', JSON.stringify(allUsers, null, 2)) +} + +main() + .then(async () => { + await prisma.$disconnect() + }) + .catch(async (e) => { + console.error(e) + await prisma.$disconnect() + process.exit(1) + }) +``` + +Run the script: + +```terminal +npx tsx script.ts +``` + +You should see the created user and all users printed to the console! + +## 9. Explore your data with Prisma Studio + + + +## Next steps + + + +## Troubleshooting + +### `Error in connector: SCRAM failure: Authentication failed.` + +If you see the `Error in connector: SCRAM failure: Authentication failed.` error message, you can specify the source database for the authentication by [adding](https://github.com/prisma/prisma/discussions/9994#discussioncomment-1562283) `?authSource=admin` to the end of the connection string. + +### `Raw query failed. Error code 8000 (AtlasError): empty database name not allowed.` + +If you see the `Raw query failed. Code: unknown. Message: Kind: Command failed: Error code 8000 (AtlasError): empty database name not allowed.` error message, be sure to append the database name to the database URL. You can find more info in this [GitHub issue](https://github.com/prisma/docs/issues/5562). + +## More info + +- [MongoDB database connector](/orm/overview/databases/mongodb) +- [MongoDB data modeling patterns](/orm/overview/databases/mongodb#type-mapping-between-mongodb-and-the-prisma-schema) +- [MongoDB deployment considerations](/orm/overview/databases/mongodb#differences-to-connectors-for-relational-databases) diff --git a/content/100-getting-started/02-prisma-orm/200-add-to-existing-project/100-prisma-postgres.mdx b/content/100-getting-started/02-prisma-orm/200-add-to-existing-project/100-prisma-postgres.mdx new file mode 100644 index 0000000000..e6585e83b8 --- /dev/null +++ b/content/100-getting-started/02-prisma-orm/200-add-to-existing-project/100-prisma-postgres.mdx @@ -0,0 +1,257 @@ +--- +title: 'Add Prisma ORM to an existing Prisma Postgres project' +sidebar_title: 'Prisma Postgres' +metaTitle: 'How to add Prisma ORM to an existing project using Prisma Postgres (15 min)' +metaDescription: 'Add Prisma ORM to an existing TypeScript project with Prisma Postgres and learn database introspection, baselining, and querying.' +sidebar_custom_props: { badge: '15 min' } +--- + +import Prerequisites from '../../_components/_prerequisites.mdx' +import ExploreData from '../../_components/_explore-data.mdx' +import NextSteps from '../../_components/_next-steps.mdx' + +[Prisma Postgres](/postgres) is a fully managed PostgreSQL database that scales to zero and integrates smoothly with both Prisma ORM and Prisma Studio. In this guide, you will learn how to add Prisma ORM to an existing TypeScript project, connect it to Prisma Postgres, introspect your existing database schema, and start querying with type-safe Prisma Client. + +## Prerequisites + + + +## 1. Set up Prisma ORM + +Navigate to your existing project directory and install the required dependencies: + +```terminal +npm install prisma @types/node --save-dev +npm install @prisma/client @prisma/adapter-pg dotenv +``` + +Here's what each package does: + +- **`prisma`** - The Prisma CLI for running commands like `prisma init`, `prisma db pull`, and `prisma generate` +- **`@prisma/client`** - The Prisma Client library for querying your database +- **`@prisma/adapter-pg`** - The [`node-postgres` driver adapter](/orm/overview/databases/postgresql#using-the-node-postgres-driver) that connects Prisma Client to your database +- **`dotenv`** - Loads environment variables from your `.env` file + +## 2. Initialize Prisma ORM + +Set up your Prisma ORM project by creating your [Prisma Schema](/orm/prisma-schema) file with the following command: + +```terminal +npx prisma init --datasource-provider postgresql --output ../generated/prisma +``` + +This command does a few things: + +- Creates a `prisma/` directory with a `schema.prisma` file containing your database connection configuration +- Creates a `.env` file in the root directory for environment variables +- Creates a `prisma.config.ts` file for Prisma configuration + +The generated `prisma.config.ts` file looks like this: + +```typescript file=prisma.config.ts +import { defineConfig, env } from 'prisma/config' + +export default defineConfig({ + schema: 'prisma/schema.prisma', + migrations: { + path: 'prisma/migrations', + }, + datasource: { + url: env('DATABASE_URL'), + }, +}) +``` + +Add `dotenv` to `prisma.config.ts` so that Prisma can load environment variables from your `.env` file: + +```typescript file=prisma.config.ts +// add-start +import 'dotenv/config' +// add-end +import { defineConfig, env } from 'prisma/config' + +export default defineConfig({ + schema: 'prisma/schema.prisma', + migrations: { + path: 'prisma/migrations', + }, + datasource: { + url: env('DATABASE_URL'), + }, +}) +``` + +The generated schema uses [the ESM-first `prisma-client` generator](/orm/prisma-schema/overview/generators#prisma-client) with a custom output path: + +```prisma file=prisma/schema.prisma +generator client { + provider = "prisma-client" + output = "../generated/prisma" +} + +datasource db { + provider = "postgresql" +} +``` + +## 3. Connect your database + +Update the `.env` file with your Prisma Postgres connection URL: + +```bash file=.env +DATABASE_URL="postgresql://user:password@host:5432/database?schema=public" +``` + +Replace the placeholder values with your actual Prisma Postgres connection details. + +## 4. Introspect your database + +Run the following command to introspect your existing database: + +```terminal +npx prisma db pull +``` + +This command reads the `DATABASE_URL` environment variable, connects to your database, and introspects the database schema. It then translates the database schema from SQL into a data model in your Prisma schema. + +![Introspect your database with Prisma ORM](/img/getting-started/prisma-db-pull-generate-schema.png) + +After introspection, your Prisma schema will contain models that represent your existing database tables. + +## 5. Baseline your database + +To use Prisma Migrate with your existing database, you need to [baseline your database](/orm/prisma-migrate/getting-started). + +First, create a `migrations` directory: + +```terminal +mkdir -p prisma/migrations/0_init +``` + +Next, generate the migration file with `prisma migrate diff`: + +```terminal +npx prisma migrate diff --from-empty --to-schema prisma/schema.prisma --script > prisma/migrations/0_init/migration.sql +``` + +Review the generated migration file to ensure it matches your database schema. + +Then, mark the migration as applied: + +```terminal +npx prisma migrate resolve --applied 0_init +``` + +You now have a baseline for your current database schema. + +## 6. Generate Prisma ORM types + +Generate Prisma Client based on your introspected schema: + +```terminal +npx prisma generate +``` + +This creates a type-safe Prisma Client tailored to your database schema in the `generated/prisma` directory. + +## 7. Instantiate Prisma Client + +Create a utility file to instantiate Prisma Client. You need to pass an instance of Prisma ORM's driver adapter to the `PrismaClient` constructor: + +```typescript file=lib/prisma.ts +import "dotenv/config"; +import { PrismaPg } from '@prisma/adapter-pg' +import { PrismaClient } from '../generated/prisma/client' + +const connectionString = `${process.env.DATABASE_URL}` + +const adapter = new PrismaPg({ connectionString }) +const prisma = new PrismaClient({ adapter }) + +export { prisma } +``` + +## 8. Query your database + +Now you can use Prisma Client to query your database. Create a `script.ts` file: + +```typescript file=script.ts +import { prisma } from './lib/prisma' + +async function main() { + // Example: Fetch all records from a table + // Replace 'user' with your actual model name + const allUsers = await prisma.user.findMany() + console.log('All users:', JSON.stringify(allUsers, null, 2)) +} + +main() + .then(async () => { + await prisma.$disconnect() + }) + .catch(async (e) => { + console.error(e) + await prisma.$disconnect() + process.exit(1) + }) +``` + +Run the script: + +```terminal +npx tsx script.ts +``` + +## 9. Evolve your schema + +To make changes to your database schema: + +### 9.1. Update your Prisma schema file + +Update your Prisma schema file to reflect the changes you want to make to your database schema. For example, add a new model: + +```prisma file=prisma/schema.prisma +// add-start +model Post { + id Int @id @default(autoincrement()) + title String + content String? + published Boolean @default(false) + authorId Int + author User @relation(fields: [authorId], references: [id]) +} + +model User { + id Int @id @default(autoincrement()) + email String @unique + name String? + posts Post[] +} +// add-end +``` + +### 9.2. Create and apply a migration: + +```terminal +npx prisma migrate dev --name your_migration_name +``` + +This command will: +- Create a new SQL migration file +- Apply the migration to your database +- Regenerate Prisma Client + +## 10. Explore your data with Prisma Studio + + + +## Next steps + + + +## More info + +- [Prisma Postgres documentation](/postgres) +- [Prisma Config reference](/orm/reference/prisma-config-reference) +- [Database introspection](/orm/prisma-schema/introspection) +- [Prisma Migrate](/orm/prisma-migrate) diff --git a/content/100-getting-started/02-prisma-orm/200-add-to-existing-project/200-sqlite.mdx b/content/100-getting-started/02-prisma-orm/200-add-to-existing-project/200-sqlite.mdx new file mode 100644 index 0000000000..e9d5d66134 --- /dev/null +++ b/content/100-getting-started/02-prisma-orm/200-add-to-existing-project/200-sqlite.mdx @@ -0,0 +1,261 @@ +--- +title: 'Add Prisma ORM to an existing SQLite project' +sidebar_title: 'SQLite' +metaTitle: 'How to add Prisma ORM to an existing project using SQLite (15 min)' +metaDescription: 'Add Prisma ORM to an existing TypeScript project with SQLite and learn database introspection, baselining, and querying.' +sidebar_custom_props: { badge: '15 min' } +--- + +import Prerequisites from '../../_components/_prerequisites.mdx' +import ExploreData from '../../_components/_explore-data.mdx' +import NextSteps from '../../_components/_next-steps.mdx' + +[SQLite](https://sqlite.org) is a lightweight, file-based database that's perfect for development, prototyping, and small applications. It requires no setup and stores data in a local file. In this guide, you will learn how to add Prisma ORM to an existing TypeScript project, connect it to SQLite, introspect your existing database schema, and start querying with type-safe Prisma Client. + +## Prerequisites + + + +## 1. Set up Prisma ORM + +Navigate to your existing project directory and install the required dependencies: + +```terminal +npm install prisma @types/node --save-dev +npm install @prisma/client @prisma/adapter-better-sqlite3 dotenv +``` + +Here's what each package does: + +- **`prisma`** - The Prisma CLI for running commands like `prisma init`, `prisma db pull`, and `prisma generate` +- **`@prisma/client`** - The Prisma Client library for querying your database +- **`@prisma/adapter-better-sqlite3`** - The SQLite driver adapter that connects Prisma Client to your database +- **`dotenv`** - Loads environment variables from your `.env` file + +## 2. Initialize Prisma ORM + +Set up your Prisma ORM project by creating your [Prisma Schema](/orm/prisma-schema) file with the following command: + +```terminal +npx prisma init --datasource-provider sqlite --output ../generated/prisma +``` + +This command does a few things: + +- Creates a `prisma/` directory with a `schema.prisma` file containing your database connection configuration +- Creates a `.env` file in the root directory for environment variables +- Creates a `prisma.config.ts` file for Prisma configuration + +The generated `prisma.config.ts` file looks like this: + +```typescript file=prisma.config.ts +import { defineConfig, env } from 'prisma/config' + +export default defineConfig({ + schema: 'prisma/schema.prisma', + migrations: { + path: 'prisma/migrations', + }, + datasource: { + url: env('DATABASE_URL'), + }, +}) +``` + +Add `dotenv` to `prisma.config.ts` so that Prisma can load environment variables from your `.env` file: + +```typescript file=prisma.config.ts +// add-start +import 'dotenv/config' +// add-end +import { defineConfig, env } from 'prisma/config' + +export default defineConfig({ + schema: 'prisma/schema.prisma', + migrations: { + path: 'prisma/migrations', + }, + datasource: { + url: env('DATABASE_URL'), + }, +}) +``` + +The generated schema uses [the ESM-first `prisma-client` generator](/orm/prisma-schema/overview/generators#prisma-client) with a custom output path: + +```prisma file=prisma/schema.prisma +generator client { + provider = "prisma-client" + output = "../generated/prisma" +} + +datasource db { + provider = "sqlite" +} +``` + +A `.env` file should be created with the following value: + +```env file=.env +DATABASE_URL="file:./dev.db" +``` + +## 3. Connect your database + +Update the `.env` file to point to your existing SQLite database file: + +```bash file=.env +DATABASE_URL="file:./path/to/your/database.db" +``` + +## 4. Introspect your database + +Run the following command to introspect your existing database: + +```terminal +npx prisma db pull +``` + +This command reads the `DATABASE_URL` environment variable, connects to your database, and introspects the database schema. It then translates the database schema from SQL into a data model in your Prisma schema. + +![Introspect your database with Prisma ORM](/img/getting-started/prisma-db-pull-generate-schema.png) + +After introspection, your Prisma schema will contain models that represent your existing database tables. + +## 5. Baseline your database + +To use Prisma Migrate with your existing database, you need to [baseline your database](/orm/prisma-migrate/getting-started). + +First, create a `migrations` directory: + +```terminal +mkdir -p prisma/migrations/0_init +``` + +Next, generate the migration file with `prisma migrate diff`: + +```terminal +npx prisma migrate diff --from-empty --to-schema prisma/schema.prisma --script > prisma/migrations/0_init/migration.sql +``` + +Review the generated migration file to ensure it matches your database schema. + +Then, mark the migration as applied: + +```terminal +npx prisma migrate resolve --applied 0_init +``` + +You now have a baseline for your current database schema. + +## 6. Generate Prisma ORM types + +Generate Prisma Client based on your introspected schema: + +```terminal +npx prisma generate +``` + +This creates a type-safe Prisma Client tailored to your database schema in the `generated/prisma` directory. + +## 7. Instantiate Prisma Client + +Create a utility file to instantiate Prisma Client. You need to pass an instance of Prisma ORM's driver adapter to the `PrismaClient` constructor: + +```typescript file=lib/prisma.ts +import "dotenv/config"; +import { PrismaBetterSqlite3 } from "@prisma/adapter-better-sqlite3"; +import { PrismaClient } from "../generated/prisma/client"; + +const connectionString = `${process.env.DATABASE_URL}`; + +const adapter = new PrismaBetterSqlite3({ url: connectionString }); +const prisma = new PrismaClient({ adapter }); + +export { prisma }; +``` + +## 8. Query your database + +Now you can use Prisma Client to query your database. Create a `script.ts` file: + +```typescript file=script.ts +import { prisma } from './lib/prisma' + +async function main() { + // Example: Fetch all records from a table + // Replace 'user' with your actual model name + const allUsers = await prisma.user.findMany() + console.log('All users:', JSON.stringify(allUsers, null, 2)) +} + +main() + .then(async () => { + await prisma.$disconnect() + }) + .catch(async (e) => { + console.error(e) + await prisma.$disconnect() + process.exit(1) + }) +``` + +Run the script: + +```terminal +npx tsx script.ts +``` + +## 9. Evolve your schema + +To make changes to your database schema: + +### 9.1. Update your Prisma schema file + +Update your Prisma schema file to reflect the changes you want to make to your database schema. For example, add a new model: + +```prisma file=prisma/schema.prisma +// add-start +model Post { + id Int @id @default(autoincrement()) + title String + content String? + published Boolean @default(false) + authorId Int + author User @relation(fields: [authorId], references: [id]) +} + +model User { + id Int @id @default(autoincrement()) + email String @unique + name String? + posts Post[] +} +// add-end +``` + +### 9.2. Create and apply a migration: + +```terminal +npx prisma migrate dev --name your_migration_name +``` + +This command will: +- Create a new SQL migration file +- Apply the migration to your database +- Regenerate Prisma Client + +## 10. Explore your data with Prisma Studio + + + +## Next steps + + + +## More info + +- [SQLite database connector](/orm/overview/databases/sqlite) +- [Prisma Config reference](/orm/reference/prisma-config-reference) +- [Database introspection](/orm/prisma-schema/introspection) +- [Prisma Migrate](/orm/prisma-migrate) diff --git a/content/100-getting-started/02-prisma-orm/200-add-to-existing-project/300-postgresql.mdx b/content/100-getting-started/02-prisma-orm/200-add-to-existing-project/300-postgresql.mdx new file mode 100644 index 0000000000..46deacf6c4 --- /dev/null +++ b/content/100-getting-started/02-prisma-orm/200-add-to-existing-project/300-postgresql.mdx @@ -0,0 +1,261 @@ +--- +title: 'Add Prisma ORM to an existing PostgreSQL project' +sidebar_title: 'PostgreSQL' +metaTitle: 'How to add Prisma ORM to an existing project using PostgreSQL (15 min)' +metaDescription: 'Add Prisma ORM to an existing TypeScript project with PostgreSQL and learn database introspection, baselining, and querying.' +sidebar_custom_props: { badge: '15 min' } +--- + +import Prerequisites from '../../_components/_prerequisites.mdx' +import ExploreData from '../../_components/_explore-data.mdx' +import NextSteps from '../../_components/_next-steps.mdx' + +[PostgreSQL](https://www.postgresql.org/) is a popular open-source relational database known for its reliability, feature robustness, and performance. In this guide, you will learn how to add Prisma ORM to an existing TypeScript project, connect it to PostgreSQL, introspect your existing database schema, and start querying with type-safe Prisma Client. + +## Prerequisites + + + +## 1. Set up Prisma ORM + +Navigate to your existing project directory and install the required dependencies: + +```terminal +npm install prisma @types/node --save-dev +npm install @prisma/client @prisma/adapter-pg dotenv +``` + +Here's what each package does: + +- **`prisma`** - The Prisma CLI for running commands like `prisma init`, `prisma db pull`, and `prisma generate` +- **`@prisma/client`** - The Prisma Client library for querying your database +- **`@prisma/adapter-pg`** - The [`node-postgres` driver adapter](/orm/overview/databases/postgresql#using-the-node-postgres-driver) that connects Prisma Client to your database +- **`dotenv`** - Loads environment variables from your `.env` file + +## 2. Initialize Prisma ORM + +Set up your Prisma ORM project by creating your [Prisma Schema](/orm/prisma-schema) file with the following command: + +```terminal +npx prisma init --datasource-provider postgresql --output ../generated/prisma +``` + +This command does a few things: + +- Creates a `prisma/` directory with a `schema.prisma` file containing your database connection configuration +- Creates a `.env` file in the root directory for environment variables +- Creates a `prisma.config.ts` file for Prisma configuration + +The generated `prisma.config.ts` file looks like this: + +```typescript file=prisma.config.ts +import { defineConfig, env } from 'prisma/config' + +export default defineConfig({ + schema: 'prisma/schema.prisma', + migrations: { + path: 'prisma/migrations', + }, + datasource: { + url: env('DATABASE_URL'), + }, +}) +``` + +Add `dotenv` to `prisma.config.ts` so that Prisma can load environment variables from your `.env` file: + +```typescript file=prisma.config.ts +// add-start +import 'dotenv/config' +// add-end +import { defineConfig, env } from 'prisma/config' + +export default defineConfig({ + schema: 'prisma/schema.prisma', + migrations: { + path: 'prisma/migrations', + }, + datasource: { + url: env('DATABASE_URL'), + }, +}) +``` + +The generated schema uses [the ESM-first `prisma-client` generator](/orm/prisma-schema/overview/generators#prisma-client) with a custom output path: + +```prisma file=prisma/schema.prisma +generator client { + provider = "prisma-client" + output = "../generated/prisma" +} + +datasource db { + provider = "postgresql" +} +``` + +## 3. Connect your database + +Update the `.env` file with your PostgreSQL connection URL: + +```bash file=.env +DATABASE_URL="postgresql://user:password@localhost:5432/mydb?schema=public" +``` + +The [format of the connection URL](/orm/reference/connection-urls) for PostgreSQL looks as follows: + +``` +postgresql://USER:PASSWORD@HOST:PORT/DATABASE?schema=SCHEMA +``` + +## 4. Introspect your database + +Run the following command to introspect your existing database: + +```terminal +npx prisma db pull +``` + +This command reads the `DATABASE_URL` environment variable, connects to your database, and introspects the database schema. It then translates the database schema from SQL into a data model in your Prisma schema. + +![Introspect your database with Prisma ORM](/img/getting-started/prisma-db-pull-generate-schema.png) + +After introspection, your Prisma schema will contain models that represent your existing database tables. + +## 5. Baseline your database + +To use Prisma Migrate with your existing database, you need to [baseline your database](/orm/prisma-migrate/getting-started). + +First, create a `migrations` directory: + +```terminal +mkdir -p prisma/migrations/0_init +``` + +Next, generate the migration file with `prisma migrate diff`: + +```terminal +npx prisma migrate diff --from-empty --to-schema prisma/schema.prisma --script > prisma/migrations/0_init/migration.sql +``` + +Review the generated migration file to ensure it matches your database schema. + +Then, mark the migration as applied: + +```terminal +npx prisma migrate resolve --applied 0_init +``` + +You now have a baseline for your current database schema. + +## 6. Generate Prisma ORM types + +Generate Prisma Client based on your introspected schema: + +```terminal +npx prisma generate +``` + +This creates a type-safe Prisma Client tailored to your database schema in the `generated/prisma` directory. + +## 7. Instantiate Prisma Client + +Create a utility file to instantiate Prisma Client. You need to pass an instance of Prisma ORM's driver adapter to the `PrismaClient` constructor: + +```typescript file=lib/prisma.ts +import "dotenv/config"; +import { PrismaPg } from '@prisma/adapter-pg' +import { PrismaClient } from '../generated/prisma/client' + +const connectionString = `${process.env.DATABASE_URL}` + +const adapter = new PrismaPg({ connectionString }) +const prisma = new PrismaClient({ adapter }) + +export { prisma } +``` + +## 8. Query your database + +Now you can use Prisma Client to query your database. Create a `script.ts` file: + +```typescript file=script.ts +import { prisma } from './lib/prisma' + +async function main() { + // Example: Fetch all records from a table + // Replace 'user' with your actual model name + const allUsers = await prisma.user.findMany() + console.log('All users:', JSON.stringify(allUsers, null, 2)) +} + +main() + .then(async () => { + await prisma.$disconnect() + }) + .catch(async (e) => { + console.error(e) + await prisma.$disconnect() + process.exit(1) + }) +``` + +Run the script: + +```terminal +npx tsx script.ts +``` + +## 9. Evolve your schema + +To make changes to your database schema: + +### 9.1. Update your Prisma schema file + +Update your Prisma schema file to reflect the changes you want to make to your database schema. For example, add a new model: + +```prisma file=prisma/schema.prisma +// add-start +model Post { + id Int @id @default(autoincrement()) + title String + content String? + published Boolean @default(false) + authorId Int + author User @relation(fields: [authorId], references: [id]) +} + +model User { + id Int @id @default(autoincrement()) + email String @unique + name String? + posts Post[] +} +// add-end +``` + +### 9.2. Create and apply a migration: + +```terminal +npx prisma migrate dev --name your_migration_name +``` + +This command will: +- Create a new SQL migration file +- Apply the migration to your database +- Regenerate Prisma Client + +## 10. Explore your data with Prisma Studio + + + +## Next steps + + + +## More info + +- [PostgreSQL database connector](/orm/overview/databases/postgresql) +- [Prisma Config reference](/orm/reference/prisma-config-reference) +- [Database introspection](/orm/prisma-schema/introspection) +- [Prisma Migrate](/orm/prisma-migrate) diff --git a/content/100-getting-started/02-prisma-orm/200-add-to-existing-project/400-mysql.mdx b/content/100-getting-started/02-prisma-orm/200-add-to-existing-project/400-mysql.mdx new file mode 100644 index 0000000000..6830a8aa8c --- /dev/null +++ b/content/100-getting-started/02-prisma-orm/200-add-to-existing-project/400-mysql.mdx @@ -0,0 +1,272 @@ +--- +title: 'Add Prisma ORM to an existing MySQL project' +sidebar_title: 'MySQL' +metaTitle: 'How to add Prisma ORM to an existing project using MySQL (15 min)' +metaDescription: 'Add Prisma ORM to an existing TypeScript project with MySQL and learn database introspection, baselining, and querying.' +sidebar_custom_props: { badge: '15 min' } +--- + +import Prerequisites from '../../_components/_prerequisites.mdx' +import ExploreData from '../../_components/_explore-data.mdx' +import NextSteps from '../../_components/_next-steps.mdx' + +[MySQL](https://www.mysql.com/) is a widely-used open-source relational database management system known for its speed, reliability, and ease of use. In this guide, you will learn how to add Prisma ORM to an existing TypeScript project, connect it to MySQL, introspect your existing database schema, and start querying with type-safe Prisma Client. + +## Prerequisites + + + +## 1. Set up Prisma ORM + +Navigate to your existing project directory and install the required dependencies: + +```terminal +npm install prisma @types/node --save-dev +npm install @prisma/client @prisma/adapter-mariadb dotenv +``` + +Here's what each package does: + +- **`prisma`** - The Prisma CLI for running commands like `prisma init`, `prisma db pull`, and `prisma generate` +- **`@prisma/client`** - The Prisma Client library for querying your database +- **`@prisma/adapter-mariadb`** - The MySQL/MariaDB driver adapter that connects Prisma Client to your database +- **`dotenv`** - Loads environment variables from your `.env` file + +## 2. Initialize Prisma ORM + +Set up your Prisma ORM project by creating your [Prisma Schema](/orm/prisma-schema) file with the following command: + +```terminal +npx prisma init --datasource-provider mysql --output ../generated/prisma +``` + +This command does a few things: + +- Creates a `prisma/` directory with a `schema.prisma` file containing your database connection configuration +- Creates a `.env` file in the root directory for environment variables +- Creates a `prisma.config.ts` file for Prisma configuration + +The generated `prisma.config.ts` file looks like this: + +```typescript file=prisma.config.ts +import { defineConfig, env } from 'prisma/config' + +export default defineConfig({ + schema: 'prisma/schema.prisma', + migrations: { + path: 'prisma/migrations', + }, + datasource: { + url: env('DATABASE_URL'), + }, +}) +``` + +Add `dotenv` to `prisma.config.ts` so that Prisma can load environment variables from your `.env` file: + +```typescript file=prisma.config.ts +// add-start +import 'dotenv/config' +// add-end +import { defineConfig, env } from 'prisma/config' + +export default defineConfig({ + schema: 'prisma/schema.prisma', + migrations: { + path: 'prisma/migrations', + }, + datasource: { + url: env('DATABASE_URL'), + }, +}) +``` + +The generated schema uses [the ESM-first `prisma-client` generator](/orm/prisma-schema/overview/generators#prisma-client) with a custom output path: + +```prisma file=prisma/schema.prisma +generator client { + provider = "prisma-client" + output = "../generated/prisma" +} + +datasource db { + provider = "mysql" +} +``` + +## 3. Connect your database + +Update the `.env` file with your MySQL connection string details: + +```bash file=.env +DATABASE_URL="mysql://username:password@localhost:3306/mydb" +//add-start +DATABASE_USER="username" +DATABASE_PASSWORD="password" +DATABASE_NAME="mydb" +DATABASE_HOST="localhost" +DATABASE_PORT=3306 +//add-end +``` + +Replace the placeholders with your actual database credentials: +- `username`: Your MySQL username +- `password`: Your MySQL password +- `localhost:3306`: Your MySQL host and port +- `mydb`: Your database name + +## 4. Introspect your database + +Run the following command to introspect your existing database: + +```terminal +npx prisma db pull +``` + +This command reads the `DATABASE_URL` environment variable, connects to your database, and introspects the database schema. It then translates the database schema from SQL into a data model in your Prisma schema. + +![Introspect your database with Prisma ORM](/img/getting-started/prisma-db-pull-generate-schema.png) + +After introspection, your Prisma schema will contain models that represent your existing database tables. + +## 5. Baseline your database + +To use Prisma Migrate with your existing database, you need to [baseline your database](/orm/prisma-migrate/getting-started). + +First, create a `migrations` directory: + +```terminal +mkdir -p prisma/migrations/0_init +``` + +Next, generate the migration file with `prisma migrate diff`: + +```terminal +npx prisma migrate diff --from-empty --to-schema prisma/schema.prisma --script > prisma/migrations/0_init/migration.sql +``` + +Review the generated migration file to ensure it matches your database schema. + +Then, mark the migration as applied: + +```terminal +npx prisma migrate resolve --applied 0_init +``` + +You now have a baseline for your current database schema. + +## 6. Generate Prisma ORM types + +Generate Prisma Client based on your introspected schema: + +```terminal +npx prisma generate +``` + +This creates a type-safe Prisma Client tailored to your database schema in the `generated/prisma` directory. + +## 7. Instantiate Prisma Client + +Create a utility file to instantiate Prisma Client. You need to pass an instance of Prisma ORM's driver adapter to the `PrismaClient` constructor: + +```typescript file=lib/prisma.ts +import "dotenv/config"; +import { PrismaMariaDb } from '@prisma/adapter-mariadb'; +import { PrismaClient } from '../generated/prisma/client'; + +const adapter = new PrismaMariaDb({ + host: process.env.DATABASE_HOST, + user: process.env.DATABASE_USER, + password: process.env.DATABASE_PASSWORD, + database: process.env.DATABASE_NAME, + connectionLimit: 5 +}); +const prisma = new PrismaClient({ adapter }); + +export { prisma } +``` + +## 8. Query your database + +Now you can use Prisma Client to query your database. Create a `script.ts` file: + +```typescript file=script.ts +import { prisma } from './lib/prisma' + +async function main() { + // Example: Fetch all records from a table + // Replace 'user' with your actual model name + const allUsers = await prisma.user.findMany() + console.log('All users:', JSON.stringify(allUsers, null, 2)) +} + +main() + .then(async () => { + await prisma.$disconnect() + }) + .catch(async (e) => { + console.error(e) + await prisma.$disconnect() + process.exit(1) + }) +``` + +Run the script: + +```terminal +npx tsx script.ts +``` + +## 9. Evolve your schema + +To make changes to your database schema: + +### 9.1. Update your Prisma schema file + +Update your Prisma schema file to reflect the changes you want to make to your database schema. For example, add a new model: + +```prisma file=prisma/schema.prisma +// add-start +model Post { + id Int @id @default(autoincrement()) + title String + content String? + published Boolean @default(false) + authorId Int + author User @relation(fields: [authorId], references: [id]) +} + +model User { + id Int @id @default(autoincrement()) + email String @unique + name String? + posts Post[] +} +// add-end +``` + +### 9.2. Create and apply a migration: + +```terminal +npx prisma migrate dev --name your_migration_name +``` + +This command will: +- Create a new SQL migration file +- Apply the migration to your database +- Regenerate Prisma Client + +## 10. Explore your data with Prisma Studio + + + +## Next steps + + + +## More info + +- [MySQL database connector](/orm/overview/databases/mysql) +- [Prisma Config reference](/orm/reference/prisma-config-reference) +- [Database introspection](/orm/prisma-schema/introspection) +- [Prisma Migrate](/orm/prisma-migrate) diff --git a/content/100-getting-started/02-prisma-orm/200-add-to-existing-project/500-sql-server.mdx b/content/100-getting-started/02-prisma-orm/200-add-to-existing-project/500-sql-server.mdx new file mode 100644 index 0000000000..ca420d5d2b --- /dev/null +++ b/content/100-getting-started/02-prisma-orm/200-add-to-existing-project/500-sql-server.mdx @@ -0,0 +1,282 @@ +--- +title: 'Add Prisma ORM to an existing SQL Server project' +sidebar_title: 'SQL Server' +metaTitle: 'How to add Prisma ORM to an existing project using SQL Server (15 min)' +metaDescription: 'Add Prisma ORM to an existing TypeScript project with SQL Server and learn database introspection, baselining, and querying.' +sidebar_custom_props: { badge: '15 min' } +--- + +import Prerequisites from '../../_components/_prerequisites.mdx' +import ExploreData from '../../_components/_explore-data.mdx' +import NextSteps from '../../_components/_next-steps.mdx' + +[SQL Server](https://www.microsoft.com/en-us/sql-server) is Microsoft's enterprise relational database management system known for its performance, security, and integration with Microsoft tools. In this guide, you will learn how to add Prisma ORM to an existing TypeScript project, connect it to SQL Server, introspect your existing database schema, and start querying with type-safe Prisma Client. + +## Prerequisites + + + +## 1. Set up Prisma ORM + +Navigate to your existing project directory and install the required dependencies: + +```terminal +npm install prisma @types/node --save-dev +npm install @prisma/client @prisma/adapter-mssql dotenv +``` + +Here's what each package does: + +- **`prisma`** - The Prisma CLI for running commands like `prisma init`, `prisma db pull`, and `prisma generate` +- **`@prisma/client`** - The Prisma Client library for querying your database +- **`@prisma/adapter-mssql`** - The SQL Server driver adapter that connects Prisma Client to your database +- **`dotenv`** - Loads environment variables from your `.env` file + +## 2. Initialize Prisma ORM + +Set up your Prisma ORM project by creating your [Prisma Schema](/orm/prisma-schema) file with the following command: + +```terminal +npx prisma init --datasource-provider sqlserver --output ../generated/prisma +``` + +This command does a few things: + +- Creates a `prisma/` directory with a `schema.prisma` file containing your database connection configuration +- Creates a `.env` file in the root directory for environment variables +- Creates a `prisma.config.ts` file for Prisma configuration + +The generated `prisma.config.ts` file looks like this: + +```typescript file=prisma.config.ts +import { defineConfig, env } from 'prisma/config' + +export default defineConfig({ + schema: 'prisma/schema.prisma', + migrations: { + path: 'prisma/migrations', + }, + datasource: { + url: env('DATABASE_URL'), + }, +}) +``` + +Add `dotenv` to `prisma.config.ts` so that Prisma can load environment variables from your `.env` file: + +```typescript file=prisma.config.ts +// add-start +import 'dotenv/config' +// add-end +import { defineConfig, env } from 'prisma/config' + +export default defineConfig({ + schema: 'prisma/schema.prisma', + migrations: { + path: 'prisma/migrations', + }, + datasource: { + url: env('DATABASE_URL'), + }, +}) +``` + +The generated schema uses [the ESM-first `prisma-client` generator](/orm/prisma-schema/overview/generators#prisma-client) with a custom output path: + +```prisma file=prisma/schema.prisma +generator client { + provider = "prisma-client" + output = "../generated/prisma" +} + +datasource db { + provider = "sqlserver" +} +``` + +## 3. Connect your database + +Update the `.env` file with your SQL Server connection string details: + +```bash file=.env +DATABASE_URL="sqlserver://localhost:1433;database=mydb;user=username;password=password;encrypt=true" +//add-start +DB_USER="username" +DB_PASSWORD="password" +DB_NAME="mydb" +HOST="localhost" +//add-end +``` + +Replace the placeholders with your actual database credentials: + +- `localhost:1433`: Your SQL Server host and port +- `mydb`: Your database name +- `username`: Your SQL Server username +- `password`: Your SQL Server password + +## 4. Introspect your database + +Run the following command to introspect your existing database: + +```terminal +npx prisma db pull +``` + +This command reads the `DATABASE_URL` environment variable, connects to your database, and introspects the database schema. It then translates the database schema from SQL into a data model in your Prisma schema. + +![Introspect your database with Prisma ORM](/img/getting-started/prisma-db-pull-generate-schema.png) + +After introspection, your Prisma schema will contain models that represent your existing database tables. + +## 5. Baseline your database + +To use Prisma Migrate with your existing database, you need to [baseline your database](/orm/prisma-migrate/getting-started). + +First, create a `migrations` directory: + +```terminal +mkdir -p prisma/migrations/0_init +``` + +Next, generate the migration file with `prisma migrate diff`: + +```terminal +npx prisma migrate diff --from-empty --to-schema prisma/schema.prisma --script > prisma/migrations/0_init/migration.sql +``` + +Review the generated migration file to ensure it matches your database schema. + +Then, mark the migration as applied: + +```terminal +npx prisma migrate resolve --applied 0_init +``` + +You now have a baseline for your current database schema. + +## 6. Generate Prisma ORM types + +Generate Prisma Client based on your introspected schema: + +```terminal +npx prisma generate +``` + +This creates a type-safe Prisma Client tailored to your database schema in the `generated/prisma` directory. + +## 7. Instantiate Prisma Client + +Create a utility file to instantiate Prisma Client. You need to pass an instance of Prisma ORM's driver adapter to the `PrismaClient` constructor: + +```typescript file=lib/prisma.ts +import "dotenv/config"; +import { PrismaMSSQL } from '@prisma/adapter-mssql'; +import { PrismaClient } from '../generated/prisma/client'; + +const sqlConfig = { + user: process.env.DB_USER, + password: process.env.DB_PASSWORD, + database: process.env.DB_NAME, + server: process.env.HOST, + pool: { + max: 10, + min: 0, + idleTimeoutMillis: 30000 + }, + options: { + encrypt: true, // for azure + trustServerCertificate: false // change to true for local dev / self-signed certs + } +} + +const adapter = new PrismaMSSQL(sqlConfig) +const prisma = new PrismaClient({ adapter }); + +export { prisma } +``` + +## 8. Query your database + +Now you can use Prisma Client to query your database. Create a `script.ts` file: + +```typescript file=script.ts +import { prisma } from './lib/prisma' + +async function main() { + // Example: Fetch all records from a table + // Replace 'user' with your actual model name + const allUsers = await prisma.user.findMany() + console.log('All users:', JSON.stringify(allUsers, null, 2)) +} + +main() + .then(async () => { + await prisma.$disconnect() + }) + .catch(async (e) => { + console.error(e) + await prisma.$disconnect() + process.exit(1) + }) +``` + +Run the script: + +```terminal +npx tsx script.ts +``` + +## 9. Evolve your schema + +To make changes to your database schema: + +### 9.1. Update your Prisma schema file + +Update your Prisma schema file to reflect the changes you want to make to your database schema. For example, add a new model: + +```prisma file=prisma/schema.prisma +// add-start +model Post { + id Int @id @default(autoincrement()) + title String + content String? + published Boolean @default(false) + authorId Int + author User @relation(fields: [authorId], references: [id]) +} + +model User { + id Int @id @default(autoincrement()) + email String @unique + name String? + posts Post[] +} +// add-end +``` + +### 9.2. Create and apply a migration: + +```terminal +npx prisma migrate dev --name your_migration_name +``` + +This command will: +- Create a new SQL migration file +- Apply the migration to your database +- Regenerate Prisma Client + +## 10. Explore your data with Prisma Studio + + + +## Next steps + + + +## More info + +- [SQL Server database connector](/orm/overview/databases/sql-server) +- [Prisma Config reference](/orm/reference/prisma-config-reference) +- [Database introspection](/orm/prisma-schema/introspection) +- [Prisma Migrate](/orm/prisma-migrate) diff --git a/content/100-getting-started/02-prisma-orm/200-add-to-existing-project/600-planetscale.mdx b/content/100-getting-started/02-prisma-orm/200-add-to-existing-project/600-planetscale.mdx new file mode 100644 index 0000000000..66bf9be2f2 --- /dev/null +++ b/content/100-getting-started/02-prisma-orm/200-add-to-existing-project/600-planetscale.mdx @@ -0,0 +1,249 @@ +--- +title: 'Add Prisma ORM to an existing PlanetScale project' +sidebar_title: 'PlanetScale' +metaTitle: 'How to add Prisma ORM to an existing project using PlanetScale MySQL (15 min)' +metaDescription: 'Add Prisma ORM to an existing TypeScript project with PlanetScale MySQL and learn database introspection and querying.' +sidebar_custom_props: { badge: '15 min' } +--- + +import Prerequisites from '../../_components/_prerequisites.mdx' +import ExploreData from '../../_components/_explore-data.mdx' +import NextSteps from '../../_components/_next-steps.mdx' + +[PlanetScale](https://planetscale.com) is a serverless database platform. This guide covers **PlanetScale MySQL**, which is built on Vitess and offers database branching, non-blocking schema changes, and automatic backups. In this guide, you will learn how to add Prisma ORM to an existing TypeScript project, connect it to PlanetScale MySQL, introspect your existing database schema, and start querying with type-safe Prisma Client. + +:::note + +PlanetScale also offers PostgreSQL databases. If you're using **PlanetScale PostgreSQL**, follow the [Add to existing PostgreSQL project guide](/getting-started/prisma-orm/add-to-existing-project/postgresql) instead. + +::: + +## Prerequisites + + + +## 1. Set up Prisma ORM + +Navigate to your existing project directory and install the required dependencies: + +```terminal +npm install prisma @types/node --save-dev +npm install @prisma/client @prisma/adapter-planetscale undici dotenv +``` + +Here's what each package does: + +- **`prisma`** - The Prisma CLI for running commands like `prisma init`, `prisma db pull`, and `prisma generate` +- **`@prisma/client`** - The Prisma Client library for querying your database +- **`@prisma/adapter-planetscale`** - The PlanetScale driver adapter that connects Prisma Client to your database +- **`undici`** - A fast HTTP/1.1 client required by the PlanetScale adapter +- **`dotenv`** - Loads environment variables from your `.env` file + +## 2. Initialize Prisma ORM + +Set up your Prisma ORM project by creating your [Prisma Schema](/orm/prisma-schema) file with the following command: + +```terminal +npx prisma init --datasource-provider mysql --output ../generated/prisma +``` + +This command does a few things: + +- Creates a `prisma/` directory with a `schema.prisma` file containing your database connection configuration +- Creates a `.env` file in the root directory for environment variables +- Creates a `prisma.config.ts` file for Prisma configuration + +The generated `prisma.config.ts` file looks like this: + +```typescript file=prisma.config.ts +import { defineConfig, env } from 'prisma/config' + +export default defineConfig({ + schema: 'prisma/schema.prisma', + migrations: { + path: 'prisma/migrations', + }, + datasource: { + url: env('DATABASE_URL'), + }, +}) +``` + +Add `dotenv` to `prisma.config.ts` so that Prisma can load environment variables from your `.env` file: + +```typescript file=prisma.config.ts +// add-start +import 'dotenv/config' +// add-end +import { defineConfig, env } from 'prisma/config' + +export default defineConfig({ + schema: 'prisma/schema.prisma', + migrations: { + path: 'prisma/migrations', + }, + datasource: { + url: env('DATABASE_URL'), + }, +}) +``` + +The generated schema uses [the ESM-first `prisma-client` generator](/orm/prisma-schema/overview/generators#prisma-client) with a custom output path: + +```prisma file=prisma/schema.prisma +generator client { + provider = "prisma-client" + output = "../generated/prisma" +} + +datasource db { + provider = "mysql" + relationMode = "prisma" +} +``` + +:::info + +PlanetScale requires `relationMode = "prisma"` because it doesn't support foreign key constraints. + +::: + +## 3. Connect your database + +Update the `.env` file with your PlanetScale connection URL: + +```bash file=.env +DATABASE_URL="mysql://username:password@host.connect.psdb.cloud/mydb?sslaccept=strict" +``` + +You can find your connection string in the PlanetScale dashboard. + +## 4. Introspect your database + +Run the following command to introspect your existing database: + +```terminal +npx prisma db pull +``` + +This command reads the `DATABASE_URL` environment variable, connects to your database, and introspects the database schema. It then translates the database schema from SQL into a data model in your Prisma schema. + +![Introspect your database with Prisma ORM](/img/getting-started/prisma-db-pull-generate-schema.png) + +After introspection, your Prisma schema will contain models that represent your existing database tables. + +## 5. Generate Prisma ORM types + +Generate Prisma Client based on your introspected schema: + +```terminal +npx prisma generate +``` + +This creates a type-safe Prisma Client tailored to your database schema in the `generated/prisma` directory. + +## 6. Instantiate Prisma Client + +Create a utility file to instantiate Prisma Client. You need to pass an instance of Prisma ORM's driver adapter to the `PrismaClient` constructor: + +```typescript file=lib/prisma.ts +import "dotenv/config"; +import { PrismaPlanetScale } from '@prisma/adapter-planetscale' +import { PrismaClient } from '../generated/prisma/client' +import { fetch as undiciFetch } from 'undici' + +const adapter = new PrismaPlanetScale({ url: process.env.DATABASE_URL, fetch: undiciFetch }) +const prisma = new PrismaClient({ adapter }) + +export { prisma } +``` + +## 7. Query your database + +Now you can use Prisma Client to query your database. Create a `script.ts` file: + +```typescript file=script.ts +import { prisma } from './lib/prisma' + +async function main() { + // Example: Fetch all records from a table + // Replace 'user' with your actual model name + const allUsers = await prisma.user.findMany() + console.log('All users:', JSON.stringify(allUsers, null, 2)) +} + +main() + .then(async () => { + await prisma.$disconnect() + }) + .catch(async (e) => { + console.error(e) + await prisma.$disconnect() + process.exit(1) + }) +``` + +Run the script: + +```terminal +npx tsx script.ts +``` + +## 8. Evolve your schema + +PlanetScale uses a branching workflow instead of traditional migrations. To make changes to your database schema: + +### 8.1. Update your Prisma schema file + +Update your Prisma schema file to reflect the changes you want to make to your database schema. For example, add a new model: + +```prisma file=prisma/schema.prisma +// add-start +model Post { + id Int @id @default(autoincrement()) + title String + content String? + published Boolean @default(false) + authorId Int + author User @relation(fields: [authorId], references: [id]) +} + +model User { + id Int @id @default(autoincrement()) + email String @unique + name String? + posts Post[] +} +// add-end +``` + +### 8.2. Push the changes to your development branch: + +```terminal +npx prisma db push +``` + +This command will: +- Apply the schema changes to your PlanetScale database +- Regenerate Prisma Client + +:::info + +For production deployments, use PlanetScale's [branching workflow](https://planetscale.com/docs/concepts/branching) to create deploy requests. + +::: + +## 9. Explore your data with Prisma Studio + + + +## Next steps + + + +## More info + +- [PlanetScale database connector](/orm/overview/databases/planetscale) +- [Prisma Config reference](/orm/reference/prisma-config-reference) +- [Database introspection](/orm/prisma-schema/introspection) +- [PlanetScale branching workflow](https://planetscale.com/docs/concepts/branching) diff --git a/content/100-getting-started/02-prisma-orm/200-add-to-existing-project/700-cockroachdb.mdx b/content/100-getting-started/02-prisma-orm/200-add-to-existing-project/700-cockroachdb.mdx new file mode 100644 index 0000000000..8e6215d96a --- /dev/null +++ b/content/100-getting-started/02-prisma-orm/200-add-to-existing-project/700-cockroachdb.mdx @@ -0,0 +1,261 @@ +--- +title: 'Add Prisma ORM to an existing CockroachDB project' +sidebar_title: 'CockroachDB' +metaTitle: 'How to add Prisma ORM to an existing project using CockroachDB (15 min)' +metaDescription: 'Add Prisma ORM to an existing TypeScript project with CockroachDB and learn database introspection, baselining, and querying.' +sidebar_custom_props: { badge: '15 min' } +--- + +import Prerequisites from '../../_components/_prerequisites.mdx' +import ExploreData from '../../_components/_explore-data.mdx' +import NextSteps from '../../_components/_next-steps.mdx' + +[CockroachDB](https://www.cockroachlabs.com/) is a distributed SQL database designed for cloud applications, offering horizontal scalability, strong consistency, and high availability. In this guide, you will learn how to add Prisma ORM to an existing TypeScript project, connect it to CockroachDB, introspect your existing database schema, and start querying with type-safe Prisma Client. + +## Prerequisites + + + +## 1. Set up Prisma ORM + +Navigate to your existing project directory and install the required dependencies: + +```terminal +npm install prisma @types/node --save-dev +npm install @prisma/client @prisma/adapter-pg dotenv +``` + +Here's what each package does: + +- **`prisma`** - The Prisma CLI for running commands like `prisma init`, `prisma db pull`, and `prisma generate` +- **`@prisma/client`** - The Prisma Client library for querying your database +- **`@prisma/adapter-pg`** - The [`node-postgres` driver adapter](/orm/overview/databases/postgresql#using-the-node-postgres-driver) that connects Prisma Client to your database (CockroachDB is PostgreSQL-compatible) +- **`dotenv`** - Loads environment variables from your `.env` file + +## 2. Initialize Prisma ORM + +Set up your Prisma ORM project by creating your [Prisma Schema](/orm/prisma-schema) file with the following command: + +```terminal +npx prisma init --datasource-provider cockroachdb --output ../generated/prisma +``` + +This command does a few things: + +- Creates a `prisma/` directory with a `schema.prisma` file containing your database connection configuration +- Creates a `.env` file in the root directory for environment variables +- Creates a `prisma.config.ts` file for Prisma configuration + +The generated `prisma.config.ts` file looks like this: + +```typescript file=prisma.config.ts +import { defineConfig, env } from 'prisma/config' + +export default defineConfig({ + schema: 'prisma/schema.prisma', + migrations: { + path: 'prisma/migrations', + }, + datasource: { + url: env('DATABASE_URL'), + }, +}) +``` + +Add `dotenv` to `prisma.config.ts` so that Prisma can load environment variables from your `.env` file: + +```typescript file=prisma.config.ts +// add-start +import 'dotenv/config' +// add-end +import { defineConfig, env } from 'prisma/config' + +export default defineConfig({ + schema: 'prisma/schema.prisma', + migrations: { + path: 'prisma/migrations', + }, + datasource: { + url: env('DATABASE_URL'), + }, +}) +``` + +The generated schema uses [the ESM-first `prisma-client` generator](/orm/prisma-schema/overview/generators#prisma-client) with a custom output path: + +```prisma file=prisma/schema.prisma +generator client { + provider = "prisma-client" + output = "../generated/prisma" +} + +datasource db { + provider = "cockroachdb" +} +``` + +## 3. Connect your database + +Update the `.env` file with your CockroachDB connection URL: + +```bash file=.env +DATABASE_URL="postgresql://user:password@host:26257/mydb?sslmode=require" +``` + +The [format of the connection URL](/orm/reference/connection-urls) for CockroachDB looks as follows: + +``` +postgresql://USER:PASSWORD@HOST:PORT/DATABASE?sslmode=require +``` + +## 4. Introspect your database + +Run the following command to introspect your existing database: + +```terminal +npx prisma db pull +``` + +This command reads the `DATABASE_URL` environment variable, connects to your database, and introspects the database schema. It then translates the database schema from SQL into a data model in your Prisma schema. + +![Introspect your database with Prisma ORM](/img/getting-started/prisma-db-pull-generate-schema.png) + +After introspection, your Prisma schema will contain models that represent your existing database tables. + +## 5. Baseline your database + +To use Prisma Migrate with your existing database, you need to [baseline your database](/orm/prisma-migrate/getting-started). + +First, create a `migrations` directory: + +```terminal +mkdir -p prisma/migrations/0_init +``` + +Next, generate the migration file with `prisma migrate diff`: + +```terminal +npx prisma migrate diff --from-empty --to-schema prisma/schema.prisma --script > prisma/migrations/0_init/migration.sql +``` + +Review the generated migration file to ensure it matches your database schema. + +Then, mark the migration as applied: + +```terminal +npx prisma migrate resolve --applied 0_init +``` + +You now have a baseline for your current database schema. + +## 6. Generate Prisma ORM types + +Generate Prisma Client based on your introspected schema: + +```terminal +npx prisma generate +``` + +This creates a type-safe Prisma Client tailored to your database schema in the `generated/prisma` directory. + +## 7. Instantiate Prisma Client + +Create a utility file to instantiate Prisma Client. You need to pass an instance of Prisma ORM's driver adapter to the `PrismaClient` constructor: + +```typescript file=lib/prisma.ts +import "dotenv/config"; +import { PrismaPg } from '@prisma/adapter-pg' +import { PrismaClient } from '../generated/prisma/client' + +const connectionString = `${process.env.DATABASE_URL}` + +const adapter = new PrismaPg({ connectionString }) +const prisma = new PrismaClient({ adapter }) + +export { prisma } +``` + +## 8. Query your database + +Now you can use Prisma Client to query your database. Create a `script.ts` file: + +```typescript file=script.ts +import { prisma } from './lib/prisma' + +async function main() { + // Example: Fetch all records from a table + // Replace 'user' with your actual model name + const allUsers = await prisma.user.findMany() + console.log('All users:', JSON.stringify(allUsers, null, 2)) +} + +main() + .then(async () => { + await prisma.$disconnect() + }) + .catch(async (e) => { + console.error(e) + await prisma.$disconnect() + process.exit(1) + }) +``` + +Run the script: + +```terminal +npx tsx script.ts +``` + +## 9. Evolve your schema + +To make changes to your database schema: + +### 9.1. Update your Prisma schema file + +Update your Prisma schema file to reflect the changes you want to make to your database schema. For example, add a new model: + +```prisma file=prisma/schema.prisma +// add-start +model Post { + id Int @id @default(autoincrement()) + title String + content String? + published Boolean @default(false) + authorId Int + author User @relation(fields: [authorId], references: [id]) +} + +model User { + id Int @id @default(autoincrement()) + email String @unique + name String? + posts Post[] +} +// add-end +``` + +### 9.2. Create and apply a migration: + +```terminal +npx prisma migrate dev --name your_migration_name +``` + +This command will: +- Create a new SQL migration file +- Apply the migration to your database +- Regenerate Prisma Client + +## 10. Explore your data with Prisma Studio + + + +## Next steps + + + +## More info + +- [CockroachDB database connector](/orm/overview/databases/cockroachdb) +- [Prisma Config reference](/orm/reference/prisma-config-reference) +- [Database introspection](/orm/prisma-schema/introspection) +- [Prisma Migrate](/orm/prisma-migrate) diff --git a/content/100-getting-started/02-prisma-orm/200-add-to-existing-project/800-mongodb.mdx b/content/100-getting-started/02-prisma-orm/200-add-to-existing-project/800-mongodb.mdx new file mode 100644 index 0000000000..7fc993a4c7 --- /dev/null +++ b/content/100-getting-started/02-prisma-orm/200-add-to-existing-project/800-mongodb.mdx @@ -0,0 +1,308 @@ +--- +title: 'Add Prisma ORM to an existing MongoDB project' +sidebar_title: 'MongoDB' +metaTitle: 'How to add Prisma ORM to an existing project using MongoDB (15 min)' +metaDescription: 'Add Prisma ORM to an existing TypeScript project with MongoDB and learn database introspection and querying.' +sidebar_custom_props: { badge: '15 min' } +--- + +import Prerequisites from '../../_components/_prerequisites.mdx' +import ExploreData from '../../_components/_explore-data.mdx' +import NextSteps from '../../_components/_next-steps.mdx' + +[MongoDB](https://www.mongodb.com/) is a popular document-based NoSQL database known for its flexibility, scalability, and developer-friendly features. In this guide, you will learn how to add Prisma ORM to an existing TypeScript project, connect it to MongoDB, introspect your existing database schema, and start querying with type-safe Prisma Client. + +:::tip + +If you're migrating to Prisma ORM from Mongoose, see our [Migrate from Mongoose guide](/guides/migrate-from-mongoose). + +::: + +## Prerequisites + +In order to successfully complete this guide, you need: + +- [Node.js](https://nodejs.org/en/) installed on your machine (see [system requirements](/orm/reference/system-requirements) for officially supported versions) +- An existing TypeScript project with a `package.json` file +- Access to a MongoDB 4.2+ server with a replica set deployment. We recommend using [MongoDB Atlas](https://www.mongodb.com/cloud/atlas). + +:::warning + +The MongoDB database connector uses transactions to support nested writes. Transactions **requires** a [replica set](https://www.mongodb.com/docs/manual/tutorial/deploy-replica-set/) deployment. The easiest way to deploy a replica set is with [Atlas](https://www.mongodb.com/docs/atlas/getting-started/). It's free to get started. + +::: + +Make sure you have your database [connection URL](/orm/reference/connection-urls) (that includes your authentication credentials) at hand! + +:::note + +If your project contains multiple directories with `package.json` files (e.g., `frontend`, `backend`, etc.), note that Prisma ORM is specifically designed for use in the API/backend layer. To set up Prisma, navigate to the appropriate backend directory containing the relevant `package.json` file and configure Prisma there. + +::: + +## 1. Set up Prisma ORM + +Navigate to your existing project directory and install the required dependencies: + +```terminal +npm install prisma @types/node --save-dev +npm install @prisma/client dotenv +``` + +Here's what each package does: + +- **`prisma`** - The Prisma CLI for running commands like `prisma init`, `prisma db pull`, and `prisma generate` +- **`@prisma/client`** - The Prisma Client library for querying your database +- **`dotenv`** - Loads environment variables from your `.env` file + +:::info + +MongoDB does not require a driver adapter like relational databases. Prisma Client connects directly to MongoDB. + +::: + +## 2. Initialize Prisma ORM + +Set up your Prisma ORM project by creating your [Prisma Schema](/orm/prisma-schema) file with the following command: + +```terminal +npx prisma init --datasource-provider mongodb --output ../generated/prisma +``` + +This command does a few things: + +- Creates a `prisma/` directory with a `schema.prisma` file containing your database connection configuration +- Creates a `.env` file in the root directory for environment variables +- Creates a `prisma.config.ts` file for Prisma configuration + +The generated `prisma.config.ts` file looks like this: + +```typescript file=prisma.config.ts +import { defineConfig, env } from 'prisma/config' + +export default defineConfig({ + schema: 'prisma/schema.prisma', + migrations: { + path: 'prisma/migrations', + }, + engine: "classic", + datasource: { + url: env('DATABASE_URL'), + }, +}) +``` + +Add `dotenv` to `prisma.config.ts` so that Prisma can load environment variables from your `.env` file: + +```typescript file=prisma.config.ts +// add-start +import 'dotenv/config' +// add-end +import { defineConfig, env } from 'prisma/config' + +export default defineConfig({ + schema: 'prisma/schema.prisma', + migrations: { + path: 'prisma/migrations', + }, + engine: "classic", + datasource: { + url: env('DATABASE_URL'), + }, +}) +``` + +The generated schema uses [the ESM-first `prisma-client` generator](/orm/prisma-schema/overview/generators#prisma-client) with a custom output path: + +```prisma file=prisma/schema.prisma +generator client { + provider = "prisma-client" + output = "../generated/prisma" +} + +datasource db { + provider = "mongodb" +} +``` + +## 3. Connect your database + +Update the `.env` file with your MongoDB connection URL: + +```bash file=.env +DATABASE_URL="mongodb+srv://username:password@cluster.mongodb.net/mydb" +``` + +For MongoDB Atlas, the connection URL format is: + +``` +mongodb+srv://USERNAME:PASSWORD@CLUSTER.mongodb.net/DATABASE +``` + +The [format of the connection URL](/orm/reference/connection-urls) for MongoDB looks as follows (the parts spelled all-uppercased are _placeholders_ for your specific connection details): + +``` +mongodb://USERNAME:PASSWORD@HOST:PORT/DATABASE +``` + +Here's a short explanation of each component: + +- **`USERNAME`**: The name of your database user +- **`PASSWORD`**: The password for your database user +- **`HOST`**: The host where a [`mongod`](https://www.mongodb.com/docs/manual/reference/program/mongod/#mongodb-binary-bin.mongod) (or [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos/#mongodb-binary-bin.mongos)) instance is running +- **`PORT`**: The port where your database server is running (typically `27017` for MongoDB) +- **`DATABASE`**: The name of the database + +:::tip + +If you're using MongoDB Atlas, you need to manually append the database name to the connection URL because the environment link from MongoDB Atlas doesn't contain it. + +::: + +### Troubleshooting connection issues + +#### `Error in connector: SCRAM failure: Authentication failed.` + +If you see the `Error in connector: SCRAM failure: Authentication failed.` error message, you can specify the source database for the authentication by [adding](https://github.com/prisma/prisma/discussions/9994#discussioncomment-1562283) `?authSource=admin` to the end of the connection string. + +#### `Raw query failed. Error code 8000 (AtlasError): empty database name not allowed.` + +If you see the `Raw query failed. Code: unknown. Message: Kind: Command failed: Error code 8000 (AtlasError): empty database name not allowed.` error message, be sure to append the database name to the database URL. You can find more info in this [GitHub issue](https://github.com/prisma/docs/issues/5562). + +## 4. Introspect your database + +Run the following command to introspect your existing database: + +```terminal +npx prisma db pull +``` + +This command reads the `DATABASE_URL` environment variable, connects to your database, and introspects the database schema. Prisma ORM introspects a MongoDB schema by sampling the data stored in the database and inferring the schema. + +![Introspect your database with Prisma ORM](/img/getting-started/prisma-db-pull-generate-schema.png) + +After introspection, your Prisma schema will contain models that represent your existing MongoDB collections. + +:::info + +MongoDB introspection works by sampling documents in your collections. You may need to manually add relation fields using the `@relation` attribute to enable relational queries. + +::: + +## 5. Generate Prisma ORM types + +Generate Prisma Client based on your introspected schema: + +```terminal +npx prisma generate +``` + +This creates a type-safe Prisma Client tailored to your database schema in the `generated/prisma` directory. + +## 6. Instantiate Prisma Client + +Create a utility file to instantiate Prisma Client: + +```typescript file=lib/prisma.ts +import "dotenv/config"; +import { PrismaClient } from '../generated/prisma/client' + +const prisma = new PrismaClient() + +export { prisma } +``` + +## 7. Query your database + +Now you can use Prisma Client to query your database. Create a `script.ts` file: + +```typescript file=script.ts +import { prisma } from './lib/prisma' + +async function main() { + // Example: Fetch all records from a collection + // Replace 'user' with your actual model name + const allUsers = await prisma.user.findMany() + console.log('All users:', JSON.stringify(allUsers, null, 2)) +} + +main() + .then(async () => { + await prisma.$disconnect() + }) + .catch(async (e) => { + console.error(e) + await prisma.$disconnect() + process.exit(1) + }) +``` + +Run the script: + +```terminal +npx tsx script.ts +``` + +## 8. Evolve your schema + +MongoDB does not use migrations. To make changes to your database schema: + +### 8.1. Update your Prisma schema file + +Update your Prisma schema file to reflect the changes you want to make to your database schema. For example, add a new model: + +```prisma file=prisma/schema.prisma +// add-start +model Post { + id String @id @default(auto()) @map("_id") @db.ObjectId + title String + content String? + published Boolean @default(false) + authorId String @db.ObjectId + author User @relation(fields: [authorId], references: [id]) +} + +model User { + id String @id @default(auto()) @map("_id") @db.ObjectId + email String @unique + name String? + posts Post[] +} +// add-end +``` + +:::info + +In MongoDB, the `id` field is mapped to `_id` and uses `@db.ObjectId` type. Relations use `String` type with `@db.ObjectId` annotation. + +::: + +### 8.2. Push the changes to your database: + +```terminal +npx prisma db push +``` + +This command will: +- Apply the schema changes to your MongoDB database +- Regenerate Prisma Client + +:::info + +Prisma Migrate is not supported for MongoDB. Use `prisma db push` to sync your schema changes. + +::: + +## 9. Explore your data with Prisma Studio + + + +## Next steps + + + +## More info + +- [MongoDB database connector](/orm/overview/databases/mongodb) +- [Prisma Config reference](/orm/reference/prisma-config-reference) +- [Database introspection](/orm/prisma-schema/introspection) diff --git a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases-node-cockroachdb.mdx b/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases-node-cockroachdb.mdx deleted file mode 100644 index c9b8a135e3..0000000000 --- a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases-node-cockroachdb.mdx +++ /dev/null @@ -1,52 +0,0 @@ ---- -title: 'Relational databases (JavaScript and CockroachDB)' -sidebar_label: 'Relational databases' -metaTitle: 'Start from scratch with Prisma ORM using JavaScript and CockroachDB (15 min)' -metaDescription: 'Learn how to create a new Node.js project from scratch by connecting Prisma ORM to your CockroachDB database and generating a Prisma Client for database access.' -hide_table_of_contents: true -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -sidebar_custom_props: { badge: '15 min' } -sidebar_class_name: hidden-sidebar -pagination_next: getting-started/setup-prisma/start-from-scratch/relational-databases/connect-your-database-node-cockroachdb -slugSwitch: /getting-started/setup-prisma/start-from-scratch/relational-databases- ---- - - - -Learn how to create a new Node.js or TypeScript project from scratch by connecting Prisma ORM to your database and generating a Prisma Client for database access. The following tutorial introduces you to the [Prisma CLI](/orm/tools/prisma-cli), [Prisma Client](/orm/prisma-client), and [Prisma Migrate](/orm/prisma-migrate). - - - -## Prerequisites - -In order to successfully complete this guide, you need: - -- [Node.js](https://nodejs.org/en/) installed on your machine (see [system requirements](/orm/reference/system-requirements) for officially supported versions) -- a [CockroachDB](https://www.cockroachlabs.com/) database server running - -> See [System requirements](/orm/reference/system-requirements) for exact version requirements. - -Make sure you have your database [connection URL](/orm/reference/connection-urls) at hand. If you don't have a database server running and just want to explore Prisma ORM, check out the [Quickstart](/getting-started/quickstart-sqlite). - -## Create project setup - -As a first step, create a project directory and navigate into it: - -```terminal copy -mkdir hello-prisma -cd hello-prisma -``` - -Next, initialize a Node.js project and add the Prisma CLI as a development dependency to it: - -```terminal copy -npm init -y -npm install prisma --save-dev -``` - -This creates a `package.json` with an initial setup for a Node.js app. - -import PrismaInitPartial from './_prisma-init-partial.mdx' - - \ No newline at end of file diff --git a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases-node-mysql.mdx b/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases-node-mysql.mdx deleted file mode 100644 index b0397ccd45..0000000000 --- a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases-node-mysql.mdx +++ /dev/null @@ -1,58 +0,0 @@ ---- -title: 'Relational databases (JavaScript and MySQL)' -sidebar_label: 'Relational databases' -metaTitle: 'Start from scratch with Prisma ORM using JavaScript and MySQL (15 min)' -metaDescription: 'Learn how to create a new Node.js project from scratch by connecting Prisma ORM to your MySQL database and generating a Prisma Client for database access.' -hide_table_of_contents: true -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -sidebar_custom_props: { badge: '15 min' } -sidebar_class_name: hidden-sidebar -pagination_next: getting-started/setup-prisma/start-from-scratch/relational-databases/connect-your-database-node-mysql -slugSwitch: /getting-started/setup-prisma/start-from-scratch/relational-databases- ---- - - - -Learn how to create a new Node.js or TypeScript project from scratch by connecting Prisma ORM to your database and generating a Prisma Client for database access. The following tutorial introduces you to the [Prisma CLI](/orm/tools/prisma-cli), [Prisma Client](/orm/prisma-client), and [Prisma Migrate](/orm/prisma-migrate). - - - -## Prerequisites - -In order to successfully complete this guide, you need: - -- [Node.js](https://nodejs.org/en/) installed on your machine (see [system requirements](/orm/reference/system-requirements) for officially supported versions) -- a [MySQL](https://www.mysql.com/) database server running - -> See [System requirements](/orm/reference/system-requirements) for exact version requirements. - -Make sure you have your database [connection URL](/orm/reference/connection-urls) at hand. If you don't have a database server running and just want to explore Prisma ORM, check out the [Quickstart](/getting-started/quickstart-sqlite). - -## Create project setup - -As a first step, create a project directory and navigate into it: - -```terminal copy -mkdir hello-prisma -cd hello-prisma -``` - -Next, initialize a Node.js project and add the Prisma CLI as a development dependency to it: - -```terminal copy -npm init -y -npm install prisma --save-dev -``` - -This creates a `package.json` with an initial setup for a Node.js app. - -:::info - -See [installation instructions](/orm/tools/prisma-cli#installation) to learn how to install Prisma using a different package manager. - -::: - -import PrismaInitPartial from './_prisma-init-partial.mdx' - - \ No newline at end of file diff --git a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases-node-planetscale.mdx b/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases-node-planetscale.mdx deleted file mode 100644 index ec9ef078fe..0000000000 --- a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases-node-planetscale.mdx +++ /dev/null @@ -1,51 +0,0 @@ ---- -title: 'Relational databases (JavaScript and PlanetScale)' -sidebar_label: 'Relational databases' -metaTitle: 'Start from scratch with Prisma ORM using JavaScript and PlanetScale (15 min)' -metaDescription: 'Learn how to create a new Node.js project from scratch by connecting Prisma ORM to your PlanetScale database and generating a Prisma Client for database access.' -hide_table_of_contents: true -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -sidebar_custom_props: { badge: '15 min' } -sidebar_class_name: hidden-sidebar -pagination_next: getting-started/setup-prisma/start-from-scratch/relational-databases/connect-your-database-node-planetscale -slugSwitch: /getting-started/setup-prisma/start-from-scratch/relational-databases- ---- - - - -Learn how to create a new Node.js or TypeScript project from scratch by connecting Prisma ORM to your database and generating a Prisma Client for database access. The following tutorial introduces you to the [Prisma CLI](/orm/tools/prisma-cli), [Prisma Client](/orm/prisma-client), and [Prisma Migrate](/orm/prisma-migrate). - - - -## Prerequisites - -In order to successfully complete this guide, you need: - -- [Node.js](https://nodejs.org/en/) installed on your machine (see [system requirements](/orm/reference/system-requirements) for officially supported versions) -- a [PlanetScale](https://planetscale.com/) database server running - - - -This tutorial will also assume that you can push to the `main` branch of your database. Do not do this if your `main` branch has been promoted to production. - - - -Next, initialize a Node.js project and add the Prisma CLI as a development dependency to it: - -```terminal copy -npm init -y -npm install prisma --save-dev -``` - -This creates a `package.json` with an initial setup for a Node.js app. - -:::info - -See [installation instructions](/orm/tools/prisma-cli#installation) to learn how to install Prisma using a different package manager. - -::: - -import PrismaInitPartial from './_prisma-init-partial.mdx' - - diff --git a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases-node-postgresql.mdx b/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases-node-postgresql.mdx deleted file mode 100644 index 81fe5d9135..0000000000 --- a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases-node-postgresql.mdx +++ /dev/null @@ -1,58 +0,0 @@ ---- -title: 'Relational databases (JavaScript and PostgreSQL)' -sidebar_label: 'Relational databases' -metaTitle: 'Start from scratch with Prisma ORM using JavaScript and PostgreSQL (15 min)' -metaDescription: 'Learn how to create a new Node.js project from scratch by connecting Prisma ORM to your PostgreSQL database and generating a Prisma Client for database access.' -hide_table_of_contents: true -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -sidebar_custom_props: { badge: '15 min' } -sidebar_class_name: hidden-sidebar -pagination_next: getting-started/setup-prisma/start-from-scratch/relational-databases/connect-your-database-node-postgresql -slugSwitch: /getting-started/setup-prisma/start-from-scratch/relational-databases- ---- - - - -Learn how to create a new Node.js or TypeScript project from scratch by connecting Prisma ORM to your database and generating a Prisma Client for database access. The following tutorial introduces you to the [Prisma CLI](/orm/tools/prisma-cli), [Prisma Client](/orm/prisma-client), and [Prisma Migrate](/orm/prisma-migrate). - - - -## Prerequisites - -In order to successfully complete this guide, you need: - -- [Node.js](https://nodejs.org/en/) installed on your machine (see [system requirements](/orm/reference/system-requirements) for officially supported versions) -- a [PostgreSQL](https://www.postgresql.org/) database server running - -> See [System requirements](/orm/reference/system-requirements) for exact version requirements. - -Make sure you have your database [connection URL](/orm/reference/connection-urls) at hand. If you don't have a database server running and just want to explore Prisma ORM, check out the [Quickstart](/getting-started/quickstart-sqlite). - -## Create project setup - -As a first step, create a project directory and navigate into it: - -```terminal copy -mkdir hello-prisma -cd hello-prisma -``` - -Next, initialize a Node.js project and add the Prisma CLI as a development dependency to it: - -```terminal copy -npm init -y -npm install prisma --save-dev -``` - -This creates a `package.json` with an initial setup for a Node.js app. - -:::info - -See [installation instructions](/orm/tools/prisma-cli#installation) to learn how to install Prisma using a different package manager. - -::: - -import PrismaInitPartial from './_prisma-init-partial.mdx' - - diff --git a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases-node-sqlserver.mdx b/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases-node-sqlserver.mdx deleted file mode 100644 index 92f8f25f9a..0000000000 --- a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases-node-sqlserver.mdx +++ /dev/null @@ -1,61 +0,0 @@ ---- -title: 'Relational databases (JavaScript and SQL Server)' -sidebar_label: 'Relational databases' -metaTitle: 'Start from scratch with Prisma ORM using JavaScript and SQL Server (15 min)' -metaDescription: 'Learn how to create a new Node.js project from scratch by connecting Prisma ORM to your SQL Server database and generating a Prisma Client for database access.' -hide_table_of_contents: true -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -sidebar_custom_props: { badge: '15 min' } -sidebar_class_name: hidden-sidebar -pagination_next: getting-started/setup-prisma/start-from-scratch/relational-databases/connect-your-database-node-sqlserver -slugSwitch: /getting-started/setup-prisma/start-from-scratch/relational-databases- ---- - - - -Learn how to create a new Node.js or TypeScript project from scratch by connecting Prisma ORM to your database and generating a Prisma Client for database access. The following tutorial introduces you to the [Prisma CLI](/orm/tools/prisma-cli), [Prisma Client](/orm/prisma-client), and [Prisma Migrate](/orm/prisma-migrate). - - - -## Prerequisites - -In order to successfully complete this guide, you need: - -- [Node.js](https://nodejs.org/en/) installed on your machine (see [system requirements](/orm/reference/system-requirements) for officially supported versions) -- A [Microsoft SQL Server](https://learn.microsoft.com/en-us/sql/?view=sql-server-ver16) database - - [Microsoft SQL Server on Linux for Docker](/orm/overview/databases/sql-server/sql-server-docker) - - [Microsoft SQL Server on Windows (local)](/orm/overview/databases/sql-server/sql-server-local) - - -> See [System requirements](/orm/reference/system-requirements) for exact version requirements. - -Make sure you have your database [connection URL](/orm/reference/connection-urls) at hand. If you don't have a database server running and just want to explore Prisma ORM, check out the [Quickstart](/getting-started/quickstart-sqlite). - -## Create project setup - -As a first step, create a project directory and navigate into it: - -```terminal copy -mkdir hello-prisma -cd hello-prisma -``` - -Next, initialize a Node.js project and add the Prisma CLI as a development dependency to it: - -```terminal copy -npm init -y -npm install prisma --save-dev -``` - -This creates a `package.json` with an initial setup for a Node.js app. - -:::info - -See [installation instructions](/orm/tools/prisma-cli#installation) to learn how to install Prisma using a different package manager. - -::: - -import PrismaInitPartial from './_prisma-init-partial.mdx' - - diff --git a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases-typescript-cockroachdb.mdx b/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases-typescript-cockroachdb.mdx deleted file mode 100644 index ca1f6a19f2..0000000000 --- a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases-typescript-cockroachdb.mdx +++ /dev/null @@ -1,64 +0,0 @@ ---- -title: 'Relational databases (TypeScript and CockroachDB)' -sidebar_label: 'Relational databases' -metaTitle: 'Start from scratch with Prisma ORM using TypeScript and CockroachDB (15 min)' -metaDescription: 'Learn how to create a new TypeScript project from scratch by connecting Prisma ORM to your CockroachDB database and generating a Prisma Client for database access.' -hide_table_of_contents: true -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb', 'prismaPostgres'] -sidebar_custom_props: { badge: '15 min' } -sidebar_class_name: hidden-sidebar -pagination_next: getting-started/setup-prisma/start-from-scratch/relational-databases/connect-your-database-typescript-cockroachdb -slugSwitch: /getting-started/setup-prisma/start-from-scratch/relational-databases- ---- - - - -Learn how to create a new Node.js or TypeScript project from scratch by connecting Prisma ORM to your database and generating a Prisma Client for database access. The following tutorial introduces you to the [Prisma CLI](/orm/tools/prisma-cli), [Prisma Client](/orm/prisma-client), and [Prisma Migrate](/orm/prisma-migrate). - - - -## Prerequisites - -In order to successfully complete this guide, you need: - -- [Node.js](https://nodejs.org/en/) installed on your machine (see [system requirements](/orm/reference/system-requirements) for officially supported versions) -- a [CockroachDB](https://www.cockroachlabs.com/) database server running - -> See [System requirements](/orm/reference/system-requirements) for exact version requirements. - -Make sure you have your database [connection URL](/orm/reference/connection-urls) at hand. If you don't have a database server running and just want to explore Prisma ORM, check out the [Quickstart](/getting-started/quickstart-sqlite). - -## Create project setup - -As a first step, create a project directory and navigate into it: - -```terminal copy -mkdir hello-prisma -cd hello-prisma -``` - -Next, initialize a TypeScript project and add the Prisma CLI as a development dependency to it: - -```terminal copy -npm init -y -npm install prisma typescript tsx @types/node --save-dev -``` - -This creates a `package.json` with an initial setup for your TypeScript app. - -Next, initialize TypeScript: - -```terminal copy -npx tsc --init -``` - -:::info - -See [installation instructions](/orm/tools/prisma-cli#installation) to learn how to install Prisma using a different package manager. - -::: - -import PrismaInitPartial from './_prisma-init-partial.mdx' - - diff --git a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases-typescript-mysql.mdx b/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases-typescript-mysql.mdx deleted file mode 100644 index 1c61373522..0000000000 --- a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases-typescript-mysql.mdx +++ /dev/null @@ -1,64 +0,0 @@ ---- -title: 'Relational databases (TypeScript and MySQL)' -sidebar_label: 'Relational databases' -metaTitle: 'Start from scratch with Prisma ORM using TypeScript and MySQL (15 min)' -metaDescription: 'Learn how to create a new TypeScript project from scratch by connecting Prisma ORM to your MySQL database and generating a Prisma Client for database access.' -hide_table_of_contents: true -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb', 'prismaPostgres'] -sidebar_custom_props: { badge: '15 min' } -sidebar_class_name: hidden-sidebar -pagination_next: getting-started/setup-prisma/start-from-scratch/relational-databases/connect-your-database-typescript-mysql -slugSwitch: /getting-started/setup-prisma/start-from-scratch/relational-databases- ---- - - - -Learn how to create a new Node.js or TypeScript project from scratch by connecting Prisma ORM to your database and generating a Prisma Client for database access. The following tutorial introduces you to the [Prisma CLI](/orm/tools/prisma-cli), [Prisma Client](/orm/prisma-client), and [Prisma Migrate](/orm/prisma-migrate). - - - -## Prerequisites - -In order to successfully complete this guide, you need: - -- [Node.js](https://nodejs.org/en/) installed on your machine (see [system requirements](/orm/reference/system-requirements) for officially supported versions) -- a [MySQL](https://www.mysql.com/) database server running - -> See [System requirements](/orm/reference/system-requirements) for exact version requirements. - -Make sure you have your database [connection URL](/orm/reference/connection-urls) at hand. If you don't have a database server running and just want to explore Prisma ORM, check out the [Quickstart](/getting-started/quickstart-sqlite). - -## Create project setup - -As a first step, create a project directory and navigate into it: - -```terminal copy -mkdir hello-prisma -cd hello-prisma -``` - -Next, initialize a TypeScript project and add the Prisma CLI as a development dependency to it: - -```terminal copy -npm init -y -npm install prisma typescript tsx @types/node --save-dev -``` - -This creates a `package.json` with an initial setup for your TypeScript app. - -Next, initialize TypeScript: - -```terminal copy -npx tsc --init -``` - -:::info - -See [installation instructions](/orm/tools/prisma-cli#installation) to learn how to install Prisma using a different package manager. - -::: - -import PrismaInitPartial from './_prisma-init-partial.mdx' - - diff --git a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases-typescript-planetscale.mdx b/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases-typescript-planetscale.mdx deleted file mode 100644 index 5243330350..0000000000 --- a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases-typescript-planetscale.mdx +++ /dev/null @@ -1,70 +0,0 @@ ---- -title: 'Relational databases (TypeScript and PlanetScale)' -sidebar_label: 'Relational databases' -metaTitle: 'Start from scratch with Prisma ORM using TypeScript and PlanetScale (15 min)' -metaDescription: 'Learn how to create a new TypeScript project from scratch by connecting Prisma ORM to your PlanetScale database and generating a Prisma Client for database access.' -hide_table_of_contents: true -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb', 'prismaPostgres'] -sidebar_custom_props: { badge: '15 min' } -sidebar_class_name: hidden-sidebar -pagination_next: getting-started/setup-prisma/start-from-scratch/relational-databases/connect-your-database-typescript-planetscale -slugSwitch: /getting-started/setup-prisma/start-from-scratch/relational-databases- ---- - - - -Learn how to create a new Node.js or TypeScript project from scratch by connecting Prisma ORM to your database and generating a Prisma Client for database access. The following tutorial introduces you to the [Prisma CLI](/orm/tools/prisma-cli), [Prisma Client](/orm/prisma-client), and [Prisma Migrate](/orm/prisma-migrate). - - - -## Prerequisites - -In order to successfully complete this guide, you need: - -- [Node.js](https://nodejs.org/en/) installed on your machine (see [system requirements](/orm/reference/system-requirements) for officially supported versions) -- a [PlanetScale](https://planetscale.com/) database server running - - - -This tutorial will also assume that you can push to the `main` branch of your database. Do not do this if your `main` branch has been promoted to production. - - - -> See [System requirements](/orm/reference/system-requirements) for exact version requirements. - -Make sure you have your database [connection URL](/orm/reference/connection-urls) at hand. If you don't have a database server running and just want to explore Prisma ORM, check out the [Quickstart](/getting-started/quickstart-sqlite). - -## Create project setup - -As a first step, create a project directory and navigate into it: - -```terminal copy -mkdir hello-prisma -cd hello-prisma -``` - -Next, initialize a TypeScript project and add the Prisma CLI as a development dependency to it: - -```terminal copy -npm init -y -npm install prisma typescript tsx @types/node --save-dev -``` - -This creates a `package.json` with an initial setup for your TypeScript app. - -Next, initialize TypeScript: - -```terminal copy -npx tsc --init -``` - -:::info - -See [installation instructions](/orm/tools/prisma-cli#installation) to learn how to install Prisma using a different package manager. - -::: - -import PrismaInitPartial from './_prisma-init-partial.mdx' - - diff --git a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases-typescript-postgresql.mdx b/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases-typescript-postgresql.mdx deleted file mode 100644 index 18e56a42b5..0000000000 --- a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases-typescript-postgresql.mdx +++ /dev/null @@ -1,59 +0,0 @@ ---- -title: 'Relational databases (TypeScript and PostgreSQL)' -sidebar_label: 'Relational databases' -metaTitle: 'Start from scratch with Prisma ORM using TypeScript and PostgreSQL (15 min)' -metaDescription: 'Learn how to create a new TypeScript project from scratch by connecting Prisma ORM to your PostgreSQL database and generating a Prisma Client for database access.' -hide_table_of_contents: true -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb', 'prismaPostgres'] -sidebar_custom_props: { badge: '15 min' } -pagination_next: getting-started/setup-prisma/start-from-scratch/relational-databases/connect-your-database-typescript-postgresql -slugSwitch: /getting-started/setup-prisma/start-from-scratch/relational-databases- ---- - -Learn how to create a new Node.js or TypeScript project from scratch by connecting Prisma ORM to your database and generating a Prisma Client for database access. The following tutorial introduces you to the [Prisma CLI](/orm/tools/prisma-cli), [Prisma Client](/orm/prisma-client), and [Prisma Migrate](/orm/prisma-migrate). - -## Prerequisites - -In order to successfully complete this guide, you need: - -- [Node.js](https://nodejs.org/en/) installed on your machine (see [system requirements](/orm/reference/system-requirements) for officially supported versions) -- a [PostgreSQL](https://www.postgresql.org/) database server running - -> See [System requirements](/orm/reference/system-requirements) for exact version requirements. - -Make sure you have your database [connection URL](/orm/reference/connection-urls) at hand. If you don't have a database server running and just want to explore Prisma ORM, check out the [Quickstart](/getting-started/quickstart-sqlite). - -## Create project setup - -As a first step, create a project directory and navigate into it: - -```terminal copy -mkdir hello-prisma -cd hello-prisma -``` - -Next, initialize a TypeScript project and add the Prisma CLI as a development dependency to it: - -```terminal copy -npm init -y -npm install prisma typescript tsx @types/node --save-dev -``` - -This creates a `package.json` with an initial setup for your TypeScript app. - -Next, initialize TypeScript: - -```terminal copy -npx tsc --init -``` - -:::info - -See [installation instructions](/orm/tools/prisma-cli#installation) to learn how to install Prisma using a different package manager. - -::: - -import PrismaInitPartial from './_prisma-init-partial.mdx' - - diff --git a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases-typescript-prismaPostgres.mdx b/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases-typescript-prismaPostgres.mdx deleted file mode 100644 index ed8342b018..0000000000 --- a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases-typescript-prismaPostgres.mdx +++ /dev/null @@ -1,70 +0,0 @@ ---- -title: 'Relational databases (TypeScript and Prisma Postgres)' -sidebar_label: 'Relational databases' -metaTitle: 'Start from scratch with Prisma ORM using TypeScript and Prisma Postgres (15 min)' -metaDescription: 'Learn how to create a new TypeScript project from scratch by connecting Prisma ORM to your Prisma Postgres database and generating a Prisma Client for database access.' -hide_table_of_contents: true -langSwitcher: ['typescript'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb', 'prismaPostgres'] -sidebar_custom_props: { badge: '15 min' } -sidebar_class_name: hidden-sidebar -pagination_next: getting-started/setup-prisma/start-from-scratch/relational-databases/connect-your-database-typescript-prismaPostgres -slugSwitch: /getting-started/setup-prisma/start-from-scratch/relational-databases- ---- - -Learn how to create a new TypeScript project with a Prisma Postgres database from scratch. This tutorial introduces you to the [Prisma CLI](/orm/tools/prisma-cli), [Prisma Client](/orm/prisma-client), and [Prisma Migrate](/orm/prisma-migrate) and covers the following workflows: - -- Creating a TypeScript project on your local machine from scratch -- Creating a [Prisma Postgres](https://www.prisma.io/postgres?utm_source=docs) database -- Schema migrations and queries (via [Prisma ORM](https://www.prisma.io/orm)) -- Connection pooling and caching (via [Prisma Accelerate](https://www.prisma.io/accelerate)) - -## Prerequisites - -To successfully complete this tutorial, you need: -- a [Prisma Data Platform](https://console.prisma.io/) (PDP) account -- [Node.js](https://nodejs.org/en/) installed on your machine (see [system requirements](/orm/reference/system-requirements) for officially supported versions) (see [system requirements](/orm/reference/system-requirements) for officially supported versions) - -## Create project setup - -Create a project directory and navigate into it: - -```terminal copy -mkdir hello-prisma -cd hello-prisma -``` - -Next, initialize a TypeScript project and add the Prisma CLI as a development dependency to it: - -```terminal copy -npm init -y -npm install prisma typescript tsx @types/node --save-dev -``` - -This creates a `package.json` with an initial setup for your TypeScript app. - -Next, initialize TypeScript: - -```terminal copy -npx tsc --init -``` - -You can now invoke the Prisma CLI by prefixing it with `npx`: - -```terminal -npx prisma -``` - -Next, set up your Prisma ORM project by creating your [Prisma Schema](/orm/prisma-schema) file with the following command: - -```terminal copy -npx prisma init --db --output ../generated/prisma -``` - -This command does a few things: - -- Creates a new directory called `prisma` that contains a file called `schema.prisma`, which contains the Prisma Schema with your database connection variable and schema models. -- Sets the `output` to a custom location. -- Creates a [`.env`](/orm/more/development-environment/environment-variables) file in the root directory of the project, which is used for defining environment variables (such as your database connection and API keys). - -In the next section, you'll learn how to connect your Prisma Postgres database to the project you just created on your file system. \ No newline at end of file diff --git a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases-typescript-sqlserver.mdx b/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases-typescript-sqlserver.mdx deleted file mode 100644 index 2459fa217c..0000000000 --- a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases-typescript-sqlserver.mdx +++ /dev/null @@ -1,66 +0,0 @@ ---- -title: 'Relational databases (TypeScript and SQL Server)' -sidebar_label: 'Relational databases' -metaTitle: 'Start from scratch with Prisma ORM using TypeScript and SQL Server (15 min)' -metaDescription: 'Learn how to create a new TypeScript project from scratch by connecting Prisma ORM to your SQL Server database and generating a Prisma Client for database access.' -hide_table_of_contents: true -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb', 'prismaPostgres'] -sidebar_custom_props: { badge: '15 min' } -sidebar_class_name: hidden-sidebar -pagination_next: getting-started/setup-prisma/start-from-scratch/relational-databases/connect-your-database-typescript-sqlserver -slugSwitch: /getting-started/setup-prisma/start-from-scratch/relational-databases- ---- - - - -Learn how to create a new Node.js or TypeScript project from scratch by connecting Prisma ORM to your database and generating a Prisma Client for database access. The following tutorial introduces you to the [Prisma CLI](/orm/tools/prisma-cli), [Prisma Client](/orm/prisma-client), and [Prisma Migrate](/orm/prisma-migrate). - - - -## Prerequisites - -In order to successfully complete this guide, you need: - -- [Node.js](https://nodejs.org/en/) installed on your machine (see [system requirements](/orm/reference/system-requirements) for officially supported versions) -- A [Microsoft SQL Server](https://learn.microsoft.com/en-us/sql/?view=sql-server-ver16) database - - [Microsoft SQL Server on Linux for Docker](/orm/overview/databases/sql-server/sql-server-docker) - - [Microsoft SQL Server on Windows (local)](/orm/overview/databases/sql-server/sql-server-local) - -> See [System requirements](/orm/reference/system-requirements) for exact version requirements. - -Make sure you have your database [connection URL](/orm/reference/connection-urls) at hand. If you don't have a database server running and just want to explore Prisma ORM, check out the [Quickstart](/getting-started/quickstart-sqlite). - -## Create project setup - -As a first step, create a project directory and navigate into it: - -```terminal copy -mkdir hello-prisma -cd hello-prisma -``` - -Next, initialize a TypeScript project and add the Prisma CLI as a development dependency to it: - -```terminal copy -npm init -y -npm install prisma typescript tsx @types/node --save-dev -``` - -This creates a `package.json` with an initial setup for your TypeScript app. - -Next, initialize TypeScript: - -```terminal copy -npx tsc --init -``` - -:::info - -See [installation instructions](/orm/tools/prisma-cli#installation) to learn how to install Prisma using a different package manager. - -::: - -import PrismaInitPartial from './_prisma-init-partial.mdx' - - diff --git a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/100-connect-your-database-node-cockroachdb.mdx b/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/100-connect-your-database-node-cockroachdb.mdx deleted file mode 100644 index de67fb16a7..0000000000 --- a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/100-connect-your-database-node-cockroachdb.mdx +++ /dev/null @@ -1,54 +0,0 @@ ---- -title: 'Connect your database using JavaScript and CockroachDB' -sidebar_label: 'Connect your database' -metaTitle: 'Connect your database using JavaScript and CockroachDB' -metaDescription: 'Connect your database to your project using JavaScript and CockroachDB' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -hide_table_of_contents: true -sidebar_class_name: hidden-sidebar -pagination_prev: getting-started/setup-prisma/start-from-scratch/relational-databases-node-cockroachdb -pagination_next: getting-started/setup-prisma/start-from-scratch/relational-databases/using-prisma-migrate-node-cockroachdb -slugSwitch: /getting-started/setup-prisma/start-from-scratch/relational-databases/connect-your-database- ---- - -To connect your database, you need to set the `url` field of the `datasource` block in your Prisma schema to your database [connection URL](/orm/reference/connection-urls): - -```prisma file=prisma/schema.prisma showLineNumbers -datasource db { - provider = "postgresql" - url = env("DATABASE_URL") -} -``` - -The `url` is [set via an environment variable](/orm/more/development-environment/environment-variables) which is defined in `.env`. You now need to adjust the connection URL to point to your own database. - -The [format of the connection URL](/orm/reference/connection-urls) for your database depends on the database you use. CockroachDB uses the PostgreSQL connection URL format, which has the following structure (the parts spelled all-uppercased are _placeholders_ for your specific connection details): - -```no-lines -postgresql://USER:PASSWORD@HOST:PORT/DATABASE?PARAMETERS -``` - -Here's a short explanation of each component: - -- `USER`: The name of your database user -- `PASSWORD`: The password for your database user -- `PORT`: The port where your database server is running. The default for CockroachDB is `26257`. -- `DATABASE`: The name of the database -- `PARAMETERS`: Any additional connection parameters. See the CockroachDB documentation [here](https://www.cockroachlabs.com/docs/stable/connection-parameters.html#additional-connection-parameters). - -For a [CockroachDB Serverless](https://www.cockroachlabs.com/docs/cockroachcloud/quickstart.html) or [Cockroach Dedicated](https://www.cockroachlabs.com/docs/cockroachcloud/quickstart-trial-cluster) database hosted on [CockroachDB Cloud](https://www.cockroachlabs.com/docs/cockroachcloud/quickstart/), the [connection URL](/orm/reference/connection-urls) looks similar to this: - -```bash file=.env -DATABASE_URL="postgresql://:@..cockroachlabs.cloud:26257/defaultdb?sslmode=verify-full&sslrootcert=$HOME/.postgresql/root.crt&options=--" -``` - -To find your connection string on CockroachDB Cloud, click the 'Connect' button on the overview page for your database cluster, and select the 'Connection string' tab. - -For a [CockroachDB database hosted locally](https://www.cockroachlabs.com/docs/stable/secure-a-cluster.html), the [connection URL](/orm/reference/connection-urls) looks similar to this: - -```bash file=.env -DATABASE_URL="postgresql://root@localhost:26257?sslmode=disable" -``` - -Your connection string is displayed as part of the welcome text when starting CockroachDB from the command line. diff --git a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/100-connect-your-database-node-mysql.mdx b/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/100-connect-your-database-node-mysql.mdx deleted file mode 100644 index 4a01cb0314..0000000000 --- a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/100-connect-your-database-node-mysql.mdx +++ /dev/null @@ -1,61 +0,0 @@ ---- -title: 'Connect your database using JavaScript and MySQL' -sidebar_label: 'Connect your database' -metaTitle: 'Connect your database using JavaScript and MySQL' -metaDescription: 'Connect your database to your project using JavaScript and MySQL' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -sidebar_class_name: hidden-sidebar -hide_table_of_contents: true -pagination_prev: getting-started/setup-prisma/start-from-scratch/relational-databases-node-mysql -pagination_next: getting-started/setup-prisma/start-from-scratch/relational-databases/using-prisma-migrate-node-mysql -slugSwitch: /getting-started/setup-prisma/start-from-scratch/relational-databases/connect-your-database- ---- - -To connect your database, you need to set the `url` field of the `datasource` block in your Prisma schema to your database [connection URL](/orm/reference/connection-urls): - -```prisma file=prisma/schema.prisma showLineNumbers -datasource db { - provider = "mysql" - url = env("DATABASE_URL") -} -``` - -In this case, the `url` is [set via an environment variable](/orm/prisma-schema/overview#accessing-environment-variables-from-the-schema) which is defined in `.env`: - -```bash file=.env -DATABASE_URL="mysql://johndoe:randompassword@localhost:3306/mydb" -``` - - - -We recommend adding `.env` to your `.gitignore` file to prevent committing your environment variables. - - - -You now need to adjust the connection URL to point to your own database. - -The [format of the connection URL](/orm/reference/connection-urls) for your database typically depends on the database you use. For MySQL, it looks as follows (the parts spelled all-uppercased are _placeholders_ for your specific connection details): - -```no-lines -mysql://USER:PASSWORD@HOST:PORT/DATABASE -``` - -Here's a short explanation of each component: - -- `USER`: The name of your database user -- `PASSWORD`: The password for your database user -- `PORT`: The port where your database server is running (typically `3306` for MySQL) -- `DATABASE`: The name of the [database](https://dev.mysql.com/doc/refman/8.0/en/creating-database.html) - -As an example, for a MySQL database hosted on AWS RDS, the [connection URL](/orm/reference/connection-urls) might look similar to this: - -```bash file=.env -DATABASE_URL="mysql://johndoe:XXX@mysql–instance1.123456789012.us-east-1.rds.amazonaws.com:3306/mydb" -``` - -When running MySQL locally, your connection URL typically looks similar to this: - -```bash file=.env -DATABASE_URL="mysql://root:randompassword@localhost:3306/mydb" -``` diff --git a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/100-connect-your-database-node-planetscale.mdx b/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/100-connect-your-database-node-planetscale.mdx deleted file mode 100644 index 85aa2f3447..0000000000 --- a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/100-connect-your-database-node-planetscale.mdx +++ /dev/null @@ -1,89 +0,0 @@ ---- -title: 'Connect your database using JavaScript and PlanetScale' -sidebar_label: 'Connect your database' -metaTitle: 'Connect your database using JavaScript and PlanetScale' -metaDescription: 'Connect your database to your project using JavaScript and PlanetScale' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -sidebar_class_name: hidden-sidebar -hide_table_of_contents: true -pagination_prev: getting-started/setup-prisma/start-from-scratch/relational-databases-node-planetscale -pagination_next: getting-started/setup-prisma/start-from-scratch/relational-databases/using-prisma-migrate-node-planetscale -slugSwitch: /getting-started/setup-prisma/start-from-scratch/relational-databases/connect-your-database- ---- - -To connect your database, you need to set the `url` field of the `datasource` block in your Prisma schema to your database [connection URL](/orm/reference/connection-urls): - -```prisma file=prisma/schema.prisma showLineNumbers -datasource db { - provider = "postgresql" - url = env("DATABASE_URL") -} -``` - -You will also need to set the relation mode type to `prisma` in order to [emulate foreign key constraints](/orm/overview/databases/planetscale#option-1-emulate-relations-in-prisma-client) in the `datasource` block: - -```prisma file=schema.prisma highlight=4;add showLineNumbers -datasource db { - provider = "mysql" - url = env("DATABASE_URL") - //add-next-line - relationMode = "prisma" -} -``` - -> **Note**: Since February 2024, you can alternatively [use foreign key constraints on a database-level in PlanetScale](/orm/overview/databases/planetscale#option-2-enable-foreign-key-constraints-in-the-planetscale-database-settings), which omits the need for setting `relationMode = "prisma"`. - -The `url` is [set via an environment variable](/orm/prisma-schema/overview#accessing-environment-variables-from-the-schema) which is defined in `.env`: - -```bash file=.env -DATABASE_URL="mysql://janedoe:mypassword@server.us-east-2.psdb.cloud/mydb?sslaccept=strict" -``` - -You now need to adjust the connection URL to point to your own database. - -The [format of the connection URL](/orm/reference/connection-urls) for your database typically depends on the database you use. PlanetScale uses the MySQL connection URL format, which has the following structure (the parts spelled all-uppercased are _placeholders_ for your specific connection details): - -```no-lines -mysql://USER:PASSWORD@HOST:PORT/DATABASE -``` - -Here's a short explanation of each component: - -- `USER`: The name of your database user -- `PASSWORD`: The password for your database user -- `PORT`: The port where your database server is running (typically `3306` for MySQL) -- `DATABASE`: The name of the [database](https://dev.mysql.com/doc/refman/8.0/en/creating-database.html) - -For a database hosted with PlanetScale, the [connection URL](/orm/reference/connection-urls) looks similar to this: - -```bash file=.env -DATABASE_URL="mysql://myusername:mypassword@server.us-east-2.psdb.cloud/mydb?sslaccept=strict" -``` - -The connection URL for a given database branch can be found from your PlanetScale account by going to the overview page for the branch and selecting the 'Connect' dropdown. In the 'Passwords' section, generate a new password and select 'Prisma' to get the Prisma format for the connection URL. - -
-Alternative method: connecting using the PlanetScale CLI - -Alternatively, you can connect to your PlanetScale database server using the [PlanetScale CLI](https://planetscale.com/docs/concepts/planetscale-environment-setup), and use a local connection URL. In this case the connection URL will look like this: - -```bash file=.env -DATABASE_URL="mysql://root@localhost:PORT/mydb" -``` - - - -We recommend adding `.env` to your `.gitignore` file to prevent committing your environment variables. - - - -To connect to your branch, use the following command: - -```terminal -pscale connect prisma-test branchname --port PORT -``` - -The `--port` flag can be omitted if you are using the default port `3306`. - -
diff --git a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/100-connect-your-database-node-postgresql.mdx b/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/100-connect-your-database-node-postgresql.mdx deleted file mode 100644 index 0ca802e8ae..0000000000 --- a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/100-connect-your-database-node-postgresql.mdx +++ /dev/null @@ -1,65 +0,0 @@ ---- -title: 'Connect your database using JavaScript and PostgreSQL' -sidebar_label: 'Connect your database' -metaTitle: 'Connect your database using JavaScript and PostgreSQL' -metaDescription: 'Connect your database to your project using JavaScript and PostgreSQL' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -sidebar_class_name: hidden-sidebar -hide_table_of_contents: true -pagination_prev: getting-started/setup-prisma/start-from-scratch/relational-databases-node-postgresql -pagination_next: getting-started/setup-prisma/start-from-scratch/relational-databases/using-prisma-migrate-node-postgresql -slugSwitch: /getting-started/setup-prisma/start-from-scratch/relational-databases/connect-your-database- ---- - -To connect your database, you need to set the `url` field of the `datasource` block in your Prisma schema to your database [connection URL](/orm/reference/connection-urls): - -```prisma file=prisma/schema.prisma showLineNumbers -datasource db { - provider = "postgresql" - url = env("DATABASE_URL") -} -``` - -In this case, the `url` is [set via an environment variable](/orm/more/development-environment/environment-variables) which is defined in `.env`: - -```bash file=.env -DATABASE_URL="postgresql://johndoe:randompassword@localhost:5432/mydb?schema=public" -``` - - - -We recommend adding `.env` to your `.gitignore` file to prevent committing your environment variables. - - - -You now need to adjust the connection URL to point to your own database. - -The [format of the connection URL](/orm/reference/connection-urls) for your database depends on the database you use. For PostgreSQL, it looks as follows (the parts spelled all-uppercased are _placeholders_ for your specific connection details): - -```no-lines -postgresql://USER:PASSWORD@HOST:PORT/DATABASE?schema=SCHEMA -``` - -Here's a short explanation of each component: - -- `USER`: The name of your database user -- `PASSWORD`: The password for your database user -- `HOST`: The name of your host name (for the local environment, it is `localhost`) -- `PORT`: The port where your database server is running (typically `5432` for PostgreSQL) -- `DATABASE`: The name of the [database](https://www.postgresql.org/docs/12/manage-ag-overview.html) -- `SCHEMA`: The name of the [schema](https://www.postgresql.org/docs/12/ddl-schemas.html) inside the database - -If you're unsure what to provide for the `schema` parameter for a PostgreSQL connection URL, you can probably omit it. In that case, the default schema name `public` will be used. - -As an example, for a PostgreSQL database hosted on Heroku, the [connection URL](/orm/reference/connection-urls) might look similar to this: - -```bash file=.env -DATABASE_URL="postgresql://opnmyfngbknppm:XXX@ec2-46-137-91-216.eu-west-1.compute.amazonaws.com:5432/d50rgmkqi2ipus?schema=hello-prisma" -``` - -When running PostgreSQL locally on macOS, your user and password as well as the database name _typically_ correspond to the current _user_ of your OS, e.g. assuming the user is called `janedoe`: - -```bash file=.env -DATABASE_URL="postgresql://janedoe:janedoe@localhost:5432/janedoe?schema=hello-prisma" -``` diff --git a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/100-connect-your-database-node-sqlserver.mdx b/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/100-connect-your-database-node-sqlserver.mdx deleted file mode 100644 index 56115cd142..0000000000 --- a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/100-connect-your-database-node-sqlserver.mdx +++ /dev/null @@ -1,40 +0,0 @@ ---- -title: 'Connect your database using JavaScript and SQL Server' -sidebar_label: 'Connect your database' -metaTitle: 'Connect your database using JavaScript and SQL Server' -metaDescription: 'Connect your database to your project using JavaScript and SQL Server' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -sidebar_class_name: hidden-sidebar -hide_table_of_contents: true -pagination_prev: getting-started/setup-prisma/start-from-scratch/relational-databases-node-sqlserver -pagination_next: getting-started/setup-prisma/start-from-scratch/relational-databases/using-prisma-migrate-node-sqlserver -slugSwitch: /getting-started/setup-prisma/start-from-scratch/relational-databases/connect-your-database- ---- - -To connect your database, you need to set the `url` field of the `datasource` block in your Prisma schema to your database [connection URL](/orm/reference/connection-urls): -```prisma file=prisma/schema.prisma showLineNumbers -datasource db { - provider = "sqlserver" - url = env("DATABASE_URL") -} -``` - -In this case, the `url` is [set via an environment variable](/orm/prisma-schema/overview#accessing-environment-variables-from-the-schema) which is defined in `.env`: - -The following example connection URL [uses SQL authentication](/orm/overview/databases/sql-server), but there are [other ways to format your connection URL](/orm/overview/databases/sql-server) - -```bash file=.env - DATABASE_URL="sqlserver://localhost:1433;database=mydb;user=sa;password=r@ndomP@$$w0rd;trustServerCertificate=true" -``` - - - -We recommend adding `.env` to your `.gitignore` file to prevent committing your environment variables. - - - -Adjust the connection URL to match your setup - see [Microsoft SQL Server connection URL](/orm/overview/databases/sql-server) for more information. - -> Make sure TCP/IP connections are enabled via [SQL Server Configuration Manager](https://learn.microsoft.com/en-us/sql/relational-databases/sql-server-configuration-manager?view=sql-server-ver16&viewFallbackFrom=sql-server-ver16) to avoid `No connection could be made because the target machine actively refused it. (os error 10061)` - diff --git a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/100-connect-your-database-typescript-cockroachdb.mdx b/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/100-connect-your-database-typescript-cockroachdb.mdx deleted file mode 100644 index f8f76a1f3d..0000000000 --- a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/100-connect-your-database-typescript-cockroachdb.mdx +++ /dev/null @@ -1,54 +0,0 @@ ---- -title: 'Connect your database using TypeScript and CockroachDB' -sidebar_label: 'Connect your database' -metaTitle: 'Connect your database using TypeScript and CockroachDB' -metaDescription: 'Connect your database to your project using TypeScript and CockroachDB' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb', 'prismaPostgres'] -sidebar_class_name: 'hidden-sidebar tech-switch' -hide_table_of_contents: true -pagination_prev: getting-started/setup-prisma/start-from-scratch/relational-databases-typescript-cockroachdb -pagination_next: getting-started/setup-prisma/start-from-scratch/relational-databases/using-prisma-migrate-typescript-cockroachdb -slugSwitch: /getting-started/setup-prisma/start-from-scratch/relational-databases/connect-your-database- ---- - -To connect your database, you need to set the `url` field of the `datasource` block in your Prisma schema to your database [connection URL](/orm/reference/connection-urls): - -```prisma file=prisma/schema.prisma showLineNumbers -datasource db { - provider = "postgresql" - url = env("DATABASE_URL") -} -``` - -The `url` is [set via an environment variable](/orm/more/development-environment/environment-variables) which is defined in `.env`. You now need to adjust the connection URL to point to your own database. - -The [format of the connection URL](/orm/reference/connection-urls) for your database depends on the database you use. CockroachDB uses the PostgreSQL connection URL format, which has the following structure (the parts spelled all-uppercased are _placeholders_ for your specific connection details): - -```no-lines -postgresql://USER:PASSWORD@HOST:PORT/DATABASE?PARAMETERS -``` - -Here's a short explanation of each component: - -- `USER`: The name of your database user -- `PASSWORD`: The password for your database user -- `PORT`: The port where your database server is running. The default for CockroachDB is `26257`. -- `DATABASE`: The name of the database -- `PARAMETERS`: Any additional connection parameters. See the CockroachDB documentation [here](https://www.cockroachlabs.com/docs/stable/connection-parameters.html#additional-connection-parameters). - -For a [CockroachDB Serverless](https://www.cockroachlabs.com/docs/cockroachcloud/quickstart.html) or [Cockroach Dedicated](https://www.cockroachlabs.com/docs/cockroachcloud/quickstart-trial-cluster) database hosted on [CockroachDB Cloud](https://www.cockroachlabs.com/docs/cockroachcloud/quickstart/), the [connection URL](/orm/reference/connection-urls) looks similar to this: - -```bash file=.env -DATABASE_URL="postgresql://:@..cockroachlabs.cloud:26257/defaultdb?sslmode=verify-full&sslrootcert=$HOME/.postgresql/root.crt&options=--" -``` - -To find your connection string on CockroachDB Cloud, click the 'Connect' button on the overview page for your database cluster, and select the 'Connection string' tab. - -For a [CockroachDB database hosted locally](https://www.cockroachlabs.com/docs/stable/secure-a-cluster.html), the [connection URL](/orm/reference/connection-urls) looks similar to this: - -```bash file=.env -DATABASE_URL="postgresql://root@localhost:26257?sslmode=disable" -``` - -Your connection string is displayed as part of the welcome text when starting CockroachDB from the command line. diff --git a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/100-connect-your-database-typescript-mysql.mdx b/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/100-connect-your-database-typescript-mysql.mdx deleted file mode 100644 index 9b8f5ae7f6..0000000000 --- a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/100-connect-your-database-typescript-mysql.mdx +++ /dev/null @@ -1,61 +0,0 @@ ---- -title: 'Connect your database using TypeScript and MySQL' -sidebar_label: 'Connect your database' -metaTitle: 'Connect your database using TypeScript and MySQL' -metaDescription: 'Connect your database to your project using TypeScript and MySQL' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb', 'prismaPostgres'] -sidebar_class_name: hidden-sidebar -hide_table_of_contents: true -pagination_prev: getting-started/setup-prisma/start-from-scratch/relational-databases-typescript-mysql -pagination_next: getting-started/setup-prisma/start-from-scratch/relational-databases/using-prisma-migrate-typescript-mysql -slugSwitch: /getting-started/setup-prisma/start-from-scratch/relational-databases/connect-your-database- ---- - -To connect your database, you need to set the `url` field of the `datasource` block in your Prisma schema to your database [connection URL](/orm/reference/connection-urls): - -```prisma file=prisma/schema.prisma showLineNumbers -datasource db { - provider = "mysql" - url = env("DATABASE_URL") -} -``` - -In this case, the `url` is [set via an environment variable](/orm/prisma-schema/overview#accessing-environment-variables-from-the-schema) which is defined in `.env`: - -```bash file=.env -DATABASE_URL="mysql://johndoe:randompassword@localhost:3306/mydb" -``` - - - -We recommend adding `.env` to your `.gitignore` file to prevent committing your environment variables. - - - -You now need to adjust the connection URL to point to your own database. - -The [format of the connection URL](/orm/reference/connection-urls) for your database typically depends on the database you use. For MySQL, it looks as follows (the parts spelled all-uppercased are _placeholders_ for your specific connection details): - -```no-lines -mysql://USER:PASSWORD@HOST:PORT/DATABASE -``` - -Here's a short explanation of each component: - -- `USER`: The name of your database user -- `PASSWORD`: The password for your database user -- `PORT`: The port where your database server is running (typically `3306` for MySQL) -- `DATABASE`: The name of the [database](https://dev.mysql.com/doc/refman/8.0/en/creating-database.html) - -As an example, for a MySQL database hosted on AWS RDS, the [connection URL](/orm/reference/connection-urls) might look similar to this: - -```bash file=.env -DATABASE_URL="mysql://johndoe:XXX@mysql–instance1.123456789012.us-east-1.rds.amazonaws.com:3306/mydb" -``` - -When running MySQL locally, your connection URL typically looks similar to this: - -```bash file=.env -DATABASE_URL="mysql://root:randompassword@localhost:3306/mydb" -``` diff --git a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/100-connect-your-database-typescript-planetscale.mdx b/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/100-connect-your-database-typescript-planetscale.mdx deleted file mode 100644 index 408d02ba82..0000000000 --- a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/100-connect-your-database-typescript-planetscale.mdx +++ /dev/null @@ -1,89 +0,0 @@ ---- -title: 'Connect your database using TypeScript and PlanetScale' -sidebar_label: 'Connect your database' -metaTitle: 'Connect your database using TypeScript and PlanetScale' -metaDescription: 'Connect your database to your project using TypeScript and PlanetScale' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb', 'prismaPostgres'] -sidebar_class_name: hidden-sidebar -hide_table_of_contents: true -pagination_prev: getting-started/setup-prisma/start-from-scratch/relational-databases-typescript-planetscale -pagination_next: getting-started/setup-prisma/start-from-scratch/relational-databases/using-prisma-migrate-typescript-planetscale -slugSwitch: /getting-started/setup-prisma/start-from-scratch/relational-databases/connect-your-database- ---- - -To connect your database, you need to set the `url` field of the `datasource` block in your Prisma schema to your database [connection URL](/orm/reference/connection-urls): - -```prisma file=prisma/schema.prisma showLineNumbers -datasource db { - provider = "postgresql" - url = env("DATABASE_URL") -} -``` - -You will also need to set the relation mode type to `prisma` in order to [emulate foreign key constraints](/orm/overview/databases/planetscale#option-1-emulate-relations-in-prisma-client) in the `datasource` block: - -```prisma file=schema.prisma highlight=4;add showLineNumbers -datasource db { - provider = "mysql" - url = env("DATABASE_URL") - //add-next-line - relationMode = "prisma" -} -``` - -> **Note**: Since February 2024, you can alternatively [use foreign key constraints on a database-level in PlanetScale](/orm/overview/databases/planetscale#option-2-enable-foreign-key-constraints-in-the-planetscale-database-settings), which omits the need for setting `relationMode = "prisma"`. - -The `url` is [set via an environment variable](/orm/prisma-schema/overview#accessing-environment-variables-from-the-schema) which is defined in `.env`: - -```bash file=.env -DATABASE_URL="mysql://janedoe:mypassword@server.us-east-2.psdb.cloud/mydb?sslaccept=strict" -``` - -You now need to adjust the connection URL to point to your own database. - -The [format of the connection URL](/orm/reference/connection-urls) for your database typically depends on the database you use. PlanetScale uses the MySQL connection URL format, which has the following structure (the parts spelled all-uppercased are _placeholders_ for your specific connection details): - -```no-lines -mysql://USER:PASSWORD@HOST:PORT/DATABASE -``` - -Here's a short explanation of each component: - -- `USER`: The name of your database user -- `PASSWORD`: The password for your database user -- `PORT`: The port where your database server is running (typically `3306` for MySQL) -- `DATABASE`: The name of the [database](https://dev.mysql.com/doc/refman/8.0/en/creating-database.html) - -For a database hosted with PlanetScale, the [connection URL](/orm/reference/connection-urls) looks similar to this: - -```bash file=.env -DATABASE_URL="mysql://myusername:mypassword@server.us-east-2.psdb.cloud/mydb?sslaccept=strict" -``` - -The connection URL for a given database branch can be found from your PlanetScale account by going to the overview page for the branch and selecting the 'Connect' dropdown. In the 'Passwords' section, generate a new password and select 'Prisma' to get the Prisma format for the connection URL. - -
-Alternative method: connecting using the PlanetScale CLI - -Alternatively, you can connect to your PlanetScale database server using the [PlanetScale CLI](https://planetscale.com/docs/concepts/planetscale-environment-setup), and use a local connection URL. In this case the connection URL will look like this: - -```bash file=.env -DATABASE_URL="mysql://root@localhost:PORT/mydb" -``` - - - -We recommend adding `.env` to your `.gitignore` file to prevent committing your environment variables. - - - -To connect to your branch, use the following command: - -```terminal -pscale connect prisma-test branchname --port PORT -``` - -The `--port` flag can be omitted if you are using the default port `3306`. - -
diff --git a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/100-connect-your-database-typescript-postgresql.mdx b/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/100-connect-your-database-typescript-postgresql.mdx deleted file mode 100644 index 82703b7c19..0000000000 --- a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/100-connect-your-database-typescript-postgresql.mdx +++ /dev/null @@ -1,64 +0,0 @@ ---- -title: 'Connect your database using TypeScript and PostgreSQL' -sidebar_label: 'Connect your database' -metaTitle: 'Connect your database using TypeScript and PostgreSQL' -metaDescription: 'Connect your database to your project using TypeScript and PostgreSQL' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb', 'prismaPostgres'] -hide_table_of_contents: true -pagination_prev: getting-started/setup-prisma/start-from-scratch/relational-databases-typescript-postgresql -pagination_next: getting-started/setup-prisma/start-from-scratch/relational-databases/using-prisma-migrate-typescript-postgresql -slugSwitch: /getting-started/setup-prisma/start-from-scratch/relational-databases/connect-your-database- ---- - -To connect your database, you need to set the `url` field of the `datasource` block in your Prisma schema to your database [connection URL](/orm/reference/connection-urls): - -```prisma file=prisma/schema.prisma showLineNumbers -datasource db { - provider = "postgresql" - url = env("DATABASE_URL") -} -``` - -In this case, the `url` is [set via an environment variable](/orm/more/development-environment/environment-variables) which is defined in `.env`: - -```bash file=.env -DATABASE_URL="postgresql://johndoe:randompassword@localhost:5432/mydb?schema=public" -``` - - - -We recommend adding `.env` to your `.gitignore` file to prevent committing your environment variables. - - - -You now need to adjust the connection URL to point to your own database. - -The [format of the connection URL](/orm/reference/connection-urls) for your database depends on the database you use. For PostgreSQL, it looks as follows (the parts spelled all-uppercased are _placeholders_ for your specific connection details): - -```no-lines -postgresql://USER:PASSWORD@HOST:PORT/DATABASE?schema=SCHEMA -``` - -Here's a short explanation of each component: - -- `USER`: The name of your database user -- `PASSWORD`: The password for your database user -- `HOST`: The name of your host name (for the local environment, it is `localhost`) -- `PORT`: The port where your database server is running (typically `5432` for PostgreSQL) -- `DATABASE`: The name of the [database](https://www.postgresql.org/docs/12/manage-ag-overview.html) -- `SCHEMA`: The name of the [schema](https://www.postgresql.org/docs/12/ddl-schemas.html) inside the database - -If you're unsure what to provide for the `schema` parameter for a PostgreSQL connection URL, you can probably omit it. In that case, the default schema name `public` will be used. - -As an example, for a PostgreSQL database hosted on Heroku, the [connection URL](/orm/reference/connection-urls) might look similar to this: - -```bash file=.env -DATABASE_URL="postgresql://opnmyfngbknppm:XXX@ec2-46-137-91-216.eu-west-1.compute.amazonaws.com:5432/d50rgmkqi2ipus?schema=hello-prisma" -``` - -When running PostgreSQL locally on macOS, your user and password as well as the database name _typically_ correspond to the current _user_ of your OS, e.g. assuming the user is called `janedoe`: - -```bash file=.env -DATABASE_URL="postgresql://janedoe:janedoe@localhost:5432/janedoe?schema=hello-prisma" -``` diff --git a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/100-connect-your-database-typescript-prismaPostgres.mdx b/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/100-connect-your-database-typescript-prismaPostgres.mdx deleted file mode 100644 index cb0fe2f5b5..0000000000 --- a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/100-connect-your-database-typescript-prismaPostgres.mdx +++ /dev/null @@ -1,50 +0,0 @@ ---- -title: 'Connect your database using TypeScript and Prisma Postgres' -sidebar_label: 'Connect your database' -metaTitle: 'Connect your database using TypeScript and Prisma Postgres' -metaDescription: 'Connect your database to your project using TypeScript and Prisma Postgres' -langSwitcher: ['typescript'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb', 'prismaPostgres'] -sidebar_class_name: 'hidden-sidebar tech-switch' -hide_table_of_contents: true -pagination_prev: getting-started/setup-prisma/start-from-scratch/relational-databases-typescript-prismaPostgres -pagination_next: getting-started/setup-prisma/start-from-scratch/relational-databases/using-prisma-migrate-typescript-prismaPostgres -slugSwitch: /getting-started/setup-prisma/start-from-scratch/relational-databases/connect-your-database- ---- - -## Set up a Prisma Postgres database in the PDP Console - -Follow these steps to create your Prisma Postgres database: - -1. Log in to [PDP Console](https://console.prisma.io/). -1. In a [workspace](/platform/about#workspace) of your choice, click the **New project** button. -1. Type a name for your project in the **Name** field, e.g. **hello-ppg**. -1. In the **Prisma Postgres** section, click the **Get started** button. -1. In the **Region** dropdown, select the region that's closest to your current location, e.g. **US East (N. Virginia)**. -1. Click the **Create project** button. - -At this point, you'll be redirected to the **Dashboard** where you will need to wait for a few seconds while the status of your database changes from **`PROVISIONING`**, to **`ACTIVATING`** to **`CONNECTED`**. - -Once the green **`CONNECTED`** label appears, your database is ready to use. - -In the Console UI, you'll see a code snippet for a `.env` file with two environment variables defined. - -## Set environment variables in your local project - -Copy the `DATABASE_URL` environment variable from the Console UI and paste it into your `.env` file. Your `.env` file should look similar to this: - -```bash file=.env no-copy -DATABASE_URL="prisma+postgres://accelerate.prisma-data.net/?api_key=ey..." -``` - -By setting the `DATABASE_URL` in the `.env` file, you're ensuring that Prisma ORM can connect to your database. The `DATABASE_URL` is used in the `datasource` block in your Prisma schema: - -```prisma file=prisma/schema.prisma -datasource db { - provider = "postgresql" - // highlight-next-line - url = env("DATABASE_URL") -} -``` - -That's it! You can now start using the Prisma CLI to interact with your Prisma Postgres database. In the next section, you'll learn how to use the Prisma CLI to create and run migrations against your database to update its schema. \ No newline at end of file diff --git a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/100-connect-your-database-typescript-sqlserver.mdx b/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/100-connect-your-database-typescript-sqlserver.mdx deleted file mode 100644 index 2ef9848ae4..0000000000 --- a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/100-connect-your-database-typescript-sqlserver.mdx +++ /dev/null @@ -1,41 +0,0 @@ ---- -title: 'Connect your database using TypeScript and SQL Server' -sidebar_label: 'Connect your database' -metaTitle: 'Connect your database using TypeScript and SQL Server' -metaDescription: 'Connect your database to your project using TypeScript and SQL Server' -langSwitcher: ['typescript', 'node'] -sidebar_class_name: hidden-sidebar -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb', 'prismaPostgres'] -hide_table_of_contents: true -pagination_prev: getting-started/setup-prisma/start-from-scratch/relational-databases-typescript-sqlserver -pagination_next: getting-started/setup-prisma/start-from-scratch/relational-databases/using-prisma-migrate-typescript-sqlserver -slugSwitch: /getting-started/setup-prisma/start-from-scratch/relational-databases/connect-your-database- ---- - -To connect your database, you need to set the `url` field of the `datasource` block in your Prisma schema to your database [connection URL](/orm/reference/connection-urls): - -```prisma file=prisma/schema.prisma showLineNumbers -datasource db { - provider = "sqlserver" - url = env("DATABASE_URL") -} -``` - -In this case, the `url` is [set via an environment variable](/orm/prisma-schema/overview#accessing-environment-variables-from-the-schema) which is defined in `.env`: - -The following example connection URL [uses SQL authentication](/orm/overview/databases/sql-server), but there are [other ways to format your connection URL](/orm/overview/databases/sql-server) - -```bash file=.env - DATABASE_URL="sqlserver://localhost:1433;database=mydb;user=sa;password=r@ndomP@$$w0rd;trustServerCertificate=true" -``` - - - -We recommend adding `.env` to your `.gitignore` file to prevent committing your environment variables. - - - -Adjust the connection URL to match your setup - see [Microsoft SQL Server connection URL](/orm/overview/databases/sql-server) for more information. - -> Make sure TCP/IP connections are enabled via [SQL Server Configuration Manager](https://learn.microsoft.com/en-us/sql/relational-databases/sql-server-configuration-manager?view=sql-server-ver16&viewFallbackFrom=sql-server-ver16) to avoid `No connection could be made because the target machine actively refused it. (os error 10061)` - diff --git a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate-node-cockroachdb.mdx b/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate-node-cockroachdb.mdx deleted file mode 100644 index f39fe32418..0000000000 --- a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate-node-cockroachdb.mdx +++ /dev/null @@ -1,62 +0,0 @@ ---- -title: 'Using Prisma Migrate with JavaScript and CockroachDB' -sidebar_label: 'Using Prisma Migrate' -metaTitle: 'Using Prisma Migrate with JavaScript and CockroachDB' -metaDescription: 'Create database tables with Prisma Migrate using JavaScript and CockroachDB' -langSwitcher: ['typescript', 'node'] -sidebar_class_name: hidden-sidebar -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -hide_table_of_contents: true -pagination_prev: getting-started/setup-prisma/start-from-scratch/relational-databases/connect-your-database-node-cockroachdb -pagination_next: getting-started/setup-prisma/start-from-scratch/relational-databases/install-prisma-client-node-cockroachdb -slugSwitch: /getting-started/setup-prisma/start-from-scratch/relational-databases/using-prisma-migrate- ---- - -## Creating the database schema - -In this guide, you'll use [Prisma Migrate](/orm/prisma-migrate) to create the tables in your database. Add the following Prisma data model to your Prisma schema in `prisma/schema.prisma`: - -```prisma file=prisma/schema.prisma copy showLineNumbers -model Post { - id BigInt @id @default(sequence()) - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt - title String - content String? - published Boolean @default(false) - author User @relation(fields: [authorId], references: [id]) - authorId BigInt -} - -model Profile { - id BigInt @id @default(sequence()) - bio String? - user User @relation(fields: [userId], references: [id]) - userId BigInt @unique -} - -model User { - id BigInt @id @default(sequence()) - email String @unique - name String? - posts Post[] - profile Profile? -} -``` - -To map your data model to the database schema, you need to use the `prisma migrate` CLI commands: - -```terminal -npx prisma migrate dev --name init -``` - -This command does two things: - -1. It creates a new SQL migration file for this migration -1. It runs the SQL migration file against the database - -:::note -`generate` is called under the hood by default, after running `prisma migrate dev`. If the `prisma-client-js` generator is defined in your schema, this will check if `@prisma/client` is installed and install it if it's missing. -::: - -Great, you now created three tables in your database with Prisma Migrate 🚀 diff --git a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate-node-mysql.mdx b/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate-node-mysql.mdx deleted file mode 100644 index 4d95269b0a..0000000000 --- a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate-node-mysql.mdx +++ /dev/null @@ -1,61 +0,0 @@ ---- -title: 'Using Prisma Migrate with JavaScript and MySQL' -sidebar_label: 'Using Prisma Migrate' -metaTitle: 'Using Prisma Migrate with JavaScript and MySQL' -metaDescription: 'Create database tables with Prisma Migrate using JavaScript and MySQL' -langSwitcher: ['typescript', 'node'] -sidebar_class_name: hidden-sidebar -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -hide_table_of_contents: true -pagination_prev: getting-started/setup-prisma/start-from-scratch/relational-databases/connect-your-database-node-mysql -pagination_next: getting-started/setup-prisma/start-from-scratch/relational-databases/install-prisma-client-node-mysql -slugSwitch: /getting-started/setup-prisma/start-from-scratch/relational-databases/using-prisma-migrate- ---- - -## Creating the database schema - - -In this guide, you'll use [Prisma Migrate](/orm/prisma-migrate) to create the tables in your database. Add the following Prisma data model to your Prisma schema in `prisma/schema.prisma`: - -```prisma file=prisma/schema.prisma copy showLineNumbers -model Post { - id Int @id @default(autoincrement()) - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt - title String @db.VarChar(255) - content String? - published Boolean @default(false) - author User @relation(fields: [authorId], references: [id]) - authorId Int -} - -model Profile { - id Int @id @default(autoincrement()) - bio String? - user User @relation(fields: [userId], references: [id]) - userId Int @unique -} - -model User { - id Int @id @default(autoincrement()) - email String @unique - name String? - posts Post[] - profile Profile? -} -``` - -To map your data model to the database schema, you need to use the `prisma migrate` CLI commands: - -```terminal -npx prisma migrate dev --name init -``` - -This command does two things: - -1. It creates a new SQL migration file for this migration -1. It runs the SQL migration file against the database - -> **Note**: `generate` is called under the hood by default, after running `prisma migrate dev`. If the `prisma-client-js` generator is defined in your schema, this will check if `@prisma/client` is installed and install it if it's missing. - -Great, you now created three tables in your database with Prisma Migrate 🚀 diff --git a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate-node-planetscale.mdx b/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate-node-planetscale.mdx deleted file mode 100644 index d583dd3b63..0000000000 --- a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate-node-planetscale.mdx +++ /dev/null @@ -1,59 +0,0 @@ ---- -title: 'Using Prisma Migrate with JavaScript and PlanetScale' -sidebar_label: 'Using Prisma Migrate' -metaTitle: 'Using Prisma Migrate with JavaScript and PlanetScale' -metaDescription: 'Create database tables with Prisma Migrate using JavaScript and PlanetScale' -langSwitcher: ['typescript', 'node'] -sidebar_class_name: hidden-sidebar -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -hide_table_of_contents: true -pagination_prev: getting-started/setup-prisma/start-from-scratch/relational-databases/connect-your-database-node-planetscale -pagination_next: getting-started/setup-prisma/start-from-scratch/relational-databases/install-prisma-client-node-planetscale -slugSwitch: /getting-started/setup-prisma/start-from-scratch/relational-databases/using-prisma-migrate- ---- - -## Creating the database schema - -In this guide, you'll use Prisma's [`db push` command](/orm/prisma-migrate/workflows/prototyping-your-schema) to create the tables in your database. Add the following Prisma data model to your Prisma schema in `prisma/schema.prisma`: - -```prisma file=prisma/schema.prisma copy showLineNumbers -model Post { - id Int @id @default(autoincrement()) - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt - title String @db.VarChar(255) - content String? - published Boolean @default(false) - author User @relation(fields: [authorId], references: [id]) - authorId Int - - @@index(authorId) -} - -model Profile { - id Int @id @default(autoincrement()) - bio String? - user User @relation(fields: [userId], references: [id]) - userId Int @unique - - @@index(userId) -} - -model User { - id Int @id @default(autoincrement()) - email String @unique - name String? - posts Post[] - profile Profile? -} -``` - -You are now ready to push your new schema to your database. Connect to your `main` branch using the instructions in [Connect your database](/getting-started/setup-prisma/start-from-scratch/relational-databases/connect-your-database-typescript-planetscale). - -Now use the `db push` CLI command to push to the `main` branch: - -```terminal -npx prisma db push -``` - -Great, you now created three tables in your database with Prisma's `db push` command 🚀 diff --git a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate-node-postgresql.mdx b/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate-node-postgresql.mdx deleted file mode 100644 index 3a5db8a0df..0000000000 --- a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate-node-postgresql.mdx +++ /dev/null @@ -1,62 +0,0 @@ ---- -title: 'Using Prisma Migrate with JavaScript and PostgreSQL' -sidebar_label: 'Using Prisma Migrate' -metaTitle: 'Using Prisma Migrate with JavaScript and PostgreSQL' -metaDescription: 'Create database tables with Prisma Migrate using JavaScript and PostgreSQL' -langSwitcher: ['typescript', 'node'] -sidebar_class_name: hidden-sidebar -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -hide_table_of_contents: true -pagination_prev: getting-started/setup-prisma/start-from-scratch/relational-databases/connect-your-database-node-postgresql -pagination_next: getting-started/setup-prisma/start-from-scratch/relational-databases/install-prisma-client-node-postgresql -slugSwitch: /getting-started/setup-prisma/start-from-scratch/relational-databases/using-prisma-migrate- ---- - -## Creating the database schema - -In this guide, you'll use [Prisma Migrate](/orm/prisma-migrate) to create the tables in your database. Add the following data model to your [Prisma schema](/orm/prisma-schema) in `prisma/schema.prisma`: - -```prisma file=prisma/schema.prisma showLineNumbers -model Post { - id Int @id @default(autoincrement()) - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt - title String @db.VarChar(255) - content String? - published Boolean @default(false) - author User @relation(fields: [authorId], references: [id]) - authorId Int -} - -model Profile { - id Int @id @default(autoincrement()) - bio String? - user User @relation(fields: [userId], references: [id]) - userId Int @unique -} - -model User { - id Int @id @default(autoincrement()) - email String @unique - name String? - posts Post[] - profile Profile? -} -``` - -To map your data model to the database schema, you need to use the `prisma migrate` CLI commands: - -```terminal -npx prisma migrate dev --name init -``` - -This command does two things: - -1. It creates a new SQL migration file for this migration -1. It runs the SQL migration file against the database - -:::note -`generate` is called under the hood by default, after running `prisma migrate dev`. If the `prisma-client-js` generator is defined in your schema, this will check if `@prisma/client` is installed and install it if it's missing. -::: - -Great, you now created three tables in your database with Prisma Migrate 🚀 diff --git a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate-node-sqlserver.mdx b/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate-node-sqlserver.mdx deleted file mode 100644 index a7446e5dd0..0000000000 --- a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate-node-sqlserver.mdx +++ /dev/null @@ -1,60 +0,0 @@ ---- -title: 'Using Prisma Migrate with JavaScript and SQL Server' -sidebar_label: 'Using Prisma Migrate' -metaTitle: 'Using Prisma Migrate with JavaScript and SQL Server' -metaDescription: 'Create database tables with Prisma Migrate using JavaScript and SQL Server' -langSwitcher: ['typescript', 'node'] -sidebar_class_name: hidden-sidebar -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -hide_table_of_contents: true -pagination_prev: getting-started/setup-prisma/start-from-scratch/relational-databases/connect-your-database-node-sqlserver -pagination_next: getting-started/setup-prisma/start-from-scratch/relational-databases/install-prisma-client-node-sqlserver -slugSwitch: /getting-started/setup-prisma/start-from-scratch/relational-databases/using-prisma-migrate- ---- - -## Creating the database schema - -In this guide, you'll use [Prisma Migrate](/orm/prisma-migrate) to create the tables in your database. Add the following Prisma data model to your Prisma schema in `prisma/schema.prisma`: - -```prisma file=prisma/schema.prisma copy showLineNumbers -model Post { - id Int @id @default(autoincrement()) - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt - title String @db.VarChar(255) - content String? - published Boolean @default(false) - author User @relation(fields: [authorId], references: [id]) - authorId Int -} - -model Profile { - id Int @id @default(autoincrement()) - bio String? - user User @relation(fields: [userId], references: [id]) - userId Int @unique -} - -model User { - id Int @id @default(autoincrement()) - email String @unique - name String? - posts Post[] - profile Profile? -} -``` - -To map your data model to the database schema, you need to use the `prisma migrate` CLI commands: - -```terminal -npx prisma migrate dev --name init -``` - -This command does two things: - -1. It creates a new SQL migration file for this migration -1. It runs the SQL migration file against the database - -> **Note**: `generate` is called under the hood by default, after running `prisma migrate dev`. If the `prisma-client-js` generator is defined in your schema, this will check if `@prisma/client` is installed and install it if it's missing. - -Great, you now created three tables in your database with Prisma Migrate 🚀 diff --git a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate-typescript-cockroachdb.mdx b/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate-typescript-cockroachdb.mdx deleted file mode 100644 index 8afec9807f..0000000000 --- a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate-typescript-cockroachdb.mdx +++ /dev/null @@ -1,62 +0,0 @@ ---- -title: 'Using Prisma Migrate with TypeScript and CockroachDB' -sidebar_label: 'Using Prisma Migrate' -metaTitle: 'Using Prisma Migrate with TypeScript and CockroachDB' -metaDescription: 'Create database tables with Prisma Migrate using TypeScript and CockroachDB' -langSwitcher: ['typescript', 'node'] -sidebar_class_name: hidden-sidebar -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb', 'prismaPostgres'] -hide_table_of_contents: true -pagination_prev: getting-started/setup-prisma/start-from-scratch/relational-databases/connect-your-database-typescript-cockroachdb -pagination_next: getting-started/setup-prisma/start-from-scratch/relational-databases/install-prisma-client-typescript-cockroachdb -slugSwitch: /getting-started/setup-prisma/start-from-scratch/relational-databases/using-prisma-migrate- ---- - -## Creating the database schema - -In this guide, you'll use [Prisma Migrate](/orm/prisma-migrate) to create the tables in your database. Add the following Prisma data model to your Prisma schema in `prisma/schema.prisma`: - -```prisma file=prisma/schema.prisma copy showLineNumbers -model Post { - id BigInt @id @default(sequence()) - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt - title String - content String? - published Boolean @default(false) - author User @relation(fields: [authorId], references: [id]) - authorId BigInt -} - -model Profile { - id BigInt @id @default(sequence()) - bio String? - user User @relation(fields: [userId], references: [id]) - userId BigInt @unique -} - -model User { - id BigInt @id @default(sequence()) - email String @unique - name String? - posts Post[] - profile Profile? -} -``` - -To map your data model to the database schema, you need to use the `prisma migrate` CLI commands: - -```terminal -npx prisma migrate dev --name init -``` - -This command does two things: - -1. It creates a new SQL migration file for this migration -1. It runs the SQL migration file against the database - -:::note -`generate` is called under the hood by default, after running `prisma migrate dev`. If the `prisma-client-js` generator is defined in your schema, this will check if `@prisma/client` is installed and install it if it's missing. -::: - -Great, you now created three tables in your database with Prisma Migrate 🚀 diff --git a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate-typescript-mysql.mdx b/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate-typescript-mysql.mdx deleted file mode 100644 index c7081afe43..0000000000 --- a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate-typescript-mysql.mdx +++ /dev/null @@ -1,60 +0,0 @@ ---- -title: 'Using Prisma Migrate with TypeScript and MySQL' -sidebar_label: 'Using Prisma Migrate' -metaTitle: 'Using Prisma Migrate with TypeScript and MySQL' -metaDescription: 'Create database tables with Prisma Migrate using TypeScript and MySQL' -langSwitcher: ['typescript', 'node'] -sidebar_class_name: hidden-sidebar -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb', 'prismaPostgres'] -hide_table_of_contents: true -pagination_prev: getting-started/setup-prisma/start-from-scratch/relational-databases/connect-your-database-typescript-mysql -pagination_next: getting-started/setup-prisma/start-from-scratch/relational-databases/install-prisma-client-typescript-mysql -slugSwitch: /getting-started/setup-prisma/start-from-scratch/relational-databases/using-prisma-migrate- ---- - -## Creating the database schema - -In this guide, you'll use [Prisma Migrate](/orm/prisma-migrate) to create the tables in your database. Add the following Prisma data model to your Prisma schema in `prisma/schema.prisma`: - -```prisma file=prisma/schema.prisma copy showLineNumbers -model Post { - id Int @id @default(autoincrement()) - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt - title String @db.VarChar(255) - content String? - published Boolean @default(false) - author User @relation(fields: [authorId], references: [id]) - authorId Int -} - -model Profile { - id Int @id @default(autoincrement()) - bio String? - user User @relation(fields: [userId], references: [id]) - userId Int @unique -} - -model User { - id Int @id @default(autoincrement()) - email String @unique - name String? - posts Post[] - profile Profile? -} -``` - -To map your data model to the database schema, you need to use the `prisma migrate` CLI commands: - -```terminal -npx prisma migrate dev --name init -``` - -This command does two things: - -1. It creates a new SQL migration file for this migration -1. It runs the SQL migration file against the database - -> **Note**: `generate` is called under the hood by default, after running `prisma migrate dev`. If the `prisma-client-js` generator is defined in your schema, this will check if `@prisma/client` is installed and install it if it's missing. - -Great, you now created three tables in your database with Prisma Migrate 🚀 diff --git a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate-typescript-planetscale.mdx b/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate-typescript-planetscale.mdx deleted file mode 100644 index 14af90d1ee..0000000000 --- a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate-typescript-planetscale.mdx +++ /dev/null @@ -1,59 +0,0 @@ ---- -title: 'Using Prisma Migrate with TypeScript and PlanetScale' -sidebar_label: 'Using Prisma Migrate' -metaTitle: 'Using Prisma Migrate with TypeScript and PlanetScale' -metaDescription: 'Create database tables with Prisma Migrate using TypeScript and PlanetScale' -langSwitcher: ['typescript', 'node'] -sidebar_class_name: hidden-sidebar -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb', 'prismaPostgres'] -hide_table_of_contents: true -pagination_prev: getting-started/setup-prisma/start-from-scratch/relational-databases/connect-your-database-typescript-planetscale -pagination_next: getting-started/setup-prisma/start-from-scratch/relational-databases/install-prisma-client-typescript-planetscale -slugSwitch: /getting-started/setup-prisma/start-from-scratch/relational-databases/using-prisma-migrate- ---- - -## Creating the database schema - -In this guide, you'll use Prisma's [`db push` command](/orm/prisma-migrate/workflows/prototyping-your-schema) to create the tables in your database. Add the following Prisma data model to your Prisma schema in `prisma/schema.prisma`: - -```prisma file=prisma/schema.prisma copy showLineNumbers -model Post { - id Int @id @default(autoincrement()) - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt - title String @db.VarChar(255) - content String? - published Boolean @default(false) - author User @relation(fields: [authorId], references: [id]) - authorId Int - - @@index(authorId) -} - -model Profile { - id Int @id @default(autoincrement()) - bio String? - user User @relation(fields: [userId], references: [id]) - userId Int @unique - - @@index(userId) -} - -model User { - id Int @id @default(autoincrement()) - email String @unique - name String? - posts Post[] - profile Profile? -} -``` - -You are now ready to push your new schema to your database. Connect to your `main` branch using the instructions in [Connect your database](/getting-started/setup-prisma/start-from-scratch/relational-databases/connect-your-database-typescript-planetscale). - -Now use the `db push` CLI command to push to the `main` branch: - -```terminal -npx prisma db push -``` - -Great, you now created three tables in your database with Prisma's `db push` command 🚀 diff --git a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate-typescript-postgresql.mdx b/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate-typescript-postgresql.mdx deleted file mode 100644 index 9591d0517e..0000000000 --- a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate-typescript-postgresql.mdx +++ /dev/null @@ -1,61 +0,0 @@ ---- -title: 'Using Prisma Migrate with TypeScript and PostgreSQL' -sidebar_label: 'Using Prisma Migrate' -metaTitle: 'Using Prisma Migrate with TypeScript and PostgreSQL' -metaDescription: 'Create database tables with Prisma Migrate using TypeScript and PostgreSQL' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb', 'prismaPostgres'] -hide_table_of_contents: true -pagination_prev: getting-started/setup-prisma/start-from-scratch/relational-databases/connect-your-database-typescript-postgresql -pagination_next: getting-started/setup-prisma/start-from-scratch/relational-databases/install-prisma-client-typescript-postgresql -slugSwitch: /getting-started/setup-prisma/start-from-scratch/relational-databases/using-prisma-migrate- ---- - -## Creating the database schema - -In this guide, you'll use [Prisma Migrate](/orm/prisma-migrate) to create the tables in your database. Add the following data model to your [Prisma schema](/orm/prisma-schema) in `prisma/schema.prisma`: - -```prisma file=prisma/schema.prisma showLineNumbers -model Post { - id Int @id @default(autoincrement()) - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt - title String @db.VarChar(255) - content String? - published Boolean @default(false) - author User @relation(fields: [authorId], references: [id]) - authorId Int -} - -model Profile { - id Int @id @default(autoincrement()) - bio String? - user User @relation(fields: [userId], references: [id]) - userId Int @unique -} - -model User { - id Int @id @default(autoincrement()) - email String @unique - name String? - posts Post[] - profile Profile? -} -``` - -To map your data model to the database schema, you need to use the `prisma migrate` CLI commands: - -```terminal -npx prisma migrate dev --name init -``` - -This command does two things: - -1. It creates a new SQL migration file for this migration -1. It runs the SQL migration file against the database - -:::note -`generate` is called under the hood by default, after running `prisma migrate dev`. If the `prisma-client-js` generator is defined in your schema, this will check if `@prisma/client` is installed and install it if it's missing. -::: - -Great, you now created three tables in your database with Prisma Migrate 🚀 diff --git a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate-typescript-prismaPostgres.mdx b/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate-typescript-prismaPostgres.mdx deleted file mode 100644 index 350b89cfdb..0000000000 --- a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate-typescript-prismaPostgres.mdx +++ /dev/null @@ -1,83 +0,0 @@ ---- -title: 'Using Prisma Migrate with TypeScript and Prisma Postgres' -sidebar_label: 'Using Prisma Migrate' -metaTitle: 'Using Prisma Migrate with TypeScript and Prisma Postgres' -metaDescription: 'Create database tables with Prisma Migrate using TypeScript and Prisma Postgres' -langSwitcher: ['typescript'] -sidebar_class_name: hidden-sidebar -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb', 'prismaPostgres'] -hide_table_of_contents: true -pagination_prev: getting-started/setup-prisma/start-from-scratch/relational-databases/connect-your-database-typescript-prismaPostgres -pagination_next: getting-started/setup-prisma/start-from-scratch/relational-databases/install-prisma-client-typescript-prismaPostgres -slugSwitch: /getting-started/setup-prisma/start-from-scratch/relational-databases/using-prisma-migrate- ---- - -## Creating the database schema - -In this guide, you'll use [Prisma Migrate](/orm/prisma-migrate) to create the tables in your database. - -To do so, first add the following Prisma data model to your Prisma schema in `prisma/schema.prisma`: - -```prisma file=prisma/schema.prisma copy -model Post { - id Int @id @default(autoincrement()) - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt - title String - content String? - published Boolean @default(false) - author User @relation(fields: [authorId], references: [id]) - authorId Int -} - -model Profile { - id Int @id @default(autoincrement()) - bio String? - user User @relation(fields: [userId], references: [id]) - userId Int @unique -} - -model User { - id Int @id @default(autoincrement()) - email String @unique - name String? - posts Post[] - profile Profile? -} -``` - -This data model defines three [models](/orm/prisma-schema/data-model/models) (which will be mapped to _tables_ in the underlying database): -- `Post` -- `Profile` -- `User` - -It also defines two [relations](/orm/prisma-schema/data-model/relations): -- A one-to-many relation between `User` and `Post` (i.e. "_one_ user can have _many_ posts") -- A one-to-one relation between `User` and `Profile` (i.e. "_one_ user can have _one_ profile") - -To map your data model to the database schema, you need to use the `prisma migrate` CLI commands: - -```terminal -npx prisma migrate dev --name init -``` - -This command did two things: - -1. It generated a new SQL migration file for this migration -1. It ran the SQL migration file against the database - -You can inspect the generated SQL migration file in the newly created `prisma/migrations` directory. - -:::tip Explore your database in Prisma Studio - -[Prisma Studio](/orm/tools/prisma-studio) is a visual editor for your database. You can open it with the following command in your terminal: - -``` -npx prisma studio -``` - -Since you just created the database, you won't see any records but you can take a look at the empty `User`, `Post` and `Profile` tables. - -::: - -Great, you now created three tables in your database with Prisma Migrate. In the next section, you'll learn how to install Prisma Client which lets you send queries to your database from your TypeScript app. diff --git a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate-typescript-sqlserver.mdx b/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate-typescript-sqlserver.mdx deleted file mode 100644 index ee06eeffae..0000000000 --- a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/150-using-prisma-migrate-typescript-sqlserver.mdx +++ /dev/null @@ -1,60 +0,0 @@ ---- -title: 'Using Prisma Migrate with TypeScript and SQL Server' -sidebar_label: 'Using Prisma Migrate' -metaTitle: 'Using Prisma Migrate with TypeScript and SQL Server' -metaDescription: 'Create database tables with Prisma Migrate using TypeScript and SQL Server' -langSwitcher: ['typescript', 'node'] -sidebar_class_name: hidden-sidebar -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb', 'prismaPostgres'] -hide_table_of_contents: true -pagination_prev: getting-started/setup-prisma/start-from-scratch/relational-databases/connect-your-database-typescript-sqlserver -pagination_next: getting-started/setup-prisma/start-from-scratch/relational-databases/install-prisma-client-typescript-sqlserver -slugSwitch: /getting-started/setup-prisma/start-from-scratch/relational-databases/using-prisma-migrate- ---- - -## Creating the database schema - -In this guide, you'll use [Prisma Migrate](/orm/prisma-migrate) to create the tables in your database. Add the following Prisma data model to your Prisma schema in `prisma/schema.prisma`: - -```prisma file=prisma/schema.prisma copy showLineNumbers -model Post { - id Int @id @default(autoincrement()) - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt - title String @db.VarChar(255) - content String? - published Boolean @default(false) - author User @relation(fields: [authorId], references: [id]) - authorId Int -} - -model Profile { - id Int @id @default(autoincrement()) - bio String? - user User @relation(fields: [userId], references: [id]) - userId Int @unique -} - -model User { - id Int @id @default(autoincrement()) - email String @unique - name String? - posts Post[] - profile Profile? -} -``` - -To map your data model to the database schema, you need to use the `prisma migrate` CLI commands: - -```terminal -npx prisma migrate dev --name init -``` - -This command does two things: - -1. It creates a new SQL migration file for this migration -1. It runs the SQL migration file against the database - -> **Note**: `generate` is called under the hood by default, after running `prisma migrate dev`. If the `prisma-client-js` generator is defined in your schema, this will check if `@prisma/client` is installed and install it if it's missing. - -Great, you now created three tables in your database with Prisma Migrate 🚀 diff --git a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client-node-cockroachdb.mdx b/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client-node-cockroachdb.mdx deleted file mode 100644 index 751ae30729..0000000000 --- a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client-node-cockroachdb.mdx +++ /dev/null @@ -1,17 +0,0 @@ ---- -title: 'Install Prisma Client (JavaScript and CockroachDB)' -sidebar_label: 'Install Prisma Client' -metaTitle: 'Install Prisma Client: JavaScript and CockroachDB' -metaDescription: 'Install and generate Prisma Client in your project using JavaScript and CockroachDB' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -sidebar_class_name: hidden-sidebar -hide_table_of_contents: true -pagination_prev: getting-started/setup-prisma/start-from-scratch/relational-databases/using-prisma-migrate-node-cockroachdb -pagination_next: getting-started/setup-prisma/start-from-scratch/relational-databases/querying-the-database-node-cockroachdb -slugSwitch: /getting-started/setup-prisma/start-from-scratch/relational-databases/install-prisma-client- ---- - -import InstallPrismaClient from './_install-prisma-client-partial.mdx' - - diff --git a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client-node-mysql.mdx b/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client-node-mysql.mdx deleted file mode 100644 index 2de9870bd7..0000000000 --- a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client-node-mysql.mdx +++ /dev/null @@ -1,17 +0,0 @@ ---- -title: 'Install Prisma Client (JavaScript and MySQL)' -sidebar_label: 'Install Prisma Client' -metaTitle: 'Install Prisma Client: JavaScript and MySQL' -metaDescription: 'Install and generate Prisma Client in your project using JavaScript and MySQL' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -sidebar_class_name: hidden-sidebar -hide_table_of_contents: true -pagination_prev: getting-started/setup-prisma/start-from-scratch/relational-databases/using-prisma-migrate-node-mysql -pagination_next: getting-started/setup-prisma/start-from-scratch/relational-databases/querying-the-database-node-mysql -slugSwitch: /getting-started/setup-prisma/start-from-scratch/relational-databases/install-prisma-client- ---- - -import InstallPrismaClient from './_install-prisma-client-partial.mdx' - - diff --git a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client-node-planetscale.mdx b/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client-node-planetscale.mdx deleted file mode 100644 index 5caaba1e29..0000000000 --- a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client-node-planetscale.mdx +++ /dev/null @@ -1,17 +0,0 @@ ---- -title: 'Install Prisma Client (JavaScript and PlanetScale)' -sidebar_label: 'Install Prisma Client' -metaTitle: 'Install Prisma Client: JavaScript and PlanetScale' -metaDescription: 'Install and generate Prisma Client in your project using JavaScript and PlanetScale' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -sidebar_class_name: hidden-sidebar -hide_table_of_contents: true -pagination_prev: getting-started/setup-prisma/start-from-scratch/relational-databases/using-prisma-migrate-node-planetscale -pagination_next: getting-started/setup-prisma/start-from-scratch/relational-databases/querying-the-database-node-planetscale -slugSwitch: /getting-started/setup-prisma/start-from-scratch/relational-databases/install-prisma-client- ---- - -import InstallPrismaClient from './_install-prisma-client-partial.mdx' - - diff --git a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client-node-postgresql.mdx b/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client-node-postgresql.mdx deleted file mode 100644 index 8be8bd1b6a..0000000000 --- a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client-node-postgresql.mdx +++ /dev/null @@ -1,17 +0,0 @@ ---- -title: 'Install Prisma Client (JavaScript and PostgreSQL)' -sidebar_label: 'Install Prisma Client' -metaTitle: 'Install Prisma Client: JavaScript and PostgreSQL' -metaDescription: 'Install and generate Prisma Client in your project using JavaScript and PostgreSQL' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -sidebar_class_name: hidden-sidebar -hide_table_of_contents: true -pagination_prev: getting-started/setup-prisma/start-from-scratch/relational-databases/using-prisma-migrate-node-postgresql -pagination_next: getting-started/setup-prisma/start-from-scratch/relational-databases/querying-the-database-node-postgresql -slugSwitch: /getting-started/setup-prisma/start-from-scratch/relational-databases/install-prisma-client- ---- - -import InstallPrismaClient from './_install-prisma-client-partial.mdx' - - diff --git a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client-node-sqlserver.mdx b/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client-node-sqlserver.mdx deleted file mode 100644 index f68348bd8e..0000000000 --- a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client-node-sqlserver.mdx +++ /dev/null @@ -1,17 +0,0 @@ ---- -title: 'Install Prisma Client (JavaScript and SQL Server)' -sidebar_label: 'Install Prisma Client' -metaTitle: 'Install Prisma Client: JavaScript and SQL Server' -metaDescription: 'Install and generate Prisma Client in your project using JavaScript and SQL Server' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -sidebar_class_name: hidden-sidebar -hide_table_of_contents: true -pagination_prev: getting-started/setup-prisma/start-from-scratch/relational-databases/using-prisma-migrate-node-sqlserver -pagination_next: getting-started/setup-prisma/start-from-scratch/relational-databases/querying-the-database-node-sqlserver -slugSwitch: /getting-started/setup-prisma/start-from-scratch/relational-databases/install-prisma-client- ---- - -import InstallPrismaClient from './_install-prisma-client-partial.mdx' - - diff --git a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client-typescript-cockroachdb.mdx b/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client-typescript-cockroachdb.mdx deleted file mode 100644 index ee8904442b..0000000000 --- a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client-typescript-cockroachdb.mdx +++ /dev/null @@ -1,17 +0,0 @@ ---- -title: 'Install Prisma Client (TypeScript and CockroachDB)' -sidebar_label: 'Install Prisma Client' -metaTitle: 'Install Prisma Client: TypeScript and CockroachDB' -metaDescription: 'Install and generate Prisma Client in your project using TypeScript and CockroachDB' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb', 'prismaPostgres'] -sidebar_class_name: hidden-sidebar -hide_table_of_contents: true -pagination_prev: getting-started/setup-prisma/start-from-scratch/relational-databases/using-prisma-migrate-typescript-cockroachdb -pagination_next: getting-started/setup-prisma/start-from-scratch/relational-databases/querying-the-database-typescript-cockroachdb -slugSwitch: /getting-started/setup-prisma/start-from-scratch/relational-databases/install-prisma-client- ---- - -import InstallPrismaClient from './_install-prisma-client-partial.mdx' - - diff --git a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client-typescript-mysql.mdx b/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client-typescript-mysql.mdx deleted file mode 100644 index 9f4f57e82e..0000000000 --- a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client-typescript-mysql.mdx +++ /dev/null @@ -1,17 +0,0 @@ ---- -title: 'Install Prisma Client (TypeScript and MySQL)' -sidebar_label: 'Install Prisma Client' -metaTitle: 'Install Prisma Client: TypeScript and MySQL' -metaDescription: 'Install and generate Prisma Client in your project using TypeScript and MySQL' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb', 'prismaPostgres'] -sidebar_class_name: hidden-sidebar -hide_table_of_contents: true -pagination_prev: getting-started/setup-prisma/start-from-scratch/relational-databases/using-prisma-migrate-typescript-mysql -pagination_next: getting-started/setup-prisma/start-from-scratch/relational-databases/querying-the-database-typescript-mysql -slugSwitch: /getting-started/setup-prisma/start-from-scratch/relational-databases/install-prisma-client- ---- - -import InstallPrismaClient from './_install-prisma-client-partial.mdx' - - diff --git a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client-typescript-planetscale.mdx b/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client-typescript-planetscale.mdx deleted file mode 100644 index cc8361c41b..0000000000 --- a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client-typescript-planetscale.mdx +++ /dev/null @@ -1,17 +0,0 @@ ---- -title: 'Install Prisma Client (TypeScript and PlanetScale)' -sidebar_label: 'Install Prisma Client' -metaTitle: 'Install Prisma Client: TypeScript and PlanetScale' -metaDescription: 'Install and generate Prisma Client in your project using TypeScript and PlanetScale' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb', 'prismaPostgres'] -sidebar_class_name: hidden-sidebar -hide_table_of_contents: true -pagination_prev: getting-started/setup-prisma/start-from-scratch/relational-databases/using-prisma-migrate-typescript-planetscale -pagination_next: getting-started/setup-prisma/start-from-scratch/relational-databases/querying-the-database-typescript-planetscale -slugSwitch: /getting-started/setup-prisma/start-from-scratch/relational-databases/install-prisma-client- ---- - -import InstallPrismaClient from './_install-prisma-client-partial.mdx' - - diff --git a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client-typescript-postgresql.mdx b/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client-typescript-postgresql.mdx deleted file mode 100644 index a8b37611ee..0000000000 --- a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client-typescript-postgresql.mdx +++ /dev/null @@ -1,32 +0,0 @@ ---- -title: 'Install Prisma Client (TypeScript and PostgreSQL)' -sidebar_label: 'Install Prisma Client' -metaTitle: 'Install Prisma Client: TypeScript and PostgreSQL' -metaDescription: 'Install and generate Prisma Client in your project using TypeScript and PostgreSQL' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb', 'prismaPostgres'] -hide_table_of_contents: true -pagination_prev: getting-started/setup-prisma/start-from-scratch/relational-databases/using-prisma-migrate-typescript-postgresql -pagination_next: getting-started/setup-prisma/start-from-scratch/relational-databases/querying-the-database-typescript-postgresql -slugSwitch: /getting-started/setup-prisma/start-from-scratch/relational-databases/install-prisma-client- ---- - -import InstallPrismaClient from './_install-prisma-client-partial.mdx' - - - -These commands serve different purposes in managing your database schema with Prisma. Here’s a breakdown of when and why to use each: - -#### `npx prisma migrate dev` - -- **Purpose:** This command generates and applies a new migration based on your Prisma schema changes. It creates migration files that keep a history of changes. -- **Use Case:** Use this when you want to maintain a record of database changes, which is essential for production environments or when working in teams. It allows for version control of your database schema. -- **Benefits:** This command also includes checks for applying migrations in a controlled manner, ensuring data integrity. - - -#### `npx prisma db push` - -- **Purpose:** This command is used to push your current Prisma schema to the database directly. It applies any changes you've made to your schema without creating migration files. -- **Use Case:** It’s particularly useful during the development phase when you want to quickly sync your database schema with your Prisma schema without worrying about migration history. -- **Caution:** It can overwrite data if your schema changes affect existing tables or columns, so it’s best for early-stage development or prototyping. - diff --git a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client-typescript-prismaPostgres.mdx b/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client-typescript-prismaPostgres.mdx deleted file mode 100644 index cd152cec57..0000000000 --- a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client-typescript-prismaPostgres.mdx +++ /dev/null @@ -1,28 +0,0 @@ ---- -title: 'Install Prisma Client (TypeScript and Prisma Postgres)' -sidebar_label: 'Install Prisma Client' -metaTitle: 'Install Prisma Client: TypeScript and Prisma Postgres' -metaDescription: 'Install and generate Prisma Client in your project using TypeScript and Prisma Postgres' -langSwitcher: ['typescript'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb', 'prismaPostgres'] -sidebar_class_name: hidden-sidebar -hide_table_of_contents: true -pagination_prev: getting-started/setup-prisma/start-from-scratch/relational-databases/using-prisma-migrate-typescript-prismaPostgres -pagination_next: getting-started/setup-prisma/start-from-scratch/relational-databases/querying-the-database-typescript-prismaPostgres -slugSwitch: /getting-started/setup-prisma/start-from-scratch/relational-databases/install-prisma-client- ---- - -import InstallPrismaClient from './_install-prisma-client-partial.mdx' - - - -## Install the Prisma Accelerate extension - -Since Prisma Postgres provides a connection pool and (optional) caching layer with Prisma Accelerate, you need to install the Accelerate [Client extension](/orm/prisma-client/client-extensions) in your project as well: - -``` -npm install @prisma/extension-accelerate -``` - -With that you're all set to read and write data in your database. Move on to the next page to start querying your Prisma Postgres database using Prisma Client. - diff --git a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client-typescript-sqlserver.mdx b/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client-typescript-sqlserver.mdx deleted file mode 100644 index c92dbcf171..0000000000 --- a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/200-install-prisma-client-typescript-sqlserver.mdx +++ /dev/null @@ -1,17 +0,0 @@ ---- -title: 'Install Prisma Client (TypeScript and SQL Server)' -sidebar_label: 'Install Prisma Client' -metaTitle: 'Install Prisma Client: TypeScript and SQL Server' -metaDescription: 'Install and generate Prisma Client in your project using TypeScript and SQL Server' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb', 'prismaPostgres'] -sidebar_class_name: hidden-sidebar -hide_table_of_contents: true -pagination_prev: getting-started/setup-prisma/start-from-scratch/relational-databases/using-prisma-migrate-typescript-sqlserver -pagination_next: getting-started/setup-prisma/start-from-scratch/relational-databases/querying-the-database-typescript-sqlserver -slugSwitch: /getting-started/setup-prisma/start-from-scratch/relational-databases/install-prisma-client- ---- - -import InstallPrismaClient from './_install-prisma-client-partial.mdx' - - diff --git a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database-node-cockroachdb.mdx b/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database-node-cockroachdb.mdx deleted file mode 100644 index da47ee46b7..0000000000 --- a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database-node-cockroachdb.mdx +++ /dev/null @@ -1,205 +0,0 @@ ---- -title: 'Querying the database using JavaScript and CockroachDB' -sidebar_label: 'Querying the database' -metaTitle: 'Querying the database using JavaScript and CockroachDB' -metaDescription: 'Write data to and query the database using JavaScript and CockroachDB' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -hide_table_of_contents: true -sidebar_class_name: hidden-sidebar -pagination_prev: getting-started/setup-prisma/start-from-scratch/relational-databases/install-prisma-client-node-cockroachdb -pagination_next: getting-started/setup-prisma/start-from-scratch/relational-databases/next-steps -slugSwitch: /getting-started/setup-prisma/start-from-scratch/relational-databases/querying-the-database- ---- - -## Write your first query with Prisma Client - -Now that you have generated [Prisma Client](/orm/prisma-client), you can start writing queries to read and write data in your database. For the purpose of this guide, you'll use a plain Node.js script to explore some basic features of Prisma Client. - -Create a new file named `index.js` and add the following code to it: - -```js file=index.js copy showLineNumbers -const { PrismaClient } = require('./generated/prisma') - -const prisma = new PrismaClient() - -async function main() { - // ... you will write your Prisma Client queries here -} - -main() - .then(async () => { - await prisma.$disconnect() - }) - .catch(async (e) => { - console.error(e) - await prisma.$disconnect() - process.exit(1) - }) -``` - -Here's a quick overview of the different parts of the code snippet: - -1. Import the `PrismaClient` constructor from the `@prisma/client` node module -1. Instantiate `PrismaClient` -1. Define an `async` function named `main` to send queries to the database -1. Call the `main` function -1. Close the database connections when the script terminates - -Inside the `main` function, add the following query to read all `User` records from the database and print the result: - -```js file=index.js highlight=2;delete|3,4;add showLineNumbers -async function main() { - //delete-next-line - // ... you will write your Prisma Client queries here - //add-start - const allUsers = await prisma.user.findMany() - console.log(allUsers) - //add-end -} -``` - -Now run the code with this command: - -```terminal copy -node index.js -``` - -This should print an empty array because there are no `User` records in the database yet: - -```json no-lines -[] -``` - -## Write data into the database - -The `findMany` query you used in the previous section only _reads_ data from the database (although it was still empty). In this section, you'll learn how to write a query to _write_ new records into the `Post` and `User` tables. - -Adjust the `main` function to send a `create` query to the database: - -```js file=index.js highlight=2-21;add copy showLineNumbers -async function main() { - //add-start - await prisma.user.create({ - data: { - name: 'Alice', - email: 'alice@prisma.io', - posts: { - create: { title: 'Hello World' }, - }, - profile: { - create: { bio: 'I like turtles' }, - }, - }, - }) - - const allUsers = await prisma.user.findMany({ - include: { - posts: true, - profile: true, - }, - }) - console.dir(allUsers, { depth: null }) - //add-end -} -``` - -This code creates a new `User` record together with new `Post` and `Profile` records using a [nested write](/orm/prisma-client/queries/relation-queries#nested-writes) query. The `User` record is connected to the two other ones via the `Post.author` ↔ `User.posts` and `Profile.user` ↔ `User.profile` [relation fields](/orm/prisma-schema/data-model/relations#relation-fields) respectively. - -Notice that you're passing the [`include`](/orm/prisma-client/queries/select-fields#return-nested-objects-by-selecting-relation-fields) option to `findMany` which tells Prisma Client to include the `posts` and `profile` relations on the returned `User` objects. - -Run the code with this command: - -```terminal copy -node index.js -``` - -The output should look similar to this: - -```js no-lines -[ - { - email: 'alice@prisma.io', - id: 1, - name: 'Alice', - posts: [ - { - content: null, - createdAt: 2020-03-21T16:45:01.246Z, - updatedAt: 2020-03-21T16:45:01.246Z, - id: 1, - published: false, - title: 'Hello World', - authorId: 1, - } - ], - profile: { - bio: 'I like turtles', - id: 1, - userId: 1, - } - } -] -``` - -The query added new records to the `User` and the `Post` tables: - -**User** - -| **id** | **email** | **name** | -| :----- | :------------------ | :-------- | -| `1` | `"alice@prisma.io"` | `"Alice"` | - -**Post** - -| **id** | **createdAt** | **updatedAt** | **title** | **content** | **published** | **authorId** | -| :----- | :------------------------- | :------------------------: | :-------------- | :---------- | :------------ | :----------- | -| `1` | `2020-03-21T16:45:01.246Z` | `2020-03-21T16:45:01.246Z` | `"Hello World"` | `null` | `false` | `1` | - -**Profile** - -| **id** | **bio** | **userId** | -| :----- | :----------------- | :--------- | -| `1` | `"I like turtles"` | `1` | - -> **Note**: The numbers in the `authorId` column on `Post` and `userId` column on `Profile` both reference the `id` column of the `User` table, meaning the `id` value `1` column therefore refers to the first (and only) `User` record in the database. - -Before moving on to the next section, you'll "publish" the `Post` record you just created using an `update` query. Adjust the `main` function as follows: - -```js file=index.js copy showLineNumbers -async function main() { - const post = await prisma.post.update({ - where: { id: 1 }, - data: { published: true }, - }) - console.log(post) -} -``` - -Now run the code using the same command as before: - -```terminal copy -node index.js -``` - -You will see the following output: - -```js no-lines -{ - id: 1, - title: 'Hello World', - content: null, - published: true, - authorId: 1 -} -``` - -The `Post` record with an `id` of `1` now got updated in the database: - -**Post** - -| **id** | **title** | **content** | **published** | **authorId** | -| :----- | :-------------- | :---------- | :------------ | :----------- | -| `1` | `"Hello World"` | `null` | `true` | `1` | - -Fantastic, you just wrote new data into your database for the first time using Prisma Client 🚀 diff --git a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database-node-mysql.mdx b/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database-node-mysql.mdx deleted file mode 100644 index 93e81725bc..0000000000 --- a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database-node-mysql.mdx +++ /dev/null @@ -1,205 +0,0 @@ ---- -title: 'Querying the database using JavaScript and MySQL' -sidebar_label: 'Querying the database' -metaTitle: 'Querying the database using JavaScript and MySQL' -metaDescription: 'Write data to and query the database using JavaScript and MySQL' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -hide_table_of_contents: true -sidebar_class_name: hidden-sidebar -pagination_prev: getting-started/setup-prisma/start-from-scratch/relational-databases/install-prisma-client-node-mysql -pagination_next: getting-started/setup-prisma/start-from-scratch/relational-databases/next-steps -slugSwitch: /getting-started/setup-prisma/start-from-scratch/relational-databases/querying-the-database- ---- - -## Write your first query with Prisma Client - -Now that you have generated [Prisma Client](/orm/prisma-client), you can start writing queries to read and write data in your database. For the purpose of this guide, you'll use a plain Node.js script to explore some basic features of Prisma Client. - -Create a new file named `index.js` and add the following code to it: - -```js file=index.js copy showLineNumbers -const { PrismaClient } = require('./generated/prisma') - -const prisma = new PrismaClient() - -async function main() { - // ... you will write your Prisma Client queries here -} - -main() - .then(async () => { - await prisma.$disconnect() - }) - .catch(async (e) => { - console.error(e) - await prisma.$disconnect() - process.exit(1) - }) -``` - -Here's a quick overview of the different parts of the code snippet: - -1. Import the `PrismaClient` constructor from the `@prisma/client` node module -1. Instantiate `PrismaClient` -1. Define an `async` function named `main` to send queries to the database -1. Call the `main` function -1. Close the database connections when the script terminates - -Inside the `main` function, add the following query to read all `User` records from the database and print the result: - -```js file=index.js highlight=2;delete|3,4; showLineNumbers -async function main() { - //delete-next-line - // ... you will write your Prisma Client queries here - //add-start - const allUsers = await prisma.user.findMany() - console.log(allUsers) - //add-end -} -``` - -Now run the code with this command: - -```terminal copy -node index.js -``` - -This should print an empty array because there are no `User` records in the database yet: - -```json no-lines -[] -``` - -## Write data into the database - -The `findMany` query you used in the previous section only _reads_ data from the database (although it was still empty). In this section, you'll learn how to write a query to _write_ new records into the `Post` and `User` tables. - -Adjust the `main` function to send a `create` query to the database: - -```js file=index.js highlight=2-21;add copy showLineNumbers -async function main() { - //add-start - await prisma.user.create({ - data: { - name: 'Alice', - email: 'alice@prisma.io', - posts: { - create: { title: 'Hello World' }, - }, - profile: { - create: { bio: 'I like turtles' }, - }, - }, - }) - - const allUsers = await prisma.user.findMany({ - include: { - posts: true, - profile: true, - }, - }) - console.dir(allUsers, { depth: null }) - //add-end -} -``` - -This code creates a new `User` record together with new `Post` and `Profile` records using a [nested write](/orm/prisma-client/queries/relation-queries#nested-writes) query. The `User` record is connected to the two other ones via the `Post.author` ↔ `User.posts` and `Profile.user` ↔ `User.profile` [relation fields](/orm/prisma-schema/data-model/relations#relation-fields) respectively. - -Notice that you're passing the [`include`](/orm/prisma-client/queries/select-fields#return-nested-objects-by-selecting-relation-fields) option to `findMany` which tells Prisma Client to include the `posts` and `profile` relations on the returned `User` objects. - -Run the code with this command: - -```terminal copy -node index.js -``` - -The output should look similar to this: - -```js no-lines -[ - { - email: 'alice@prisma.io', - id: 1, - name: 'Alice', - posts: [ - { - content: null, - createdAt: 2020-03-21T16:45:01.246Z, - updatedAt: 2020-03-21T16:45:01.246Z, - id: 1, - published: false, - title: 'Hello World', - authorId: 1, - } - ], - profile: { - bio: 'I like turtles', - id: 1, - userId: 1, - } - } -] -``` - -The query added new records to the `User` and the `Post` tables: - -**User** - -| **id** | **email** | **name** | -| :----- | :------------------ | :-------- | -| `1` | `"alice@prisma.io"` | `"Alice"` | - -**Post** - -| **id** | **createdAt** | **updatedAt** | **title** | **content** | **published** | **authorId** | -| :----- | :------------------------- | :------------------------: | :-------------- | :---------- | :------------ | :----------- | -| `1` | `2020-03-21T16:45:01.246Z` | `2020-03-21T16:45:01.246Z` | `"Hello World"` | `null` | `false` | `1` | - -**Profile** - -| **id** | **bio** | **userId** | -| :----- | :----------------- | :--------- | -| `1` | `"I like turtles"` | `1` | - -> **Note**: The numbers in the `authorId` column on `Post` and `userId` column on `Profile` both reference the `id` column of the `User` table, meaning the `id` value `1` column therefore refers to the first (and only) `User` record in the database. - -Before moving on to the next section, you'll "publish" the `Post` record you just created using an `update` query. Adjust the `main` function as follows: - -```js file=index.js copy showLineNumbers -async function main() { - const post = await prisma.post.update({ - where: { id: 1 }, - data: { published: true }, - }) - console.log(post) -} -``` - -Now run the code using the same command as before: - -```terminal copy -node index.js -``` - -You will see the following output: - -```js no-lines -{ - id: 1, - title: 'Hello World', - content: null, - published: true, - authorId: 1 -} -``` - -The `Post` record with an `id` of `1` now got updated in the database: - -**Post** - -| **id** | **title** | **content** | **published** | **authorId** | -| :----- | :-------------- | :---------- | :------------ | :----------- | -| `1` | `"Hello World"` | `null` | `true` | `1` | - -Fantastic, you just wrote new data into your database for the first time using Prisma Client 🚀 diff --git a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database-node-planetscale.mdx b/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database-node-planetscale.mdx deleted file mode 100644 index 6a8bec5c58..0000000000 --- a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database-node-planetscale.mdx +++ /dev/null @@ -1,206 +0,0 @@ ---- -title: 'Querying the database using JavaScript and PlanetScale' -sidebar_label: 'Querying the database' -metaTitle: 'Querying the database using JavaScript and PlanetScale' -metaDescription: 'Write data to and query the database using JavaScript and PlanetScale' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -hide_table_of_contents: true -sidebar_class_name: hidden-sidebar -pagination_prev: getting-started/setup-prisma/start-from-scratch/relational-databases/install-prisma-client-node-planetscale -pagination_next: getting-started/setup-prisma/start-from-scratch/relational-databases/next-steps -slugSwitch: /getting-started/setup-prisma/start-from-scratch/relational-databases/querying-the-database- ---- - -## Write your first query with Prisma Client - -Now that you have generated [Prisma Client](/orm/prisma-client), you can start writing queries to read and write data in your database. For the purpose of this guide, you'll use a plain Node.js script to explore some basic features of Prisma Client. - -Create a new file named `index.js` and add the following code to it: - -```js file=index.js copy showLineNumbers -const { PrismaClient } = require('./generated/prisma') - -const prisma = new PrismaClient() - -async function main() { - // ... you will write your Prisma Client queries here -} - -main() - .then(async () => { - await prisma.$disconnect() - }) - .catch(async (e) => { - console.error(e) - await prisma.$disconnect() - process.exit(1) - }) -``` - -Here's a quick overview of the different parts of the code snippet: - -1. Import the `PrismaClient` constructor from the `@prisma/client` node module -1. Instantiate `PrismaClient` -1. Define an `async` function named `main` to send queries to the database -1. Call the `main` function -1. Close the database connections when the script terminates - -Inside the `main` function, add the following query to read all `User` records from the database and print the result: - -```js file=index.js highlight=2;delete|3,4;add showLineNumbers -async function main() { - //delete-next-line - // ... you will write your Prisma Client queries here - //add-start - const allUsers = await prisma.user.findMany() - console.log(allUsers) - //add-end -} -``` - -Now run the code with this command: - -```terminal copy -node index.js -``` - -This should print an empty array because there are no `User` records in the database yet: - -```json no-lines -[] -``` - -## Write data into the database - -The `findMany` query you used in the previous section only _reads_ data from the database (although it was still empty). In this section, you'll learn how to write a query to _write_ new records into the `Post` and `User` tables. - -Adjust the `main` function to send a `create` query to the database: - -```js file=index.js highlight=2-21;add copy showLineNumbers -async function main() { - //add-start - await prisma.user.create({ - data: { - name: 'Alice', - email: 'alice@prisma.io', - posts: { - create: { title: 'Hello World' }, - }, - profile: { - create: { bio: 'I like turtles' }, - }, - }, - }) - - const allUsers = await prisma.user.findMany({ - include: { - posts: true, - profile: true, - }, - }) - console.dir(allUsers, { depth: null }) - //add-end -} -``` - -This code creates a new `User` record together with new `Post` and `Profile` records using a [nested write](/orm/prisma-client/queries/relation-queries#nested-writes) query. The `User` record is connected to the two other ones via the `Post.author` ↔ `User.posts` and `Profile.user` ↔ `User.profile` [relation fields](/orm/prisma-schema/data-model/relations#relation-fields) respectively. - -Notice that you're passing the [`include`](/orm/prisma-client/queries/select-fields#return-nested-objects-by-selecting-relation-fields) option to `findMany` which tells Prisma Client to include the `posts` and `profile` relations on the returned `User` objects. - -Run the code with this command: - -```terminal copy -node index.js -``` - -The output should look similar to this: - -```js no-lines -[ - { - email: 'alice@prisma.io', - id: 1, - name: 'Alice', - posts: [ - { - content: null, - createdAt: 2020-03-21T16:45:01.246Z, - updatedAt: 2020-03-21T16:45:01.246Z, - id: 1, - published: false, - title: 'Hello World', - authorId: 1, - } - ], - profile: { - bio: 'I like turtles', - id: 1, - userId: 1, - } - } -] -``` - -The query added new records to the `User` and the `Post` tables: - -**User** - -| **id** | **email** | **name** | -| :----- | :------------------ | :-------- | -| `1` | `"alice@prisma.io"` | `"Alice"` | - -**Post** - -| **id** | **createdAt** | **updatedAt** | **title** | **content** | **published** | **authorId** | -| :----- | :------------------------- | :------------------------: | :-------------- | :---------- | :------------ | :----------- | -| `1` | `2020-03-21T16:45:01.246Z` | `2020-03-21T16:45:01.246Z` | `"Hello World"` | `null` | `false` | `1` | - -**Profile** - -| **id** | **bio** | **userId** | -| :----- | :----------------- | :--------- | -| `1` | `"I like turtles"` | `1` | - -> **Note**: The numbers in the `authorId` column on `Post` and `userId` column on `Profile` both reference the `id` column of the `User` table, meaning the `id` value `1` column therefore refers to the first (and only) `User` record in the database. - -Before moving on to the next section, you'll "publish" the `Post` record you just created using an `update` query. Adjust the `main` function as follows: - - -```js file=index.js copy showLineNumbers -async function main() { - const post = await prisma.post.update({ - where: { id: 1 }, - data: { published: true }, - }) - console.log(post) -} -``` - -Now run the code using the same command as before: - -```terminal copy -node index.js -``` - -You will see the following output: - -```js no-lines -{ - id: 1, - title: 'Hello World', - content: null, - published: true, - authorId: 1 -} -``` - -The `Post` record with an `id` of `1` now got updated in the database: - -**Post** - -| **id** | **title** | **content** | **published** | **authorId** | -| :----- | :-------------- | :---------- | :------------ | :----------- | -| `1` | `"Hello World"` | `null` | `true` | `1` | - -Fantastic, you just wrote new data into your database for the first time using Prisma Client 🚀 diff --git a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database-node-postgresql.mdx b/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database-node-postgresql.mdx deleted file mode 100644 index 5f16c8481c..0000000000 --- a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database-node-postgresql.mdx +++ /dev/null @@ -1,206 +0,0 @@ ---- -title: 'Querying the database using JavaScript and PostgreSQL' -sidebar_label: 'Querying the database' -metaTitle: 'Querying the database using JavaScript and PostgreSQL' -metaDescription: 'Write data to and query the database using JavaScript and PostgreSQL' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -hide_table_of_contents: true -sidebar_class_name: hidden-sidebar -pagination_prev: getting-started/setup-prisma/start-from-scratch/relational-databases/install-prisma-client-node-postgresql -pagination_next: getting-started/setup-prisma/start-from-scratch/relational-databases/next-steps -slugSwitch: /getting-started/setup-prisma/start-from-scratch/relational-databases/querying-the-database- ---- - -## Write your first query with Prisma Client - -Now that you have generated [Prisma Client](/orm/prisma-client), you can start writing queries to read and write data in your database. For the purpose of this guide, you'll use a plain Node.js script to explore some basic features of Prisma Client. - -Create a new file named `index.js` and add the following code to it: - -```js file=index.js copy showLineNumbers -const { PrismaClient } = require('./generated/prisma') - -const prisma = new PrismaClient() - -async function main() { - // ... you will write your Prisma Client queries here -} - -main() - .then(async () => { - await prisma.$disconnect() - }) - .catch(async (e) => { - console.error(e) - await prisma.$disconnect() - process.exit(1) - }) -``` - -Here's a quick overview of the different parts of the code snippet: - -1. Import `PrismaClient` from the `output` directory specified in the `prisma init` command. -1. Instantiate `PrismaClient` -1. Define an `async` function named `main` to send queries to the database -1. Call the `main` function -1. Close the database connections when the script terminates - -Inside the `main` function, add the following query to read all `User` records from the database and print the result: - - -```js file=index.js highlight=2;delete|3,4;add showLineNumbers -async function main() { - //delete-next-line - // ... you will write your Prisma Client queries here - //add-start - const allUsers = await prisma.user.findMany() - console.log(allUsers) - //add-end -} -``` - -Now run the code with this command: - -```terminal copy -node index.js -``` - -This should print an empty array because there are no `User` records in the database yet: - -```json no-lines -[] -``` - -## Write data into the database - -The `findMany` query you used in the previous section only _reads_ data from the database (although it was still empty). In this section, you'll learn how to write a query to _write_ new records into the `Post` and `User` tables. - -Adjust the `main` function to send a `create` query to the database: - -```js file=index.js highlight=2-21;add copy showLineNumbers -async function main() { - //add-start - await prisma.user.create({ - data: { - name: 'Alice', - email: 'alice@prisma.io', - posts: { - create: { title: 'Hello World' }, - }, - profile: { - create: { bio: 'I like turtles' }, - }, - }, - }) - - const allUsers = await prisma.user.findMany({ - include: { - posts: true, - profile: true, - }, - }) - console.dir(allUsers, { depth: null }) - //add-end -} -``` - -This code creates a new `User` record together with new `Post` and `Profile` records using a [nested write](/orm/prisma-client/queries/relation-queries#nested-writes) query. The `User` record is connected to the two other ones via the `Post.author` ↔ `User.posts` and `Profile.user` ↔ `User.profile` [relation fields](/orm/prisma-schema/data-model/relations#relation-fields) respectively. - -Notice that you're passing the [`include`](/orm/prisma-client/queries/select-fields#return-nested-objects-by-selecting-relation-fields) option to `findMany` which tells Prisma Client to include the `posts` and `profile` relations on the returned `User` objects. - -Run the code with this command: - -```terminal copy -node index.js -``` - -The output should look similar to this: - -```js no-lines -[ - { - email: 'alice@prisma.io', - id: 1, - name: 'Alice', - posts: [ - { - content: null, - createdAt: 2020-03-21T16:45:01.246Z, - updatedAt: 2020-03-21T16:45:01.246Z, - id: 1, - published: false, - title: 'Hello World', - authorId: 1, - } - ], - profile: { - bio: 'I like turtles', - id: 1, - userId: 1, - } - } -] -``` - -The query added new records to the `User` and the `Post` tables: - -**User** - -| **id** | **email** | **name** | -| :----- | :------------------ | :-------- | -| `1` | `"alice@prisma.io"` | `"Alice"` | - -**Post** - -| **id** | **createdAt** | **updatedAt** | **title** | **content** | **published** | **authorId** | -| :----- | :------------------------- | :------------------------: | :-------------- | :---------- | :------------ | :----------- | -| `1` | `2020-03-21T16:45:01.246Z` | `2020-03-21T16:45:01.246Z` | `"Hello World"` | `null` | `false` | `1` | - -**Profile** - -| **id** | **bio** | **userId** | -| :----- | :----------------- | :--------- | -| `1` | `"I like turtles"` | `1` | - -> **Note**: The numbers in the `authorId` column on `Post` and `userId` column on `Profile` both reference the `id` column of the `User` table, meaning the `id` value `1` column therefore refers to the first (and only) `User` record in the database. - -Before moving on to the next section, you'll "publish" the `Post` record you just created using an `update` query. Adjust the `main` function as follows: - -```js file=index.js copy showLineNumbers -async function main() { - const post = await prisma.post.update({ - where: { id: 1 }, - data: { published: true }, - }) - console.log(post) -} -``` - -Now run the code using the same command as before: - -```terminal copy -node index.js -``` - -You will see the following output: - -```js no-lines -{ - id: 1, - title: 'Hello World', - content: null, - published: true, - authorId: 1 -} -``` - -The `Post` record with an `id` of `1` now got updated in the database: - -**Post** - -| **id** | **title** | **content** | **published** | **authorId** | -| :----- | :-------------- | :---------- | :------------ | :----------- | -| `1` | `"Hello World"` | `null` | `true` | `1` | - -Fantastic, you just wrote new data into your database for the first time using Prisma Client 🚀 diff --git a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database-node-sqlserver.mdx b/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database-node-sqlserver.mdx deleted file mode 100644 index 1fe0350537..0000000000 --- a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database-node-sqlserver.mdx +++ /dev/null @@ -1,205 +0,0 @@ ---- -title: 'Querying the database using JavaScript and SQL Server' -sidebar_label: 'Querying the database' -metaTitle: 'Querying the database using JavaScript and SQL Server' -metaDescription: 'Write data to and query the database using JavaScript and SQL Server' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -hide_table_of_contents: true -sidebar_class_name: hidden-sidebar -pagination_prev: getting-started/setup-prisma/start-from-scratch/relational-databases/install-prisma-client-node-sqlserver -pagination_next: getting-started/setup-prisma/start-from-scratch/relational-databases/next-steps -slugSwitch: /getting-started/setup-prisma/start-from-scratch/relational-databases/querying-the-database- ---- - -## Write your first query with Prisma Client - -Now that you have generated [Prisma Client](/orm/prisma-client), you can start writing queries to read and write data in your database. For the purpose of this guide, you'll use a plain Node.js script to explore some basic features of Prisma Client. - -Create a new file named `index.js` and add the following code to it: - -```js file=index.js copy showLineNumbers -const { PrismaClient } = require('./generated/prisma') - -const prisma = new PrismaClient() - -async function main() { - // ... you will write your Prisma Client queries here -} - -main() - .then(async () => { - await prisma.$disconnect() - }) - .catch(async (e) => { - console.error(e) - await prisma.$disconnect() - process.exit(1) - }) -``` - -Here's a quick overview of the different parts of the code snippet: - -1. Import the `PrismaClient` constructor from the `@prisma/client` node module -1. Instantiate `PrismaClient` -1. Define an `async` function named `main` to send queries to the database -1. Call the `main` function -1. Close the database connections when the script terminates - -Inside the `main` function, add the following query to read all `User` records from the database and print the result: - -```js file=index.js highlight=2;delete|3,4;add showLineNumbers -async function main() { - //delete-next-line - // ... you will write your Prisma Client queries here - //add-start - const allUsers = await prisma.user.findMany() - console.log(allUsers) - //add-end -} -``` - -Now run the code with this command: - -```terminal copy -node index.js -``` - -This should print an empty array because there are no `User` records in the database yet: - -```json no-lines -[] -``` - -## Write data into the database - -The `findMany` query you used in the previous section only _reads_ data from the database (although it was still empty). In this section, you'll learn how to write a query to _write_ new records into the `Post` and `User` tables. - -Adjust the `main` function to send a `create` query to the database: - -```js file=index.js highlight=2-21;add copy showLineNumbers -async function main() { - //add-start - await prisma.user.create({ - data: { - name: 'Alice', - email: 'alice@prisma.io', - posts: { - create: { title: 'Hello World' }, - }, - profile: { - create: { bio: 'I like turtles' }, - }, - }, - }) - - const allUsers = await prisma.user.findMany({ - include: { - posts: true, - profile: true, - }, - }) - console.dir(allUsers, { depth: null }) - //add-end -} -``` - -This code creates a new `User` record together with new `Post` and `Profile` records using a [nested write](/orm/prisma-client/queries/relation-queries#nested-writes) query. The `User` record is connected to the two other ones via the `Post.author` ↔ `User.posts` and `Profile.user` ↔ `User.profile` [relation fields](/orm/prisma-schema/data-model/relations#relation-fields) respectively. - -Notice that you're passing the [`include`](/orm/prisma-client/queries/select-fields#return-nested-objects-by-selecting-relation-fields) option to `findMany` which tells Prisma Client to include the `posts` and `profile` relations on the returned `User` objects. - -Run the code with this command: - -```terminal copy -node index.js -``` - -The output should look similar to this: - -```js no-lines -[ - { - email: 'alice@prisma.io', - id: 1, - name: 'Alice', - posts: [ - { - content: null, - createdAt: 2020-03-21T16:45:01.246Z, - updatedAt: 2020-03-21T16:45:01.246Z, - id: 1, - published: false, - title: 'Hello World', - authorId: 1, - } - ], - profile: { - bio: 'I like turtles', - id: 1, - userId: 1, - } - } -] -``` - -The query added new records to the `User` and the `Post` tables: - -**User** - -| **id** | **email** | **name** | -| :----- | :------------------ | :-------- | -| `1` | `"alice@prisma.io"` | `"Alice"` | - -**Post** - -| **id** | **createdAt** | **updatedAt** | **title** | **content** | **published** | **authorId** | -| :----- | :------------------------- | :------------------------: | :-------------- | :---------- | :------------ | :----------- | -| `1` | `2020-03-21T16:45:01.246Z` | `2020-03-21T16:45:01.246Z` | `"Hello World"` | `null` | `false` | `1` | - -**Profile** - -| **id** | **bio** | **userId** | -| :----- | :----------------- | :--------- | -| `1` | `"I like turtles"` | `1` | - -> **Note**: The numbers in the `authorId` column on `Post` and `userId` column on `Profile` both reference the `id` column of the `User` table, meaning the `id` value `1` column therefore refers to the first (and only) `User` record in the database. - -Before moving on to the next section, you'll "publish" the `Post` record you just created using an `update` query. Adjust the `main` function as follows: - -```js file=index.js copy showLineNumbers -async function main() { - const post = await prisma.post.update({ - where: { id: 1 }, - data: { published: true }, - }) - console.log(post) -} -``` - -Now run the code using the same command as before: - -```terminal copy -node index.js -``` - -You will see the following output: - -```js no-lines -{ - id: 1, - title: 'Hello World', - content: null, - published: true, - authorId: 1 -} -``` - -The `Post` record with an `id` of `1` now got updated in the database: - -**Post** - -| **id** | **title** | **content** | **published** | **authorId** | -| :----- | :-------------- | :---------- | :------------ | :----------- | -| `1` | `"Hello World"` | `null` | `true` | `1` | - -Fantastic, you just wrote new data into your database for the first time using Prisma Client 🚀 diff --git a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database-typescript-cockroachdb.mdx b/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database-typescript-cockroachdb.mdx deleted file mode 100644 index 381a3319f1..0000000000 --- a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database-typescript-cockroachdb.mdx +++ /dev/null @@ -1,220 +0,0 @@ ---- -title: 'Querying the database using TypeScript and CockroachDB' -sidebar_label: 'Querying the database' -metaTitle: 'Querying the database using TypeScript and CockroachDB' -metaDescription: 'Write data to and query the database using TypeScript and CockroachDB' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb', 'prismaPostgres'] -hide_table_of_contents: true -sidebar_class_name: hidden-sidebar -pagination_prev: getting-started/setup-prisma/start-from-scratch/relational-databases/install-prisma-client-typescript-cockroachdb -pagination_next: getting-started/setup-prisma/start-from-scratch/relational-databases/next-steps -slugSwitch: /getting-started/setup-prisma/start-from-scratch/relational-databases/querying-the-database- ---- - -## Write your first query with Prisma Client - -Now that you have generated [Prisma Client](/orm/prisma-client), you can start writing queries to read and write data in your database. For the purpose of this guide, you'll use a plain Node.js script to explore some basic features of Prisma Client. - -Create a new file named `index.ts` and add the following code to it: - -```js file=index.ts copy showLineNumbers -import { PrismaClient } from './generated/prisma' - -const prisma = new PrismaClient() - -async function main() { - // ... you will write your Prisma Client queries here -} - -main() - .then(async () => { - await prisma.$disconnect() - }) - .catch(async (e) => { - console.error(e) - await prisma.$disconnect() - process.exit(1) - }) -``` - -Here's a quick overview of the different parts of the code snippet: - -1. Import the `PrismaClient` constructor from the `@prisma/client` node module -1. Instantiate `PrismaClient` -1. Define an `async` function named `main` to send queries to the database -1. Call the `main` function -1. Close the database connections when the script terminates - -Inside the `main` function, add the following query to read all `User` records from the database and print the result: - -```ts file=index.ts highlight=3,4;add showLineNumbers -async function main() { - // ... you will write your Prisma Client queries here - //add-start - const allUsers = await prisma.user.findMany() - console.log(allUsers) - //add-end -} -``` - -Now run the code with this command: - -```terminal copy -npx tsx index.ts -``` - -This should print an empty array because there are no `User` records in the database yet: - -```json no-lines -[] -``` - -## Write data into the database - -The `findMany` query you used in the previous section only _reads_ data from the database (although it was still empty). In this section, you'll learn how to write a query to _write_ new records into the `Post` and `User` tables. - -Adjust the `main` function to send a `create` query to the database: - -```ts file=index.ts highlight=2-21;add copy showLineNumbers -async function main() { - //add-start - await prisma.user.create({ - data: { - name: 'Alice', - email: 'alice@prisma.io', - posts: { - create: { title: 'Hello World' }, - }, - profile: { - create: { bio: 'I like turtles' }, - }, - }, - }) - - const allUsers = await prisma.user.findMany({ - include: { - posts: true, - profile: true, - }, - }) - console.dir(allUsers, { depth: null }) - //add-end -} -``` - -This code creates a new `User` record together with new `Post` and `Profile` records using a [nested write](/orm/prisma-client/queries/relation-queries#nested-writes) query. The `User` record is connected to the two other ones via the `Post.author` ↔ `User.posts` and `Profile.user` ↔ `User.profile` [relation fields](/orm/prisma-schema/data-model/relations#relation-fields) respectively. - -Notice that you're passing the [`include`](/orm/prisma-client/queries/select-fields#return-nested-objects-by-selecting-relation-fields) option to `findMany` which tells Prisma Client to include the `posts` and `profile` relations on the returned `User` objects. - -Run the code with this command: - -```terminal copy -npx tsx index.ts -``` - -The output should look similar to this: - -```js no-lines -[ - { - email: 'alice@prisma.io', - id: 1, - name: 'Alice', - posts: [ - { - content: null, - createdAt: 2020-03-21T16:45:01.246Z, - updatedAt: 2020-03-21T16:45:01.246Z, - id: 1, - published: false, - title: 'Hello World', - authorId: 1, - } - ], - profile: { - bio: 'I like turtles', - id: 1, - userId: 1, - } - } -] -``` - -Also note that `allUsers` is _statically typed_ thanks to [Prisma Client's generated types](/orm/prisma-client/type-safety/operating-against-partial-structures-of-model-types). You can observe the type by hovering over the `allUsers` variable in your editor. It should be typed as follows: - -```ts no-lines -const allUsers: (User & { - posts: Post[] -})[] - -export type Post = { - id: number - title: string - content: string | null - published: boolean - authorId: number | null -} -``` - -The query added new records to the `User` and the `Post` tables: - -**User** - -| **id** | **email** | **name** | -| :----- | :------------------ | :-------- | -| `1` | `"alice@prisma.io"` | `"Alice"` | - -**Post** - -| **id** | **createdAt** | **updatedAt** | **title** | **content** | **published** | **authorId** | -| :----- | :------------------------- | :------------------------: | :-------------- | :---------- | :------------ | :----------- | -| `1` | `2020-03-21T16:45:01.246Z` | `2020-03-21T16:45:01.246Z` | `"Hello World"` | `null` | `false` | `1` | - -**Profile** - -| **id** | **bio** | **userId** | -| :----- | :----------------- | :--------- | -| `1` | `"I like turtles"` | `1` | - -> **Note**: The numbers in the `authorId` column on `Post` and `userId` column on `Profile` both reference the `id` column of the `User` table, meaning the `id` value `1` column therefore refers to the first (and only) `User` record in the database. - -Before moving on to the next section, you'll "publish" the `Post` record you just created using an `update` query. Adjust the `main` function as follows: - -```ts file=index.ts copy showLineNumbers -async function main() { - const post = await prisma.post.update({ - where: { id: 1 }, - data: { published: true }, - }) - console.log(post) -} -``` - -Now run the code using the same command as before: - -```terminal copy -npx tsx index.ts -``` - -You will see the following output: - -```js no-lines -{ - id: 1, - title: 'Hello World', - content: null, - published: true, - authorId: 1 -} -``` - -The `Post` record with an `id` of `1` now got updated in the database: - -**Post** - -| **id** | **title** | **content** | **published** | **authorId** | -| :----- | :-------------- | :---------- | :------------ | :----------- | -| `1` | `"Hello World"` | `null` | `true` | `1` | - -Fantastic, you just wrote new data into your database for the first time using Prisma Client 🚀 diff --git a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database-typescript-mysql.mdx b/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database-typescript-mysql.mdx deleted file mode 100644 index ee929e9772..0000000000 --- a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database-typescript-mysql.mdx +++ /dev/null @@ -1,220 +0,0 @@ ---- -title: 'Querying the database using TypeScript and MySQL' -sidebar_label: 'Querying the database' -metaTitle: 'Querying the database using TypeScript and MySQL' -metaDescription: 'Write data to and query the database using TypeScript and MySQL' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb', 'prismaPostgres'] -hide_table_of_contents: true -sidebar_class_name: hidden-sidebar -pagination_prev: getting-started/setup-prisma/start-from-scratch/relational-databases/install-prisma-client-typescript-mysql -pagination_next: getting-started/setup-prisma/start-from-scratch/relational-databases/next-steps -slugSwitch: /getting-started/setup-prisma/start-from-scratch/relational-databases/querying-the-database- ---- - -## Write your first query with Prisma Client - -Now that you have generated [Prisma Client](/orm/prisma-client), you can start writing queries to read and write data in your database. For the purpose of this guide, you'll use a plain Node.js script to explore some basic features of Prisma Client. - -Create a new file named `index.ts` and add the following code to it: - -```js file=index.ts copy showLineNumbers -import { PrismaClient } from './generated/prisma' - -const prisma = new PrismaClient() - -async function main() { - // ... you will write your Prisma Client queries here -} - -main() - .then(async () => { - await prisma.$disconnect() - }) - .catch(async (e) => { - console.error(e) - await prisma.$disconnect() - process.exit(1) - }) -``` - -Here's a quick overview of the different parts of the code snippet: - -1. Import the `PrismaClient` constructor from the `@prisma/client` node module -1. Instantiate `PrismaClient` -1. Define an `async` function named `main` to send queries to the database -1. Call the `main` function -1. Close the database connections when the script terminates - -Inside the `main` function, add the following query to read all `User` records from the database and print the result: - -```ts file=index.ts highlight=3,4;add showLineNumbers -async function main() { - // ... you will write your Prisma Client queries here - //add-start - const allUsers = await prisma.user.findMany() - console.log(allUsers) - //add-end -} -``` - -Now run the code with this command: - -```terminal copy -npx tsx index.ts -``` - -This should print an empty array because there are no `User` records in the database yet: - -```json no-lines -[] -``` - -## Write data into the database - -The `findMany` query you used in the previous section only _reads_ data from the database (although it was still empty). In this section, you'll learn how to write a query to _write_ new records into the `Post` and `User` tables. - -Adjust the `main` function to send a `create` query to the database: - -```ts file=index.ts highlight=2-21;add copy showLineNumbers -async function main() { - //add-start - await prisma.user.create({ - data: { - name: 'Alice', - email: 'alice@prisma.io', - posts: { - create: { title: 'Hello World' }, - }, - profile: { - create: { bio: 'I like turtles' }, - }, - }, - }) - - const allUsers = await prisma.user.findMany({ - include: { - posts: true, - profile: true, - }, - }) - console.dir(allUsers, { depth: null }) - //add-end -} -``` - -This code creates a new `User` record together with new `Post` and `Profile` records using a [nested write](/orm/prisma-client/queries/relation-queries#nested-writes) query. The `User` record is connected to the two other ones via the `Post.author` ↔ `User.posts` and `Profile.user` ↔ `User.profile` [relation fields](/orm/prisma-schema/data-model/relations#relation-fields) respectively. - -Notice that you're passing the [`include`](/orm/prisma-client/queries/select-fields#return-nested-objects-by-selecting-relation-fields) option to `findMany` which tells Prisma Client to include the `posts` and `profile` relations on the returned `User` objects. - -Run the code with this command: - -```terminal copy -npx tsx index.ts -``` - -The output should look similar to this: - -```js no-lines -[ - { - email: 'alice@prisma.io', - id: 1, - name: 'Alice', - posts: [ - { - content: null, - createdAt: 2020-03-21T16:45:01.246Z, - updatedAt: 2020-03-21T16:45:01.246Z, - id: 1, - published: false, - title: 'Hello World', - authorId: 1, - } - ], - profile: { - bio: 'I like turtles', - id: 1, - userId: 1, - } - } -] -``` - -Also note that `allUsers` is _statically typed_ thanks to [Prisma Client's generated types](/orm/prisma-client/type-safety/operating-against-partial-structures-of-model-types). You can observe the type by hovering over the `allUsers` variable in your editor. It should be typed as follows: - -```ts no-lines -const allUsers: (User & { - posts: Post[] -})[] - -export type Post = { - id: number - title: string - content: string | null - published: boolean - authorId: number | null -} -``` - -The query added new records to the `User` and the `Post` tables: - -**User** - -| **id** | **email** | **name** | -| :----- | :------------------ | :-------- | -| `1` | `"alice@prisma.io"` | `"Alice"` | - -**Post** - -| **id** | **createdAt** | **updatedAt** | **title** | **content** | **published** | **authorId** | -| :----- | :------------------------- | :------------------------: | :-------------- | :---------- | :------------ | :----------- | -| `1` | `2020-03-21T16:45:01.246Z` | `2020-03-21T16:45:01.246Z` | `"Hello World"` | `null` | `false` | `1` | - -**Profile** - -| **id** | **bio** | **userId** | -| :----- | :----------------- | :--------- | -| `1` | `"I like turtles"` | `1` | - -> **Note**: The numbers in the `authorId` column on `Post` and `userId` column on `Profile` both reference the `id` column of the `User` table, meaning the `id` value `1` column therefore refers to the first (and only) `User` record in the database. - -Before moving on to the next section, you'll "publish" the `Post` record you just created using an `update` query. Adjust the `main` function as follows: - -```ts file=index.ts copy showLineNumbers -async function main() { - const post = await prisma.post.update({ - where: { id: 1 }, - data: { published: true }, - }) - console.log(post) -} -``` - -Now run the code using the same command as before: - -```terminal copy -npx tsx index.ts -``` - -You will see the following output: - -```js no-lines -{ - id: 1, - title: 'Hello World', - content: null, - published: true, - authorId: 1 -} -``` - -The `Post` record with an `id` of `1` now got updated in the database: - -**Post** - -| **id** | **title** | **content** | **published** | **authorId** | -| :----- | :-------------- | :---------- | :------------ | :----------- | -| `1` | `"Hello World"` | `null` | `true` | `1` | - -Fantastic, you just wrote new data into your database for the first time using Prisma Client 🚀 diff --git a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database-typescript-planetscale.mdx b/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database-typescript-planetscale.mdx deleted file mode 100644 index b28afc292d..0000000000 --- a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database-typescript-planetscale.mdx +++ /dev/null @@ -1,221 +0,0 @@ ---- -title: 'Querying the database using TypeScript and PlanetScale' -sidebar_label: 'Querying the database' -metaTitle: 'Querying the database using TypeScript and PlanetScale' -metaDescription: 'Write data to and query the database using TypeScript and PlanetScale' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb', 'prismaPostgres'] -hide_table_of_contents: true -sidebar_class_name: hidden-sidebar -pagination_prev: getting-started/setup-prisma/start-from-scratch/relational-databases/install-prisma-client-typescript-planetscale -pagination_next: getting-started/setup-prisma/start-from-scratch/relational-databases/next-steps -slugSwitch: /getting-started/setup-prisma/start-from-scratch/relational-databases/querying-the-database- ---- - -## Write your first query with Prisma Client - -Now that you have generated [Prisma Client](/orm/prisma-client), you can start writing queries to read and write data in your database. For the purpose of this guide, you'll use a plain Node.js script to explore some basic features of Prisma Client. - -Create a new file named `index.ts` and add the following code to it: - -```js file=index.ts copy showLineNumbers -import { PrismaClient } from './generated/prisma' - -const prisma = new PrismaClient() - -async function main() { - // ... you will write your Prisma Client queries here -} - -main() - .then(async () => { - await prisma.$disconnect() - }) - .catch(async (e) => { - console.error(e) - await prisma.$disconnect() - process.exit(1) - }) -``` - -Here's a quick overview of the different parts of the code snippet: - -1. Import the `PrismaClient` constructor from the `@prisma/client` node module -1. Instantiate `PrismaClient` -1. Define an `async` function named `main` to send queries to the database -1. Call the `main` function -1. Close the database connections when the script terminates - -Inside the `main` function, add the following query to read all `User` records from the database and print the result: - -```ts file=index.ts highlight=3,4;add showLineNumbers -async function main() { - // ... you will write your Prisma Client queries here - //add-start - const allUsers = await prisma.user.findMany() - console.log(allUsers) - //add-end -} -``` - -Now run the code with this command: - -```terminal copy -npx tsx index.ts -``` - -This should print an empty array because there are no `User` records in the database yet: - -```json no-lines -[] -``` - -## Write data into the database - -The `findMany` query you used in the previous section only _reads_ data from the database (although it was still empty). In this section, you'll learn how to write a query to _write_ new records into the `Post` and `User` tables. - -Adjust the `main` function to send a `create` query to the database: - -```ts file=index.ts highlight=2-21;add copy showLineNumbers -async function main() { - //add-start - await prisma.user.create({ - data: { - name: 'Alice', - email: 'alice@prisma.io', - posts: { - create: { title: 'Hello World' }, - }, - profile: { - create: { bio: 'I like turtles' }, - }, - }, - }) - - const allUsers = await prisma.user.findMany({ - include: { - posts: true, - profile: true, - }, - }) - console.dir(allUsers, { depth: null }) - //add-end -} -``` - -This code creates a new `User` record together with new `Post` and `Profile` records using a [nested write](/orm/prisma-client/queries/relation-queries#nested-writes) query. The `User` record is connected to the two other ones via the `Post.author` ↔ `User.posts` and `Profile.user` ↔ `User.profile` [relation fields](/orm/prisma-schema/data-model/relations#relation-fields) respectively. - -Notice that you're passing the [`include`](/orm/prisma-client/queries/select-fields#return-nested-objects-by-selecting-relation-fields) option to `findMany` which tells Prisma Client to include the `posts` and `profile` relations on the returned `User` objects. - -Run the code with this command: - -```terminal copy -npx tsx index.ts -``` - -The output should look similar to this: - -```js no-lines -[ - { - email: 'alice@prisma.io', - id: 1, - name: 'Alice', - posts: [ - { - content: null, - createdAt: 2020-03-21T16:45:01.246Z, - updatedAt: 2020-03-21T16:45:01.246Z, - id: 1, - published: false, - title: 'Hello World', - authorId: 1, - } - ], - profile: { - bio: 'I like turtles', - id: 1, - userId: 1, - } - } -] -``` - -Also note that `allUsers` is _statically typed_ thanks to [Prisma Client's generated types](/orm/prisma-client/type-safety/operating-against-partial-structures-of-model-types). You can observe the type by hovering over the `allUsers` variable in your editor. It should be typed as follows: - -```ts no-lines -const allUsers: (User & { - posts: Post[] -})[] - -export type Post = { - id: number - title: string - content: string | null - published: boolean - authorId: number | null -} -``` - -The query added new records to the `User` and the `Post` tables: - -**User** - -| **id** | **email** | **name** | -| :----- | :------------------ | :-------- | -| `1` | `"alice@prisma.io"` | `"Alice"` | - -**Post** - -| **id** | **createdAt** | **updatedAt** | **title** | **content** | **published** | **authorId** | -| :----- | :------------------------- | :------------------------: | :-------------- | :---------- | :------------ | :----------- | -| `1` | `2020-03-21T16:45:01.246Z` | `2020-03-21T16:45:01.246Z` | `"Hello World"` | `null` | `false` | `1` | - -**Profile** - -| **id** | **bio** | **userId** | -| :----- | :----------------- | :--------- | -| `1` | `"I like turtles"` | `1` | - -> **Note**: The numbers in the `authorId` column on `Post` and `userId` column on `Profile` both reference the `id` column of the `User` table, meaning the `id` value `1` column therefore refers to the first (and only) `User` record in the database. - -Before moving on to the next section, you'll "publish" the `Post` record you just created using an `update` query. Adjust the `main` function as follows: - -```ts file=index.ts copy showLineNumbers -async function main() { - const post = await prisma.post.update({ - where: { id: 1 }, - data: { published: true }, - }) - console.log(post) -} -``` - -Now run the code using the same command as before: - -```terminal copy -npx tsx index.ts -``` - -You will see the following output: - -```js no-lines -{ - id: 1, - title: 'Hello World', - content: null, - published: true, - authorId: 1 -} -``` - -The `Post` record with an `id` of `1` now got updated in the database: - -**Post** - -| **id** | **title** | **content** | **published** | **authorId** | -| :----- | :-------------- | :---------- | :------------ | :----------- | -| `1` | `"Hello World"` | `null` | `true` | `1` | - -Fantastic, you just wrote new data into your database for the first time using Prisma Client 🚀 - diff --git a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database-typescript-postgresql.mdx b/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database-typescript-postgresql.mdx deleted file mode 100644 index 2765dd3411..0000000000 --- a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database-typescript-postgresql.mdx +++ /dev/null @@ -1,219 +0,0 @@ ---- -title: 'Querying the database using TypeScript and PostgreSQL' -sidebar_label: 'Querying the database' -metaTitle: 'Querying the database using TypeScript and PostgreSQL' -metaDescription: 'Write data to and query the database using TypeScript and PostgreSQL' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb', 'prismaPostgres'] -hide_table_of_contents: true -pagination_prev: getting-started/setup-prisma/start-from-scratch/relational-databases/install-prisma-client-typescript-postgresql -pagination_next: getting-started/setup-prisma/start-from-scratch/relational-databases/next-steps -slugSwitch: /getting-started/setup-prisma/start-from-scratch/relational-databases/querying-the-database- ---- - -## Write your first query with Prisma Client - -Now that you have generated [Prisma Client](/orm/prisma-client), you can start writing queries to read and write data in your database. For the purpose of this guide, you'll use a plain Node.js script to explore some basic features of Prisma Client. - -Create a new file named `index.ts` and add the following code to it: - -```js file=index.ts copy showLineNumbers -import { PrismaClient } from './generated/prisma' - -const prisma = new PrismaClient() - -async function main() { - // ... you will write your Prisma Client queries here -} - -main() - .then(async () => { - await prisma.$disconnect() - }) - .catch(async (e) => { - console.error(e) - await prisma.$disconnect() - process.exit(1) - }) -``` - -Here's a quick overview of the different parts of the code snippet: - -1. Import PrismaClient from output folder specified in [`prisma init`](/getting-started/setup-prisma/start-from-scratch/relational-databases-typescript-prismaPostgres) command. -1. Instantiate `PrismaClient` -1. Define an `async` function named `main` to send queries to the database -1. Call the `main` function -1. Close the database connections when the script terminates - -Inside the `main` function, add the following query to read all `User` records from the database and print the result: - -```ts file=index.ts highlight=3,4;add showLineNumbers -async function main() { - // ... you will write your Prisma Client queries here - //add-start - const allUsers = await prisma.user.findMany() - console.log(allUsers) - //add-end -} -``` - -Now run the code with this command: - -```terminal copy -npx tsx index.ts -``` - -This should print an empty array because there are no `User` records in the database yet: - -```json no-lines -[] -``` - -## Write data into the database - -The `findMany` query you used in the previous section only _reads_ data from the database (although it was still empty). In this section, you'll learn how to write a query to _write_ new records into the `Post` and `User` tables. - -Adjust the `main` function to send a `create` query to the database: - -```ts file=index.ts highlight=2-21;add copy showLineNumbers -async function main() { - //add-start - await prisma.user.create({ - data: { - name: 'Alice', - email: 'alice@prisma.io', - posts: { - create: { title: 'Hello World' }, - }, - profile: { - create: { bio: 'I like turtles' }, - }, - }, - }) - - const allUsers = await prisma.user.findMany({ - include: { - posts: true, - profile: true, - }, - }) - console.dir(allUsers, { depth: null }) - //add-end -} -``` - -This code creates a new `User` record together with new `Post` and `Profile` records using a [nested write](/orm/prisma-client/queries/relation-queries#nested-writes) query. The `User` record is connected to the two other ones via the `Post.author` ↔ `User.posts` and `Profile.user` ↔ `User.profile` [relation fields](/orm/prisma-schema/data-model/relations#relation-fields) respectively. - -Notice that you're passing the [`include`](/orm/prisma-client/queries/select-fields#return-nested-objects-by-selecting-relation-fields) option to `findMany` which tells Prisma Client to include the `posts` and `profile` relations on the returned `User` objects. - -Run the code with this command: - -```terminal copy -npx tsx index.ts -``` - -The output should look similar to this: - -```js no-lines -[ - { - email: 'alice@prisma.io', - id: 1, - name: 'Alice', - posts: [ - { - content: null, - createdAt: 2020-03-21T16:45:01.246Z, - updatedAt: 2020-03-21T16:45:01.246Z, - id: 1, - published: false, - title: 'Hello World', - authorId: 1, - } - ], - profile: { - bio: 'I like turtles', - id: 1, - userId: 1, - } - } -] -``` - -Also note that `allUsers` is _statically typed_ thanks to [Prisma Client's generated types](/orm/prisma-client/type-safety/operating-against-partial-structures-of-model-types). You can observe the type by hovering over the `allUsers` variable in your editor. It should be typed as follows: - -```ts no-lines -const allUsers: (User & { - posts: Post[] -})[] - -export type Post = { - id: number - title: string - content: string | null - published: boolean - authorId: number | null -} -``` - -The query added new records to the `User` and the `Post` tables: - -**User** - -| **id** | **email** | **name** | -| :----- | :------------------ | :-------- | -| `1` | `"alice@prisma.io"` | `"Alice"` | - -**Post** - -| **id** | **createdAt** | **updatedAt** | **title** | **content** | **published** | **authorId** | -| :----- | :------------------------- | :------------------------: | :-------------- | :---------- | :------------ | :----------- | -| `1` | `2020-03-21T16:45:01.246Z` | `2020-03-21T16:45:01.246Z` | `"Hello World"` | `null` | `false` | `1` | - -**Profile** - -| **id** | **bio** | **userId** | -| :----- | :----------------- | :--------- | -| `1` | `"I like turtles"` | `1` | - -> **Note**: The numbers in the `authorId` column on `Post` and `userId` column on `Profile` both reference the `id` column of the `User` table, meaning the `id` value `1` column therefore refers to the first (and only) `User` record in the database. - -Before moving on to the next section, you'll "publish" the `Post` record you just created using an `update` query. Adjust the `main` function as follows: - -```ts file=index.ts copy showLineNumbers -async function main() { - const post = await prisma.post.update({ - where: { id: 1 }, - data: { published: true }, - }) - console.log(post) -} -``` - -Now run the code using the same command as before: - -```terminal copy -npx tsx index.ts -``` - -You will see the following output: - -```js no-lines -{ - id: 1, - title: 'Hello World', - content: null, - published: true, - authorId: 1 -} -``` - -The `Post` record with an `id` of `1` now got updated in the database: - -**Post** - -| **id** | **title** | **content** | **published** | **authorId** | -| :----- | :-------------- | :---------- | :------------ | :----------- | -| `1` | `"Hello World"` | `null` | `true` | `1` | - -Fantastic, you just wrote new data into your database for the first time using Prisma Client 🚀 diff --git a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database-typescript-prismaPostgres.mdx b/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database-typescript-prismaPostgres.mdx deleted file mode 100644 index cd0f4852f5..0000000000 --- a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database-typescript-prismaPostgres.mdx +++ /dev/null @@ -1,243 +0,0 @@ ---- -title: 'Querying the database using TypeScript and Prisma Postgres' -sidebar_label: 'Querying the database' -metaTitle: 'Querying the database using TypeScript and Prisma Postgres' -metaDescription: 'Write data to and query the database using TypeScript and Prisma Postgres' -langSwitcher: ['typescript'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb', 'prismaPostgres'] -hide_table_of_contents: true -sidebar_class_name: hidden-sidebar -pagination_prev: getting-started/setup-prisma/start-from-scratch/relational-databases/install-prisma-client-typescript-prismaPostgres -pagination_next: getting-started/setup-prisma/start-from-scratch/relational-databases/next-steps -slugSwitch: /getting-started/setup-prisma/start-from-scratch/relational-databases/querying-the-database- ---- - -## Write your first query with Prisma Client - -Now that you have generated [Prisma Client](/orm/prisma-client), you can start writing queries to read and write data in your database. For the purpose of this guide, you'll use a plain TypeScript script to explore some basic features of Prisma Client. - -Create a new file named `queries.ts` and add the following code to it: - -```js file=queries.ts copy -// 1 -import { PrismaClient } from './generated/prisma' -import { withAccelerate } from '@prisma/extension-accelerate' - -// 2 -const prisma = new PrismaClient() - .$extends(withAccelerate()) - -// 3 -async function main() { - // ... you will write your Prisma Client queries here -} - -// 4 -main() - .then(async () => { - await prisma.$disconnect() - }) - .catch(async (e) => { - console.error(e) - // 5 - await prisma.$disconnect() - process.exit(1) - }) -``` - -Here's a quick overview of the different parts of the code snippet: - -1. Import the `PrismaClient` constructor and the `withAccelerate` extension. -1. Instantiate `PrismaClient` and add the Accelerate extension. -1. Define an `async` function named `main` to send queries to the database. -1. Call the `main` function. -1. Close the database connections when the script terminates. - -Inside the `main` function, add the following query to read all `User` records from the database and log the result: - -```ts file=queries.ts -async function main() { - //add-start - const allUsers = await prisma.user.findMany() - console.log(allUsers) - //add-end -} -``` - -Now run the code with this command: - -```terminal copy -npx tsx queries.ts -``` - -This should print an empty array because there are no `User` records in the database yet: - -```json no-lines -[] -``` - -## Write data into the database - -The `findMany` query you used in the previous section only _reads_ data from the database (although it was still empty). - -In this section, you'll learn how to write a query to _write_ new records into the `Post`, `User` and `Profile` tables all at once. - -Adjust the `main` function by removing the code from before and adding the following: - -```ts file=queries.ts highlight=2-21;add copy -async function main() { - //add-start - await prisma.user.create({ - data: { - name: 'Alice', - email: 'alice@prisma.io', - posts: { - create: { title: 'Hello World' }, - }, - profile: { - create: { bio: 'I like turtles' }, - }, - }, - }) - - const allUsers = await prisma.user.findMany({ - include: { - posts: true, - profile: true, - }, - }) - console.dir(allUsers, { depth: null }) - //add-end -} -``` - -This code creates a new `User` record together with new `Post` and `Profile` records using a [nested write](/orm/prisma-client/queries/relation-queries#nested-writes) query. - -The records are connected via the [relation fields](/orm/prisma-schema/data-model/relations#relation-fields) that you defined in your Prisma schema. - -Notice that you're also passing the [`include`](/orm/prisma-client/queries/select-fields#return-nested-objects-by-selecting-relation-fields) option to `findMany` which tells Prisma Client to include the `posts` and `profile` relations on the returned `User` objects. - -Run the code with this command: - -```terminal copy -npx tsx queries.ts -``` - -The output should look similar to this: - -```js no-copy showLineNumbers -[ - { - email: 'alice@prisma.io', - id: 1, - name: 'Alice', - posts: [ - { - content: null, - createdAt: 2020-03-21T16:45:01.246Z, - updatedAt: 2020-03-21T16:45:01.246Z, - id: 1, - published: false, - title: 'Hello World', - authorId: 1, - } - ], - profile: { - bio: 'I like turtles', - id: 1, - userId: 1, - } - } -] -``` - -Also note that the `allUsers` variable is _statically typed_ thanks to [Prisma Client's generated types](/orm/prisma-client/type-safety/operating-against-partial-structures-of-model-types). You can observe the type by hovering over the `allUsers` variable in your editor. It should be typed as follows: - -```ts no-copy showLineNumbers -const allUsers: ({ - posts: { - id: number; - createdAt: Date; - updatedAt: Date; - title: string; - content: string | null; - published: boolean; - authorId: number; - }[]; - profile: { - id: number; - bio: string | null; - userId: number; - } | null; -} & { - ...; -})[] -``` - -
-Expand for a visual view of the records that have been created - - -The query added new records to the `User`, `Post`, and `Profile` tables: - -**User** - -| **id** | **email** | **name** | -| :----- | :------------------ | :-------- | -| `1` | `"alice@prisma.io"` | `"Alice"` | - -**Post** - -| **id** | **createdAt** | **updatedAt** | **title** | **content** | **published** | **authorId** | -| :----- | :------------------------- | :------------------------: | :-------------- | :---------- | :------------ | :----------- | -| `1` | `2020-03-21T16:45:01.246Z` | `2020-03-21T16:45:01.246Z` | `"Hello World"` | `null` | `false` | `1` | - -**Profile** - -| **id** | **bio** | **userId** | -| :----- | :----------------- | :--------- | -| `1` | `"I like turtles"` | `1` | - -The numbers in the `authorId` column on `Post` and `userId` column on `Profile` both reference the `id` column of the `User` table, meaning the `id` value `1` column therefore refers to the first (and only) `User` record in the database. - -
- -Before moving on to the next section, you'll "publish" the `Post` record you just created using an `update` query. Adjust the `main` function as follows: - -```ts file=queries.ts copy -async function main() { - const post = await prisma.post.update({ - where: { id: 1 }, - data: { published: true }, - }) - console.log(post) -} -``` - -Now run the code using the same command as before: - -```terminal copy -npx tsx queries.ts -``` - -You will see the following output: - -```js no-lines -{ - id: 1, - title: 'Hello World', - content: null, - published: true, - authorId: 1 -} -``` - -The `Post` record with an `id` of `1` now got updated in the database: - -**Post** - -| **id** | **title** | **content** | **published** | **authorId** | -| :----- | :-------------- | :---------- | :------------ | :----------- | -| `1` | `"Hello World"` | `null` | `true` | `1` | - -Congratulations! You've now learned how to query a Prisma Postgres database with Prisma Client in your application. If you got lost along the way, want to learn about more queries or explore the caching feature of Prisma Accelerate, check out the comprehensive [Prisma starter template](https://github.com/prisma/prisma-examples/tree/latest/databases/prisma-postgres). \ No newline at end of file diff --git a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database-typescript-sqlserver.mdx b/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database-typescript-sqlserver.mdx deleted file mode 100644 index 3fd7f12046..0000000000 --- a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/250-querying-the-database-typescript-sqlserver.mdx +++ /dev/null @@ -1,222 +0,0 @@ ---- -title: 'Querying the database using TypeScript and SQL Server' -sidebar_label: 'Querying the database' -metaTitle: 'Querying the database using TypeScript and SQL Server' -metaDescription: 'Write data to and query the database using TypeScript and SQL Server' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb', 'prismaPostgres'] -hide_table_of_contents: true -sidebar_class_name: hidden-sidebar -pagination_prev: getting-started/setup-prisma/start-from-scratch/relational-databases/install-prisma-client-typescript-sqlserver -pagination_next: getting-started/setup-prisma/start-from-scratch/relational-databases/next-steps -slugSwitch: /getting-started/setup-prisma/start-from-scratch/relational-databases/querying-the-database- ---- - -## Write your first query with Prisma Client - -Now that you have generated [Prisma Client](/orm/prisma-client), you can start writing queries to read and write data in your database. For the purpose of this guide, you'll use a plain Node.js script to explore some basic features of Prisma Client. - -Create a new file named `index.ts` and add the following code to it: - -```js file=index.ts copy showLineNumbers -import { PrismaClient } from './generated/prisma' - -const prisma = new PrismaClient() - -async function main() { - // ... you will write your Prisma Client queries here -} - -main() - .then(async () => { - await prisma.$disconnect() - }) - .catch(async (e) => { - console.error(e) - await prisma.$disconnect() - process.exit(1) - }) -``` - -Here's a quick overview of the different parts of the code snippet: - -1. Import the `PrismaClient` constructor from the `@prisma/client` node module -1. Instantiate `PrismaClient` -1. Define an `async` function named `main` to send queries to the database -1. Call the `main` function -1. Close the database connections when the script terminates - -Inside the `main` function, add the following query to read all `User` records from the database and print the result: - -```ts file=index.ts highlight=3,4;add showLineNumbers -async function main() { - // ... you will write your Prisma Client queries here - //add-start - const allUsers = await prisma.user.findMany() - console.log(allUsers) - //add-end -} -``` - -Now run the code with this command: - -```terminal copy -npx tsx index.ts -``` - -This should print an empty array because there are no `User` records in the database yet: - -```json no-lines -[] -``` - -## Write data into the database - -The `findMany` query you used in the previous section only _reads_ data from the database (although it was still empty). In this section, you'll learn how to write a query to _write_ new records into the `Post` and `User` tables. - -Adjust the `main` function to send a `create` query to the database: - -```ts file=index.ts highlight=2-21;add copy showLineNumbers -async function main() { - //add-start - await prisma.user.create({ - data: { - name: 'Alice', - email: 'alice@prisma.io', - posts: { - create: { title: 'Hello World' }, - }, - profile: { - create: { bio: 'I like turtles' }, - }, - }, - }) - - const allUsers = await prisma.user.findMany({ - include: { - posts: true, - profile: true, - }, - }) - console.dir(allUsers, { depth: null }) - //add-end -} -``` - -This code creates a new `User` record together with new `Post` and `Profile` records using a [nested write](/orm/prisma-client/queries/relation-queries#nested-writes) query. The `User` record is connected to the two other ones via the `Post.author` ↔ `User.posts` and `Profile.user` ↔ `User.profile` [relation fields](/orm/prisma-schema/data-model/relations#relation-fields) respectively. - -Notice that you're passing the [`include`](/orm/prisma-client/queries/select-fields#return-nested-objects-by-selecting-relation-fields) option to `findMany` which tells Prisma Client to include the `posts` and `profile` relations on the returned `User` objects. - -Run the code with this command: - -```terminal copy -npx tsx index.ts -``` - -The output should look similar to this: - -```js no-lines -[ - { - email: 'alice@prisma.io', - id: 1, - name: 'Alice', - posts: [ - { - content: null, - createdAt: 2020-03-21T16:45:01.246Z, - updatedAt: 2020-03-21T16:45:01.246Z, - id: 1, - published: false, - title: 'Hello World', - authorId: 1, - } - ], - profile: { - bio: 'I like turtles', - id: 1, - userId: 1, - } - } -] -``` - -Also note that `allUsers` is _statically typed_ thanks to [Prisma Client's generated types](/orm/prisma-client/type-safety/operating-against-partial-structures-of-model-types). You can observe the type by hovering over the `allUsers` variable in your editor. It should be typed as follows: - -```ts no-lines -const allUsers: (User & { - posts: Post[] -})[] - -export type Post = { - id: number - title: string - content: string | null - published: boolean - authorId: number | null -} -``` - -The query added new records to the `User` and the `Post` tables: - -**User** - -| **id** | **email** | **name** | -| :----- | :------------------ | :-------- | -| `1` | `"alice@prisma.io"` | `"Alice"` | - -**Post** - -| **id** | **createdAt** | **updatedAt** | **title** | **content** | **published** | **authorId** | -| :----- | :------------------------- | :------------------------: | :-------------- | :---------- | :------------ | :----------- | -| `1` | `2020-03-21T16:45:01.246Z` | `2020-03-21T16:45:01.246Z` | `"Hello World"` | `null` | `false` | `1` | - -**Profile** - -| **id** | **bio** | **userId** | -| :----- | :----------------- | :--------- | -| `1` | `"I like turtles"` | `1` | - -> **Note**: The numbers in the `authorId` column on `Post` and `userId` column on `Profile` both reference the `id` column of the `User` table, meaning the `id` value `1` column therefore refers to the first (and only) `User` record in the database. - -Before moving on to the next section, you'll "publish" the `Post` record you just created using an `update` query. Adjust the `main` function as follows: - -```ts file=index.ts copy showLineNumbers -async function main() { - const post = await prisma.post.update({ - where: { id: 1 }, - data: { published: true }, - }) - console.log(post) -} -``` - -Now run the code using the same command as before: - -```terminal copy -npx tsx index.ts -``` - -You will see the following output: - -```js no-lines -{ - id: 1, - title: 'Hello World', - content: null, - published: true, - authorId: 1 -} -``` - -The `Post` record with an `id` of `1` now got updated in the database: - -**Post** - -| **id** | **title** | **content** | **published** | **authorId** | -| :----- | :-------------- | :---------- | :------------ | :----------- | -| `1` | `"Hello World"` | `null` | `true` | `1` | - -Fantastic, you just wrote new data into your database for the first time using Prisma Client 🚀 - - diff --git a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/300-next-steps.mdx b/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/300-next-steps.mdx deleted file mode 100644 index a8cae6ef57..0000000000 --- a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/300-next-steps.mdx +++ /dev/null @@ -1,100 +0,0 @@ ---- -title: 'Next steps with Prisma ORM and your relational database' -sidebar_label: 'Next steps' -metaTitle: 'Next steps after setting up Prisma ORM with your relational database' -metaDescription: 'Next steps to take now that you have successfully added Prisma ORM to your new TypeScript or JavaScript project' -hide_table_of_contents: true ---- - -This section lists a number of potential next steps you can now take from here. Feel free to explore these or read the [Introduction](/orm/overview/introduction/what-is-prisma) page to get a high-level overview of Prisma ORM. - -### Continue exploring the Prisma Client API - -You can send a variety of queries with the Prisma Client API. Check out the [API reference](/orm/prisma-client) and use your existing database setup from this guide to try them out. - -:::tip - -You can use your editor's auto-completion feature to learn about the different API calls and the arguments it takes. Auto-completion is commonly invoked by hitting CTRL+SPACE on your keyboard. - -::: - -
-Expand for more Prisma Client API examples - -Here are a few suggestions for a number of more queries you can send with Prisma Client: - -**Filter all `Post` records that contain `"hello"`** - -```js -const filteredPosts = await prisma.post.findMany({ - where: { - OR: [{ title: { contains: 'hello' } }, { content: { contains: 'hello' } }], - }, -}) -``` - -**Create a new `Post` record and connect it to an existing `User` record** - -```js -const post = await prisma.post.create({ - data: { - title: 'Join us for Prisma Day 2020', - author: { - connect: { email: 'alice@prisma.io' }, - }, - }, -}) -``` - -**Use the fluent relations API to retrieve the `Post` records of a `User` by traversing the relations** - -```js -const posts = await prisma.profile - .findUnique({ - where: { id: 1 }, - }) - .user() - .posts() -``` - -**Delete a `User` record** - -```js -const deletedUser = await prisma.user.delete({ - where: { email: 'sarah@prisma.io' }, -}) -``` - -
- -### Build an app with Prisma ORM - -The Prisma blog features comprehensive tutorials about Prisma ORM, check out our latest ones: - -- [Build a fullstack app with Next.js](https://www.youtube.com/watch?v=QXxy8Uv1LnQ&ab_channel=ByteGrad) -- [Build a fullstack app with Remix](https://www.prisma.io/blog/fullstack-remix-prisma-mongodb-1-7D0BfTXBmB6r) (5 parts, including videos) -- [Build a REST API with NestJS](https://www.prisma.io/blog/nestjs-prisma-rest-api-7D056s1BmOL0) - -### Explore the data in Prisma Studio - -Prisma Studio is a visual editor for the data in your database. Run `npx prisma studio` in your terminal. - -If you are using [Prisma Postgres](https://www.prisma.io/postgres), you can also directly use Prisma Studio inside the [Console](https://console.prisma.io) by selecting the **Studio** tab in your project. - -### Get query insights and analytics with Prisma Optimize - -[Prisma Optimize](/optimize) helps you generate insights and provides recommendations that can help you make your database queries faster. [Try it out now!](/optimize/getting-started) - -Optimize aims to help developers of all skill levels write efficient database queries, reducing database load and making applications more responsive. - -### Try a Prisma ORM example - -The [`prisma-examples`](https://github.com/prisma/prisma-examples/) repository contains a number of ready-to-run examples: - -| Demo | Stack | Description | -| :------------------------------------------------------------------------------------------------------------------ | :----------- | --------------------------------------------------------------------------------------------------- | -| [`nextjs`](https://pris.ly/e/orm/nextjs) | Fullstack | Simple [Next.js](https://nextjs.org/) app | -| [`nextjs-graphql`](https://pris.ly/e/ts/graphql-nextjs) | Fullstack | Simple [Next.js](https://nextjs.org/) app (React) with a GraphQL API | -| [`graphql-nexus`](https://pris.ly/e/ts/graphql-nexus) | Backend only | GraphQL server based on [`@apollo/server`](https://www.apollographql.com/docs/apollo-server) | -| [`express`](https://pris.ly/e/ts/rest-express) | Backend only | Simple REST API with Express.JS | -| [`grpc`](https://pris.ly/e/ts/grpc) | Backend only | Simple gRPC API | diff --git a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/_install-prisma-client-partial.mdx b/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/_install-prisma-client-partial.mdx deleted file mode 100644 index 2bf6ab6d15..0000000000 --- a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases/_install-prisma-client-partial.mdx +++ /dev/null @@ -1,25 +0,0 @@ -## Install and generate Prisma Client - -To get started with Prisma Client, first install the `@prisma/client` package: - -```terminal copy -npm install @prisma/client -``` - -Then, run `prisma generate` which reads your Prisma schema and generates the Prisma Client. - -```terminal copy -npx prisma generate -``` - -You can now import the `PrismaClient` constructor from the `@prisma/client` package to create an instance of Prisma Client to send queries to your database. You'll learn how to do that in the next section. - -:::note Good to know - -When you run `prisma generate`, you are actually creating code (TypeScript types, methods, queries, ...) that is tailored to _your_ Prisma schema file or files in the `prisma` directory. This means, that whenever you make changes to your Prisma schema file, you also need to update the Prisma Client. You can do this by running the `prisma generate` command. - -![Install and generate Prisma Client](/img/getting-started/prisma-client-install-and-generate.png) - -Whenever you update your Prisma schema, you will have to update your database schema using either `prisma migrate dev` or `prisma db push`. This will keep your database schema in sync with your Prisma schema. These commands will also run `prisma generate` under the hood to re-generate your Prisma Client. - -::: diff --git a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb-node-mongodb.mdx b/content/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb-node-mongodb.mdx deleted file mode 100644 index 13a23e4d08..0000000000 --- a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb-node-mongodb.mdx +++ /dev/null @@ -1,54 +0,0 @@ ---- -title: 'Start from scratch with Prisma ORM using MongoDB and JavaScript' -sidebar_label: 'MongoDB' -metaTitle: 'Start from scratch with Prisma ORM using MongoDB and JavaScript (15 min)' -metaDescription: 'Learn how to create a new Node.js project from scratch by connecting Prisma ORM to your MongoDB database and generating a Prisma Client for database access.' -hide_table_of_contents: true -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['mongodb'] -sidebar_custom_props: { badge: '15 min' } -sidebar_class_name: hidden-sidebar -pagination_next: getting-started/setup-prisma/start-from-scratch/mongodb/connect-your-database-node-mongodb -slugSwitch: /getting-started/setup-prisma/start-from-scratch/mongodb- ---- - -Learn how to create a new Node.js or TypeScript project from scratch by connecting Prisma ORM to your MongoDB database and generating a Prisma Client for database access. The following tutorial introduces you to the [Prisma CLI](/orm/tools/prisma-cli) and [Prisma Client](/orm/prisma-client). - -## Prerequisites - -In order to successfully complete this guide, you need: - -- [Node.js](https://nodejs.org/en/) installed on your machine (see [system requirements](/orm/reference/system-requirements) for officially supported versions) -- Access to a MongoDB 4.2+ server with a replica set deployment. We recommend using [MongoDB Atlas](https://www.mongodb.com/cloud/atlas). - - - - The MongoDB database connector uses transactions to support nested writes. Transactions **require** a [replica set](https://www.mongodb.com/docs/manual/tutorial/deploy-replica-set/) deployment. The easiest way to deploy a replica set is with [Atlas](https://www.mongodb.com/docs/atlas/getting-started/). It's free to get started. - - - -Make sure you have your database [connection URL](/orm/reference/connection-urls) at hand. If you don't have a database server running and just want to explore Prisma ORM, check out the [Quickstart](/getting-started/quickstart-sqlite). - -> See [System requirements](/orm/reference/system-requirements) for exact version requirements. - -## Create project setup - -As a first step, create a project directory and navigate into it: - -```terminal copy -mkdir hello-prisma -cd hello-prisma -``` - -Next, initialize a Node.js project and add the Prisma CLI as a development dependency to it: - -```terminal copy -npm init -y -npm install prisma --save-dev -``` - -This creates a `package.json` with an initial setup for a Node.js app. - -import PrismaInitPartial from './_prisma-init-partial.mdx' - - diff --git a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb-typescript-mongodb.mdx b/content/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb-typescript-mongodb.mdx deleted file mode 100644 index ed401e69f4..0000000000 --- a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb-typescript-mongodb.mdx +++ /dev/null @@ -1,59 +0,0 @@ ---- -title: 'Start from scratch with Prisma ORM using MongoDB and TypeScript' -sidebar_label: 'MongoDB' -metaTitle: 'Start from scratch with Prisma ORM using MongoDB and TypeScript (15 min)' -metaDescription: 'Learn how to create a new TypeScript project from scratch by connecting Prisma ORM to your MongoDB database and generating a Prisma Client for database access.' -hide_table_of_contents: true -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['mongodb'] -sidebar_custom_props: { badge: '15 min' } -pagination_next: getting-started/setup-prisma/start-from-scratch/mongodb/connect-your-database-typescript-mongodb -slugSwitch: /getting-started/setup-prisma/start-from-scratch/mongodb- ---- - -Learn how to create a new Node.js or TypeScript project from scratch by connecting Prisma ORM to your MongoDB database and generating a Prisma Client for database access. The following tutorial introduces you to the [Prisma CLI](/orm/tools/prisma-cli) and [Prisma Client](/orm/prisma-client). - -## Prerequisites - -In order to successfully complete this guide, you need: - -- [Node.js](https://nodejs.org/en/) installed on your machine (see [system requirements](/orm/reference/system-requirements) for officially supported versions) -- Access to a MongoDB 4.2+ server with a replica set deployment. We recommend using [MongoDB Atlas](https://www.mongodb.com/cloud/atlas). - - - - The MongoDB database connector uses transactions to support nested writes. Transactions **require** a [replica set](https://www.mongodb.com/docs/manual/tutorial/deploy-replica-set/) deployment. The easiest way to deploy a replica set is with [Atlas](https://www.mongodb.com/docs/atlas/getting-started/). It's free to get started. - - - -Make sure you have your database [connection URL](/orm/reference/connection-urls) at hand. If you don't have a database server running and just want to explore Prisma ORM, check out the [Quickstart](/getting-started/quickstart-sqlite). - -> See [System requirements](/orm/reference/system-requirements) for exact version requirements. - -## Create project setup - -As a first step, create a project directory and navigate into it: - -```terminal copy -mkdir hello-prisma -cd hello-prisma -``` - -Next, initialize a TypeScript project and add the Prisma CLI as a development dependency to it: - -```terminal copy -npm init -y -npm install prisma typescript tsx @types/node --save-dev -``` - -This creates a `package.json` with an initial setup for your TypeScript app. - -Next, initialize TypeScript: - -```terminal copy -npx tsc --init -``` - -import PrismaInitPartial from './_prisma-init-partial.mdx' - - diff --git a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb/100-connect-your-database-node-mongodb.mdx b/content/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb/100-connect-your-database-node-mongodb.mdx deleted file mode 100644 index c0af956fcc..0000000000 --- a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb/100-connect-your-database-node-mongodb.mdx +++ /dev/null @@ -1,55 +0,0 @@ ---- -title: 'Connect your database using JavaScript and MongoDB' -sidebar_label: 'Connect your database (MongoDB)' -metaTitle: 'Connect your database using JavaScript and MongoDB' -metaDescription: 'Connect your database to your project using JavaScript and MongoDB' -langSwitcher: ['typescript', 'node'] -sidebar_class_name: hidden-sidebar -dbSwitcher: ['mongodb'] -hide_table_of_contents: true -toc: false -pagination_prev: getting-started/setup-prisma/start-from-scratch/mongodb-node-mongodb -pagination_next: getting-started/setup-prisma/start-from-scratch/mongodb/creating-the-prisma-schema-node-mongodb -slugSwitch: /getting-started/setup-prisma/start-from-scratch/mongodb/connect-your-database- ---- - -To connect your database, you need to set the `url` field of the `datasource` block in your Prisma schema to your database [connection URL](/orm/reference/connection-urls): - -```prisma file=prisma/schema.prisma showLineNumbers -datasource db { - provider = "mongodb" - url = env("DATABASE_URL") -} -``` - -In this case, the `url` is [set via an environment variable](/orm/more/development-environment/environment-variables) which is defined in `.env` (the example uses a [MongoDB Atlas](https://www.mongodb.com/cloud/atlas) URL): - -```bash file=.env showLineNumbers -DATABASE_URL="mongodb+srv://test:test@cluster0.ns1yp.mongodb.net/myFirstDatabase" -``` - -You now need to adjust the connection URL to point to your own database. - -The [format of the connection URL](/orm/reference/connection-urls) for your database depends on the database you use. For MongoDB, it looks as follows (the parts spelled all-uppercased are _placeholders_ for your specific connection details): - -```no-lines -mongodb://USERNAME:PASSWORD@HOST:PORT/DATABASE -``` - -Here's a short explanation of each component: - -- `USERNAME`: The name of your database user -- `PASSWORD`: The password for your database user -- `HOST`: The host where a [`mongod`](https://www.mongodb.com/docs/manual/reference/program/mongod/#mongodb-binary-bin.mongod) (or [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos/#mongodb-binary-bin.mongos)) instance is running -- `PORT`: The port where your database server is running (typically `27017` for MongoDB) -- `DATABASE`: The name of the database. Note that if you're using MongoDB Atlas, you need to manually append the database name to the connection URL because the environment link from MongoDB Atlas doesn't contain it. - -## Troubleshooting - -### `Error in connector: SCRAM failure: Authentication failed.` - -If you see the `Error in connector: SCRAM failure: Authentication failed.` error message, you can specify the source database for the authentication by [adding](https://github.com/prisma/prisma/discussions/9994#discussioncomment-1562283) `?authSource=admin` to the end of the connection string. - -### `Raw query failed. Error code 8000 (AtlasError): empty database name not allowed.` - -If you see the `Raw query failed. Code: unknown. Message: Kind: Command failed: Error code 8000 (AtlasError): empty database name not allowed.` error message, be sure to append the database name to the database URL. You can find more info in this [GitHub issue](https://github.com/prisma/docs/issues/5562). \ No newline at end of file diff --git a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb/100-connect-your-database-typescript-mongodb.mdx b/content/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb/100-connect-your-database-typescript-mongodb.mdx deleted file mode 100644 index 82c326862a..0000000000 --- a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb/100-connect-your-database-typescript-mongodb.mdx +++ /dev/null @@ -1,53 +0,0 @@ ---- -title: 'Connect your database using TypeScript and MongoDB' -sidebar_label: 'Connect your database (MongoDB)' -metaTitle: 'Connect your database using TypeScript and MongoDB' -metaDescription: 'Connect your database to your project using TypeScript and MongoDB' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['mongodb'] -hide_table_of_contents: true -pagination_prev: getting-started/setup-prisma/start-from-scratch/mongodb-typescript-mongodb -pagination_next: getting-started/setup-prisma/start-from-scratch/mongodb/creating-the-prisma-schema-typescript-mongodb -slugSwitch: /getting-started/setup-prisma/start-from-scratch/mongodb/connect-your-database- ---- - -To connect your database, you need to set the `url` field of the `datasource` block in your Prisma schema to your database [connection URL](/orm/reference/connection-urls): - -```prisma file=prisma/schema.prisma showLineNumbers -datasource db { - provider = "mongodb" - url = env("DATABASE_URL") -} -``` - -In this case, the `url` is [set via an environment variable](/orm/more/development-environment/environment-variables) which is defined in `.env` (the example uses a [MongoDB Atlas](https://www.mongodb.com/cloud/atlas) URL): - -```bash file=.env showLineNumbers -DATABASE_URL="mongodb+srv://test:test@cluster0.ns1yp.mongodb.net/myFirstDatabase" -``` - -You now need to adjust the connection URL to point to your own database. - -The [format of the connection URL](/orm/reference/connection-urls) for your database depends on the database you use. For MongoDB, it looks as follows (the parts spelled all-uppercased are _placeholders_ for your specific connection details): - -```no-lines -mongodb://USERNAME:PASSWORD@HOST:PORT/DATABASE -``` - -Here's a short explanation of each component: - -- `USERNAME`: The name of your database user -- `PASSWORD`: The password for your database user -- `HOST`: The host where a [`mongod`](https://www.mongodb.com/docs/manual/reference/program/mongod/#mongodb-binary-bin.mongod) (or [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos/#mongodb-binary-bin.mongos)) instance is running -- `PORT`: The port where your database server is running (typically `27017` for MongoDB) -- `DATABASE`: The name of the database. Note that if you're using MongoDB Atlas, you need to manually append the database name to the connection URL because the environment link from MongoDB Atlas doesn't contain it. - -## Troubleshooting - -### `Error in connector: SCRAM failure: Authentication failed.` - -If you see the `Error in connector: SCRAM failure: Authentication failed.` error message, you can specify the source database for the authentication by [adding](https://github.com/prisma/prisma/discussions/9994#discussioncomment-1562283) `?authSource=admin` to the end of the connection string. - -### `Raw query failed. Error code 8000 (AtlasError): empty database name not allowed.` - -If you see the `Raw query failed. Code: unknown. Message: Kind: Command failed: Error code 8000 (AtlasError): empty database name not allowed.` error message, be sure to append the database name to the database URL. You can find more info in this [GitHub issue](https://github.com/prisma/docs/issues/5562). \ No newline at end of file diff --git a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb/125-creating-the-prisma-schema-node-mongodb.mdx b/content/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb/125-creating-the-prisma-schema-node-mongodb.mdx deleted file mode 100644 index a2bd0d3782..0000000000 --- a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb/125-creating-the-prisma-schema-node-mongodb.mdx +++ /dev/null @@ -1,68 +0,0 @@ ---- -title: 'Creating the Prisma schema using JavaScript and MongoDB' -sidebar_label: 'Creating the Prisma schema' -metaTitle: 'Creating the Prisma schema using JavaScript and MongoDB' -metaDescription: 'Update the Prisma schema for MongoDB with JavaScript' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['mongodb'] -hide_table_of_contents: true -sidebar_class_name: hidden-sidebar -pagination_prev: getting-started/setup-prisma/start-from-scratch/mongodb/connect-your-database-node-mongodb -pagination_next: getting-started/setup-prisma/start-from-scratch/mongodb/install-prisma-client-node-mongodb -slugSwitch: /getting-started/setup-prisma/start-from-scratch/mongodb/creating-the-prisma-schema- ---- - - -## Update the Prisma schema - -Open the `prisma/schema.prisma` file and replace the default contents with the following: - -```prisma file=prisma/schema.prisma showLineNumbers -datasource db { - provider = "mongodb" - url = env("DATABASE_URL") -} - -generator client { - provider = "prisma-client-js" -} - -model Post { - id String @id @default(auto()) @map("_id") @db.ObjectId - slug String @unique - title String - body String - author User @relation(fields: [authorId], references: [id]) - authorId String @db.ObjectId - comments Comment[] -} - -model User { - id String @id @default(auto()) @map("_id") @db.ObjectId - email String @unique - name String? - address Address? - posts Post[] -} - -model Comment { - id String @id @default(auto()) @map("_id") @db.ObjectId - comment String - post Post @relation(fields: [postId], references: [id]) - postId String @db.ObjectId -} - -// Address is an embedded document -type Address { - street String - city String - state String - zip String -} -``` - -There are also a number of subtle differences in how the schema is setup when compared to relational databases like PostgreSQL. - -For example, the underlying `ID` field name is always `_id` and must be mapped with `@map("_id")`. - -For more information check out the [MongoDB schema reference](/orm/reference/prisma-schema-reference#mongodb-2). diff --git a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb/125-creating-the-prisma-schema-typescript-mongodb.mdx b/content/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb/125-creating-the-prisma-schema-typescript-mongodb.mdx deleted file mode 100644 index fc255f746b..0000000000 --- a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb/125-creating-the-prisma-schema-typescript-mongodb.mdx +++ /dev/null @@ -1,67 +0,0 @@ ---- -title: 'Creating the Prisma schema using TypeScript and MongoDB' -sidebar_label: 'Creating the Prisma schema' -metaTitle: 'Creating the Prisma schema using TypeScript and MongoDB' -metaDescription: 'Update the Prisma schema for MongoDB with TypeScript' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['mongodb'] -hide_table_of_contents: true -pagination_prev: getting-started/setup-prisma/start-from-scratch/mongodb/connect-your-database-typescript-mongodb -pagination_next: getting-started/setup-prisma/start-from-scratch/mongodb/install-prisma-client-typescript-mongodb -slugSwitch: /getting-started/setup-prisma/start-from-scratch/mongodb/creating-the-prisma-schema- ---- - -## Update the Prisma schema - -Open the `prisma/schema.prisma` file and replace the default contents with the following: - -```prisma file=prisma/schema.prisma showLineNumbers -datasource db { - provider = "mongodb" - url = env("DATABASE_URL") -} - -generator client { - provider = "prisma-client-js" -} - -model Post { - id String @id @default(auto()) @map("_id") @db.ObjectId - slug String @unique - title String - body String - author User @relation(fields: [authorId], references: [id]) - authorId String @db.ObjectId - comments Comment[] -} - -model User { - id String @id @default(auto()) @map("_id") @db.ObjectId - email String @unique - name String? - address Address? - posts Post[] -} - -model Comment { - id String @id @default(auto()) @map("_id") @db.ObjectId - comment String - post Post @relation(fields: [postId], references: [id]) - postId String @db.ObjectId -} - -// Address is an embedded document -type Address { - street String - city String - state String - zip String -} -``` - -There are also a number of subtle differences in how the schema is setup when compared to relational databases like PostgreSQL. - -For example, the underlying `ID` field name is always `_id` and must be mapped with `@map("_id")`. - -For more information check out the [MongoDB schema reference](/orm/reference/prisma-schema-reference#mongodb-2). - diff --git a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb/200-install-prisma-client-node-mongodb.mdx b/content/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb/200-install-prisma-client-node-mongodb.mdx deleted file mode 100644 index 85dd430ade..0000000000 --- a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb/200-install-prisma-client-node-mongodb.mdx +++ /dev/null @@ -1,31 +0,0 @@ ---- -title: 'Install Prisma Client (JavaScript and MongoDB)' -sidebar_label: 'Install Prisma Client' -metaTitle: 'Install Prisma Client: JavaScript and MongoDB' -metaDescription: 'Install and generate Prisma Client in your project using JavaScript and MongoDB' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['mongodb'] -hide_table_of_contents: true -sidebar_class_name: hidden-sidebar -pagination_prev: getting-started/setup-prisma/start-from-scratch/mongodb/creating-the-prisma-schema-node-mongodb -pagination_next: getting-started/setup-prisma/start-from-scratch/mongodb/querying-the-database-node-mongodb -slugSwitch: /getting-started/setup-prisma/start-from-scratch/mongodb/install-prisma-client- ---- - -## Install and generate Prisma Client - -To get started with Prisma Client, you need to install the `@prisma/client` package: - -```terminal copy -npm install @prisma/client -``` - -Then, run `prisma generate` which reads your Prisma schema and generates the Prisma Client. - -```terminal copy -npx prisma generate -``` - -![Install and generate Prisma Client](/img/getting-started/prisma-client-install-and-generate.png) - -Whenever you update your Prisma schema, you will need to run the `prisma db push` command to create new indexes and regenerate Prisma Client. diff --git a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb/200-install-prisma-client-typescript-mongodb.mdx b/content/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb/200-install-prisma-client-typescript-mongodb.mdx deleted file mode 100644 index 1d1217095c..0000000000 --- a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb/200-install-prisma-client-typescript-mongodb.mdx +++ /dev/null @@ -1,30 +0,0 @@ ---- -title: 'Install Prisma Client (TypeScript and MongoDB)' -sidebar_label: 'Install Prisma Client' -metaTitle: 'Install Prisma Client: TypeScript and MongoDB' -metaDescription: 'Install and generate Prisma Client in your project using TypeScript and MongoDB' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['mongodb'] -hide_table_of_contents: true -pagination_prev: getting-started/setup-prisma/start-from-scratch/mongodb/creating-the-prisma-schema-typescript-mongodb -pagination_next: getting-started/setup-prisma/start-from-scratch/mongodb/querying-the-database-typescript-mongodb -slugSwitch: /getting-started/setup-prisma/start-from-scratch/mongodb/install-prisma-client- ---- - -## Install and generate Prisma Client - -To get started with Prisma Client, you need to install the `@prisma/client` package: - -```terminal copy -npm install @prisma/client -``` - -Then, run `prisma generate` which reads your Prisma schema and generates the Prisma Client. - -```terminal copy -npx prisma generate -``` - -![Install and generate Prisma Client](/img/getting-started/prisma-client-install-and-generate.png) - -Whenever you update your Prisma schema, you will need to run the `prisma db push` command to create new indexes and regenerate Prisma Client. diff --git a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb/250-querying-the-database-node-mongodb.mdx b/content/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb/250-querying-the-database-node-mongodb.mdx deleted file mode 100644 index 3e3afcb5db..0000000000 --- a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb/250-querying-the-database-node-mongodb.mdx +++ /dev/null @@ -1,217 +0,0 @@ ---- -title: 'Querying the database using JavaScript and MongoDB' -sidebar_label: 'Querying the database' -metaTitle: 'Querying the database with JavaScript and MongoDB' -metaDescription: 'Write data to and query the database using JavaScript and MongoDB' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['mongodb'] -hide_table_of_contents: true -sidebar_class_name: hidden-sidebar -pagination_prev: getting-started/setup-prisma/start-from-scratch/mongodb/install-prisma-client-node-mongodb -pagination_next: getting-started/setup-prisma/start-from-scratch/mongodb/next-steps -slugSwitch: /getting-started/setup-prisma/start-from-scratch/mongodb/querying-the-database- ---- - -## Write your first query with Prisma Client - -Now that you have generated Prisma Client, you can start writing queries to read and write data in your database. For the purpose of this guide, you'll use a plain Node.js script to explore some basic features of Prisma Client. - -Create a new file named `index.js` and add the following code to it: - -```js file=index.js copy showLineNumbers -const { PrismaClient } = require('@prisma/client') - -const prisma = new PrismaClient() - -async function main() { - // ... you will write your Prisma Client queries here -} - -main() - .then(async () => { - await prisma.$disconnect() - }) - .catch(async (e) => { - console.error(e) - await prisma.$disconnect() - process.exit(1) - }) -``` - -Here's a quick overview of the different parts of the code snippet: - -1. Import the `PrismaClient` constructor from the `@prisma/client` node module -1. Instantiate `PrismaClient` -1. Define an `async` function named `main` to send queries to the database -1. Connect to the database -1. Call the `main` function -1. Close the database connections when the script terminates - -Inside the `main` function, add the following query to read all `User` records from the database and print the result: - -```js file=index.js -async function main() { - //delete-next-line -- // ... you will write your Prisma Client queries here -//add-start -+ const allUsers = await prisma.user.findMany() -+ console.log(allUsers) -//add-end -} -``` - -Now run the code with this command: - -```terminal copy -node index.js -``` - -This should print an empty array because there are no `User` records in the database yet: - -```json no-lines -[] -``` - -## Write data into the database - -The `findMany` query you used in the previous section only _reads_ data from the database (although it was still empty). In this section, you'll learn how to write a query to _write_ new records into the `Post`, `User` and `Comment` tables. - -Adjust the `main` function to send a `create` query to the database: - -```js file=index.js highlight=2-21;add copy showLineNumbers -async function main() { - //add-start - await prisma.user.create({ - data: { - name: 'Rich', - email: 'hello@prisma.com', - posts: { - create: { - title: 'My first post', - body: 'Lots of really interesting stuff', - slug: 'my-first-post', - }, - }, - }, - }) - - const allUsers = await prisma.user.findMany({ - include: { - posts: true, - }, - }) - console.dir(allUsers, { depth: null }) - //add-end -} -``` - -This code creates a new `User` record together with a new `Post` using a [nested write](/orm/prisma-client/queries/relation-queries#nested-writes) query. The `User` record is connected to the other one via the `Post.author` ↔ `User.posts` [relation fields](/orm/prisma-schema/data-model/relations#relation-fields) respectively. - -Notice that you're passing the [`include`](/orm/prisma-client/queries/select-fields#return-nested-objects-by-selecting-relation-fields) option to `findMany` which tells Prisma Client to include the `posts` relations on the returned `User` objects. - -Run the code with this command: - -```terminal copy -node index.js -``` - -The output should look similar to this: - -```json no-lines -[ - { - id: '60cc9b0e001e3bfd00a6eddf', - email: 'hello@prisma.com', - name: 'Rich', - address: null, - posts: [ - { - id: '60cc9bad005059d6007f45dd', - slug: 'my-first-post', - title: 'My first post', - body: 'Lots of really interesting stuff', - userId: '60cc9b0e001e3bfd00a6eddf', - }, - ], - }, -] -``` - -The query added new records to the `User` and the `Post` tables: - -**User** - -| **id** | **email** | **name** | -| :------------------------- | :------------------- | :------- | -| `60cc9b0e001e3bfd00a6eddf` | `"hello@prisma.com"` | `"Rich"` | - -**Post** - -| **id** | **createdAt** | **title** | **content** | **published** | **authorId** | -| :------------------------- | :------------------------- | :---------------- | :--------------------------------- | :------------ | :------------------------- | -| `60cc9bad005059d6007f45dd` | `2020-03-21T16:45:01.246Z` | `"My first post"` | `Lots of really interesting stuff` | `false` | `60cc9b0e001e3bfd00a6eddf` | - -> **Note**: The unique IDs in the `authorId` column on `Post` reference the `id` column of the `User` table, meaning the `id` value `60cc9b0e001e3bfd00a6eddf` column therefore refers to the first (and only) `User` record in the database. - -Before moving on to the next section, you'll add a couple of comments to the `Post` record you just created using an `update` query. Adjust the `main` function as follows: - -```js file=index.js copy showLineNumbers -async function main() { - await prisma.post.update({ - where: { - slug: 'my-first-post', - }, - data: { - comments: { - createMany: { - data: [ - { comment: 'Great post!' }, - { comment: "Can't wait to read more!" }, - ], - }, - }, - }, - }) - const posts = await prisma.post.findMany({ - include: { - comments: true, - }, - }) - - console.dir(posts, { depth: Infinity }) -} -``` - -Now run the code using the same command as before: - -```terminal copy -node index.js -``` - -You will see the following output: - -```json no-lines -[ - { - id: '60cc9bad005059d6007f45dd', - slug: 'my-first-post', - title: 'My first post', - body: 'Lots of really interesting stuff', - userId: '60cc9b0e001e3bfd00a6eddf', - comments: [ - { - id: '60cca420008a21d800578793', - postId: '60cca40300af8bf000f6ca99', - comment: 'Great post!', - }, - { - id: '60cca420008a21d800578794', - postId: '60cca40300af8bf000f6ca99', - comment: "Can't wait to try this!", - }, - ], - }, -] -``` - -Fantastic, you just wrote new data into your database for the first time using Prisma Client 🚀 diff --git a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb/250-querying-the-database-typescript-mongodb.mdx b/content/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb/250-querying-the-database-typescript-mongodb.mdx deleted file mode 100644 index d0e5efac14..0000000000 --- a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb/250-querying-the-database-typescript-mongodb.mdx +++ /dev/null @@ -1,230 +0,0 @@ ---- -title: 'Querying the database using TypeScript and MongoDB' -sidebar_label: 'Querying the database' -metaTitle: 'Querying the database with TypeScript and MongoDB' -metaDescription: 'Write data to and query the database using TypeScript and MongoDB' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['mongodb'] -hide_table_of_contents: true -pagination_prev: getting-started/setup-prisma/start-from-scratch/mongodb/install-prisma-client-typescript-mongodb -pagination_next: getting-started/setup-prisma/start-from-scratch/mongodb/next-steps -slugSwitch: /getting-started/setup-prisma/start-from-scratch/mongodb/querying-the-database- ---- - -## Write your first query with Prisma Client - -Now that you have generated Prisma Client, you can start writing queries to read and write data in your database. For the purpose of this guide, you'll use a plain Node.js script to explore some basic features of Prisma Client. - -Create a new file named `index.ts` and add the following code to it: - -```js file=index.ts copy showLineNumbers -import { PrismaClient } from './generated/prisma' - -const prisma = new PrismaClient() - -async function main() { - // ... you will write your Prisma Client queries here -} - -main() - .catch(async (e) => { - console.error(e) - process.exit(1) - }) - .finally(async () => { - await prisma.$disconnect() - }) -``` - -Here's a quick overview of the different parts of the code snippet: - -1. Import the `PrismaClient` constructor from the `@prisma/client` node module -1. Instantiate `PrismaClient` -1. Define an `async` function named `main` to send queries to the database -1. Connect to the database -1. Call the `main` function -1. Close the database connections when the script terminates - -Inside the `main` function, add the following query to read all `User` records from the database and print the result: - -```ts file=index.ts showLineNumbers -async function main() { - // ... you will write your Prisma Client queries here -//add-start -+ const allUsers = await prisma.user.findMany() -+ console.log(allUsers) -//add-end -} -``` - -Now run the code with this command: - -```terminal copy -npx tsx index.ts -``` - -This should print an empty array because there are no `User` records in the database yet: - -```json no-lines -[] -``` - -## Write data into the database - -The `findMany` query you used in the previous section only _reads_ data from the database (although it was still empty). In this section, you'll learn how to write a query to _write_ new records into the `Post`, `User` and `Comment` tables. - -Adjust the `main` function to send a `create` query to the database: - -```ts file=index.ts highlight=2-21;add copy showLineNumbers -async function main() { - //add-start - await prisma.user.create({ - data: { - name: 'Rich', - email: 'hello@prisma.com', - posts: { - create: { - title: 'My first post', - body: 'Lots of really interesting stuff', - slug: 'my-first-post', - }, - }, - }, - }) - - const allUsers = await prisma.user.findMany({ - include: { - posts: true, - }, - }) - console.dir(allUsers, { depth: null }) - //add-end -} -``` - -This code creates a new `User` record together with a new `Post` using a [nested write](/orm/prisma-client/queries/relation-queries#nested-writes) query. The `User` record is connected to the other one via the `Post.author` ↔ `User.posts` [relation fields](/orm/prisma-schema/data-model/relations#relation-fields) respectively. - -Notice that you're passing the [`include`](/orm/prisma-client/queries/select-fields#return-nested-objects-by-selecting-relation-fields) option to `findMany` which tells Prisma Client to include the `posts` relations on the returned `User` objects. - -Run the code with this command: - -```terminal copy -npx tsx index.ts -``` - -The output should look similar to this: - -```json no-lines -[ - { - id: '60cc9b0e001e3bfd00a6eddf', - email: 'hello@prisma.com', - name: 'Rich', - address: null, - posts: [ - { - id: '60cc9bad005059d6007f45dd', - slug: 'my-first-post', - title: 'My first post', - body: 'Lots of really interesting stuff', - userId: '60cc9b0e001e3bfd00a6eddf', - }, - ], - }, -] -``` - -Also note that `allUsers` is _statically typed_ thanks to [Prisma Client's generated types](/orm/prisma-client/type-safety/operating-against-partial-structures-of-model-types). You can observe the type by hovering over the `allUsers` variable in your editor. It should be typed as follows: - -```ts no-lines -const allUsers: (User & { - posts: Post[] -})[] - -export type Post = { - id: number - title: string - body: string | null - published: boolean - authorId: number | null -} -``` - -The query added new records to the `User` and the `Post` tables: - -**User** - -| **id** | **email** | **name** | -| :------------------------- | :------------------- | :------- | -| `60cc9b0e001e3bfd00a6eddf` | `"hello@prisma.com"` | `"Rich"` | - -**Post** - -| **id** | **createdAt** | **title** | **content** | **published** | **authorId** | -| :------------------------- | :------------------------- | :---------------- | :--------------------------------- | :------------ | :------------------------- | -| `60cc9bad005059d6007f45dd` | `2020-03-21T16:45:01.246Z` | `"My first post"` | `Lots of really interesting stuff` | `false` | `60cc9b0e001e3bfd00a6eddf` | - -> **Note**: The unique IDs in the `authorId` column on `Post` reference the `id` column of the `User` table, meaning the `id` value `60cc9b0e001e3bfd00a6eddf` column therefore refers to the first (and only) `User` record in the database. - -Before moving on to the next section, you'll add a couple of comments to the `Post` record you just created using an `update` query. Adjust the `main` function as follows: - -```ts file=index.ts copy showLineNumbers -async function main() { - await prisma.post.update({ - where: { - slug: 'my-first-post', - }, - data: { - comments: { - createMany: { - data: [ - { comment: 'Great post!' }, - { comment: "Can't wait to read more!" }, - ], - }, - }, - }, - }) - const posts = await prisma.post.findMany({ - include: { - comments: true, - }, - }) - - console.dir(posts, { depth: Infinity }) -} -``` - -Now run the code using the same command as before: - -```terminal copy -npx tsx index.ts -``` - -You will see the following output: - -```json no-lines -[ - { - id: '60cc9bad005059d6007f45dd', - slug: 'my-first-post', - title: 'My first post', - body: 'Lots of really interesting stuff', - userId: '60cc9b0e001e3bfd00a6eddf', - comments: [ - { - id: '60cca420008a21d800578793', - postId: '60cca40300af8bf000f6ca99', - comment: 'Great post!', - }, - { - id: '60cca420008a21d800578794', - postId: '60cca40300af8bf000f6ca99', - comment: "Can't wait to try this!", - }, - ], - }, -] -``` - -Fantastic, you just wrote new data into your database for the first time using Prisma Client 🚀 diff --git a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb/300-next-steps.mdx b/content/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb/300-next-steps.mdx deleted file mode 100644 index 37b3d5384d..0000000000 --- a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb/300-next-steps.mdx +++ /dev/null @@ -1,94 +0,0 @@ ---- -title: 'Next steps after setting up Prisma ORM with MongoDB' -sidebar_label: 'Next steps' -metaTitle: 'Next steps after setting up Prisma ORM with MongoDB' -metaDescription: 'Next steps to take now that you have successfully added Prisma ORM to your new JavaScript or TypeScript project' -hide_table_of_contents: true ---- - -This section lists a number of potential next steps you can now take from here. Feel free to explore these or read the [Introduction](/orm/overview/introduction/what-is-prisma) page to get a high-level overview of Prisma ORM. - -### Continue exploring the Prisma Client API - -You can send a variety of queries with the Prisma Client API. Check out the [API reference](/orm/prisma-client) and use your existing database setup from this guide to try them out. - -:::tip - -You can use your editor's auto-completion feature to learn about the different API calls and the arguments it takes. Auto-completion is commonly invoked by hitting CTRL+SPACE on your keyboard. - -::: - -
-Expand for more Prisma Client API examples - -Here are a few suggestions for a number of more queries you can send with Prisma Client: - -**Filter all `Post` records that contain `"hello"`** - -```js -const filteredPosts = await prisma.post.findMany({ - where: { - OR: [{ title: { contains: 'hello' } }, { body: { contains: 'hello' } }], - }, -}) -``` - -**Create a new `Post` record and connect it to an existing `User` record** - -```js -const post = await prisma.post.create({ - data: { - title: 'Join us for Prisma Day 2020', - slug: 'prisma-day-2020', - body: 'A conference on modern application development and databases.', - user: { - connect: { email: 'hello@prisma.com' }, - }, - }, -}) -``` - -**Use the fluent relations API to retrieve the `Post` records of a `User` by traversing the relations** - -```js -const user = await prisma.comment - .findUnique({ - where: { id: '60ff4e9500acc65700ebf470' }, - }) - .post() - .user() -``` - -**Delete a `User` record** - -```js -const deletedUser = await prisma.user.delete({ - where: { email: 'sarah@prisma.io' }, -}) -``` - -
- -### Build an app with Prisma ORM - -The Prisma blog features comprehensive tutorials about Prisma ORM, check out our latest ones: - -- [Build a fullstack app with Next.js](https://www.youtube.com/watch?v=QXxy8Uv1LnQ&ab_channel=ByteGrad) -- [Build a fullstack app with Remix](https://www.prisma.io/blog/fullstack-remix-prisma-mongodb-1-7D0BfTXBmB6r) (5 parts, including videos) -- [Build a REST API with NestJS](https://www.prisma.io/blog/nestjs-prisma-rest-api-7D056s1BmOL0) - -### Explore the data in Prisma Studio - -Prisma Studio is a visual editor for the data in your database. Run `npx prisma studio` in your terminal. - -### Try a Prisma ORM example - -The [`prisma-examples`](https://github.com/prisma/prisma-examples/) repository contains a number of ready-to-run examples: - -| Demo | Stack | Description | -| :------------------------------------------------------------------------------------------------------------------ | :----------- | --------------------------------------------------------------------------------------------------- | -| [`nextjs`](https://pris.ly/e/orm/nextjs) | Fullstack | Simple [Next.js](https://nextjs.org/) app | -| [`nextjs-graphql`](https://pris.ly/e/ts/graphql-nextjs) | Fullstack | Simple [Next.js](https://nextjs.org/) app (React) with a GraphQL API | -| [`graphql-nexus`](https://pris.ly/e/ts/graphql-nexus) | Backend only | GraphQL server based on [`@apollo/server`](https://www.apollographql.com/docs/apollo-server) | -| [`express`](https://pris.ly/e/ts/rest-express) | Backend only | Simple REST API with Express.JS | -| [`grpc`](https://pris.ly/e/ts/grpc) | Backend only | Simple gRPC API | diff --git a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/_prisma-init-partial.mdx b/content/100-getting-started/02-setup-prisma/100-start-from-scratch/_prisma-init-partial.mdx deleted file mode 100644 index a77182b411..0000000000 --- a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/_prisma-init-partial.mdx +++ /dev/null @@ -1,27 +0,0 @@ -import CodeBlock from '@theme/CodeBlock'; - -You can now invoke the Prisma CLI by prefixing it with `npx`: - -```terminal -npx prisma -``` - -Next, set up your Prisma ORM project by creating your [Prisma Schema](/orm/prisma-schema) file with the following command: - -{`npx prisma init --datasource-provider ${props.datasource.toLowerCase()} --output ../generated/prisma`} - -This command does a few things: - -- Creates a new directory called `prisma` that contains a file called `schema.prisma`, which contains the Prisma Schema with your database connection variable and schema models. -- Sets the `datasource` to {props.datasource} and the output to a custom location, respectively. -- Creates the [`.env` file](/orm/more/development-environment/environment-variables) in the root directory of the project, which is used for defining environment variables (such as your database connection) - -Note that the default schema created by `prisma init` uses PostgreSQL as the `provider`. If you didn't specify a provider with the `datasource-provider` option, you need to edit the `datasource` block to use the {props.datasource.toLowerCase()} provider instead: - - -{`datasource db { - //edit-next-line - provider = "${props.datasource.toLowerCase()}" - url = env("DATABASE_URL") -}`} - \ No newline at end of file diff --git a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/index.mdx b/content/100-getting-started/02-setup-prisma/100-start-from-scratch/index.mdx deleted file mode 100644 index 455593e360..0000000000 --- a/content/100-getting-started/02-setup-prisma/100-start-from-scratch/index.mdx +++ /dev/null @@ -1,16 +0,0 @@ ---- -title: 'Start from scratch' -metaTitle: 'Start from scratch with Prisma ORM' -metaDescription: 'Learn how to create a new Node.js or TypeScript project from scratch by connecting Prisma ORM to your database of choice and generating a Prisma Client for database access.' -hide_table_of_contents: true ---- - - - -Start a fresh project from scratch with the following tutorials as they introduce you to the [Prisma CLI](/orm/tools/prisma-cli), [Prisma Client](/orm/prisma-client), and [Prisma Migrate](/orm/prisma-migrate). - - - -## In this section - - diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-node-cockroachdb.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-node-cockroachdb.mdx deleted file mode 100644 index 8faa0c838f..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-node-cockroachdb.mdx +++ /dev/null @@ -1,57 +0,0 @@ ---- -title: 'Add Prisma ORM to an existing project (JavaScript and CockroachDB)' -sidebar_label: 'Relational databases' -metaTitle: 'Add Prisma ORM to an existing project using JavaScript and CockroachDB (15 min)' -metaDescription: 'Learn how to add Prisma ORM to an existing Node.js project by connecting it to your CockroachDB database and generating a Prisma Client for database access.' -hide_table_of_contents: true -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -sidebar_custom_props: { badge: '15 min' } -sidebar_class_name: hidden-sidebar -pagination_next: getting-started/setup-prisma/add-to-existing-project/relational-databases/connect-your-database-node-cockroachdb -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/relational-databases- ---- - - - -Learn how to add Prisma ORM to an existing Node.js or TypeScript project by connecting it to your database and generating a Prisma Client for database access. The following tutorial introduces you to the [Prisma CLI](/orm/tools/prisma-cli), [Prisma Client](/orm/prisma-client), and [Prisma Introspection](/orm/prisma-schema/introspection). - - - -:::tip - -If you're migrating to Prisma ORM from another ORM, see our [Migrate from TypeORM](/guides/migrate-from-typeorm) or [Migrate from Sequelize](/guides/migrate-from-sequelize) migration guides. - -::: - -## Prerequisites - -In order to successfully complete this guide, you need: - -- an existing Node.js project with a `package.json` -- [Node.js](https://nodejs.org/en/) installed on your machine (see [system requirements](/orm/reference/system-requirements) for officially supported versions) -- a [CockroachDB](https://www.cockroachlabs.com) database server running and a database with at least one table - -> See [System requirements](/orm/reference/system-requirements) for exact version requirements. - -Make sure you have your database [connection URL](/orm/reference/connection-urls) (that includes your authentication credentials) at hand! If you don't have a database server running and just want to explore Prisma ORM, check out the [Quickstart](/getting-started/quickstart-sqlite). - -## Set up Prisma ORM - -As a first step, navigate into your project directory that contains the `package.json` file. - -Next, add the Prisma CLI as a development dependency to your project: - -```terminal copy -npm install prisma --save-dev -``` - -:::note - -If your project contains multiple directories with `package.json` files (e.g., `frontend`, `backend`, etc.), note that Prisma ORM is specifically designed for use in the API/backend layer. To set up Prisma, navigate to the appropriate backend directory containing the relevant `package.json` file and configure Prisma there. - -::: - -import PrismaInitPartial from './_prisma-init-partial.mdx' - - diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-node-mysql.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-node-mysql.mdx deleted file mode 100644 index 27577e96cf..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-node-mysql.mdx +++ /dev/null @@ -1,58 +0,0 @@ ---- -title: 'Add Prisma ORM to an existing JavaScript project (MySQL)' -sidebar_label: 'Relational databases' -metaTitle: 'Add Prisma ORM to an existing project using JavaScript and MySQL (15 min)' -metaDescription: 'Learn how to add Prisma ORM to an existing Node.js project by connecting it to your MySQL database and generating a Prisma Client for database access.' -hide_table_of_contents: true -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -sidebar_custom_props: { badge: '15 min' } -sidebar_class_name: hidden-sidebar -pagination_next: getting-started/setup-prisma/add-to-existing-project/relational-databases/connect-your-database-node-mysql -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/relational-databases- ---- - - - -Learn how to add Prisma ORM to an existing Node.js or TypeScript project by connecting it to your database and generating a Prisma Client for database access. The following tutorial introduces you to the [Prisma CLI](/orm/tools/prisma-cli), [Prisma Client](/orm/prisma-client), and [Prisma Introspection](/orm/prisma-schema/introspection). - - - -:::tip - -If you're migrating to Prisma ORM from another ORM, see our [Migrate from TypeORM](/guides/migrate-from-typeorm) or [Migrate from Sequelize](/guides/migrate-from-sequelize) migration guides. - -::: - -## Prerequisites - -In order to successfully complete this guide, you need: - -- an existing Node.js project with a `package.json` -- [Node.js](https://nodejs.org/en/) installed on your machine (see [system requirements](/orm/reference/system-requirements) for officially supported versions) -- a [MySQL](https://www.mysql.com/) database server running and a database with at least one table - - -> See [System requirements](/orm/reference/system-requirements) for exact version requirements. - -Make sure you have your database [connection URL](/orm/reference/connection-urls) (that includes your authentication credentials) at hand! If you don't have a database server running and just want to explore Prisma ORM, check out the [Quickstart](/getting-started/quickstart-sqlite). - -## Set up Prisma ORM - -As a first step, navigate into your project directory that contains the `package.json` file. - -Next, add the Prisma CLI as a development dependency to your project: - -```terminal copy -npm install prisma --save-dev -``` - -:::note - -If your project contains multiple directories with `package.json` files (e.g., `frontend`, `backend`, etc.), note that Prisma ORM is specifically designed for use in the API/backend layer. To set up Prisma, navigate to the appropriate backend directory containing the relevant `package.json` file and configure Prisma there. - -::: - -import PrismaInitPartial from './_prisma-init-partial.mdx' - - diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-node-planetscale.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-node-planetscale.mdx deleted file mode 100644 index d1f687604e..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-node-planetscale.mdx +++ /dev/null @@ -1,57 +0,0 @@ ---- -title: 'Add Prisma ORM to an existing JavaScript project (PlanetScale)' -sidebar_label: 'Relational databases' -metaTitle: 'Add Prisma ORM to an existing project using JavaScript and PlanetScale (15 min)' -metaDescription: 'Learn how to add Prisma ORM to an existing Node.js project by connecting it to your PlanetScale database and generating a Prisma Client for database access.' -hide_table_of_contents: true -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -sidebar_custom_props: { badge: '15 min' } -sidebar_class_name: hidden-sidebar -pagination_next: getting-started/setup-prisma/add-to-existing-project/relational-databases/connect-your-database-node-planetscale -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/relational-databases- ---- - - - -Learn how to add Prisma ORM to an existing Node.js or TypeScript project by connecting it to your database and generating a Prisma Client for database access. The following tutorial introduces you to the [Prisma CLI](/orm/tools/prisma-cli), [Prisma Client](/orm/prisma-client), and [Prisma Introspection](/orm/prisma-schema/introspection). - - - -:::tip - -If you're migrating to Prisma ORM from another ORM, see our [Migrate from TypeORM](/guides/migrate-from-typeorm) or [Migrate from Sequelize](/guides/migrate-from-sequelize) migration guides. - -::: - -## Prerequisites - -In order to successfully complete this guide, you need: - -- an existing Node.js project with a `package.json` -- [Node.js](https://nodejs.org/en/) installed on your machine (see [system requirements](/orm/reference/system-requirements) for officially supported versions) -- a [PlanetScale](https://planetscale.com/) database server running and a database with at least one table - -> See [System requirements](/orm/reference/system-requirements) for exact version requirements. - -Make sure you have your database [connection URL](/orm/reference/connection-urls) (that includes your authentication credentials) at hand! If you don't have a database server running and just want to explore Prisma ORM, check out the [Quickstart](/getting-started/quickstart-sqlite). - -## Set up Prisma ORM - -As a first step, navigate into your project directory that contains the `package.json` file. - -Next, add the Prisma CLI as a development dependency to your project: - -```terminal copy -npm install prisma --save-dev -``` - -:::note - -If your project contains multiple directories with `package.json` files (e.g., `frontend`, `backend`, etc.), note that Prisma ORM is specifically designed for use in the API/backend layer. To set up Prisma, navigate to the appropriate backend directory containing the relevant `package.json` file and configure Prisma there. - -::: - -import PrismaInitPartial from './_prisma-init-partial.mdx' - - diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-node-postgresql.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-node-postgresql.mdx deleted file mode 100644 index 73e178c8c5..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-node-postgresql.mdx +++ /dev/null @@ -1,58 +0,0 @@ ---- -title: 'Add Prisma ORM to an existing JavaScript project (PostgreSQL)' -sidebar_label: 'Relational databases' -metaTitle: 'Add Prisma ORM to an existing project that using JavaScript and PostgreSQL(15 min)' -metaDescription: 'Learn how to add Prisma ORM to an existing Node.js project by connecting it to your PostgreSQL database and generating a Prisma Client for database access.' -hide_table_of_contents: true -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -sidebar_custom_props: { badge: '15 min' } -sidebar_class_name: hidden-sidebar -pagination_next: getting-started/setup-prisma/add-to-existing-project/relational-databases/connect-your-database-node-postgresql -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/relational-databases- ---- - - - - -Learn how to add Prisma ORM to an existing Node.js or TypeScript project by connecting it to your database and generating a Prisma Client for database access. The following tutorial introduces you to the [Prisma CLI](/orm/tools/prisma-cli), [Prisma Client](/orm/prisma-client), and [Prisma Introspection](/orm/prisma-schema/introspection). - - - -:::tip - -If you're migrating to Prisma ORM from another ORM, see our [Migrate from TypeORM](/guides/migrate-from-typeorm) or [Migrate from Sequelize](/guides/migrate-from-sequelize) migration guides. - -::: - -## Prerequisites - -In order to successfully complete this guide, you need: - -- an existing Node.js project with a `package.json` -- [Node.js](https://nodejs.org/en/) installed on your machine (see [system requirements](/orm/reference/system-requirements) for officially supported versions) -- a [PostgreSQL](https://www.postgresql.org/) database server running and a database with at least one table - -> See [System requirements](/orm/reference/system-requirements) for exact version requirements. - -Make sure you have your database [connection URL](/orm/reference/connection-urls) (that includes your authentication credentials) at hand! If you don't have a database server running and just want to explore Prisma ORM, check out the [Quickstart](/getting-started/quickstart-sqlite). - -## Set up Prisma ORM - -As a first step, navigate into your project directory that contains the `package.json` file. - -Next, add the Prisma CLI as a development dependency to your project: - -```terminal copy -npm install prisma --save-dev -``` - -:::note - -If your project contains multiple directories with `package.json` files (e.g., `frontend`, `backend`, etc.), note that Prisma ORM is specifically designed for use in the API/backend layer. To set up Prisma, navigate to the appropriate backend directory containing the relevant `package.json` file and configure Prisma there. - -::: - -import PrismaInitPartial from './_prisma-init-partial.mdx' - - diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-node-sqlserver.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-node-sqlserver.mdx deleted file mode 100644 index 872be668d2..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-node-sqlserver.mdx +++ /dev/null @@ -1,58 +0,0 @@ ---- -title: 'Add Prisma ORM to an existing project (JavaScript and SQL Server)' -sidebar_label: 'Relational databases' -metaTitle: 'Add Prisma to an existing project using JavaScript and SQL Server (15 min)' -metaDescription: 'Learn how to add Prisma to an existing Node.js project by connecting it to your SQL Server database and generating a Prisma Client for database access.' -hide_table_of_contents: true -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -sidebar_custom_props: { badge: '15 min' } -pagination_next: getting-started/setup-prisma/add-to-existing-project/relational-databases/connect-your-database-node-sqlserver -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/relational-databases- ---- - - - -Learn how to add Prisma ORM to an existing Node.js or TypeScript project by connecting it to your database and generating a Prisma Client for database access. The following tutorial introduces you to the [Prisma CLI](/orm/tools/prisma-cli), [Prisma Client](/orm/prisma-client), and [Prisma Introspection](/orm/prisma-schema/introspection). - - - -:::tip - - -If you're migrating to Prisma ORM from another ORM, see our [Migrate from TypeORM](/guides/migrate-from-typeorm) or [Migrate from Sequelize](/guides/migrate-from-sequelize) migration guides. - -::: - -## Prerequisites - -In order to successfully complete this guide, you need: - -- [Node.js](https://nodejs.org/en/) installed on your machine (see [system requirements](/orm/reference/system-requirements) for officially supported versions) -- A [Microsoft SQL Server](https://learn.microsoft.com/en-us/sql/?view=sql-server-ver16) database - - [Microsoft SQL Server on Linux for Docker](/orm/overview/databases/sql-server/sql-server-docker) - - [Microsoft SQL Server on Windows (local)](/orm/overview/databases/sql-server/sql-server-local) - -> See [System requirements](/orm/reference/system-requirements) for exact version requirements. - -Make sure you have your database [connection URL](/orm/reference/connection-urls) (that includes your authentication credentials) at hand! If you don't have a database server running and just want to explore Prisma ORM, check out the [Quickstart](/getting-started/quickstart-sqlite). - -## Set up Prisma ORM - -As a first step, navigate into your project directory that contains the `package.json` file. - -Next, add the Prisma CLI as a development dependency to your project: - -```terminal copy -npm install prisma --save-dev -``` - -:::note - -If your project contains multiple directories with `package.json` files (e.g., `frontend`, `backend`, etc.), note that Prisma ORM is specifically designed for use in the API/backend layer. To set up Prisma, navigate to the appropriate backend directory containing the relevant `package.json` file and configure Prisma there. - -::: - -import PrismaInitPartial from './_prisma-init-partial.mdx' - - diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-typescript-cockroachdb.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-typescript-cockroachdb.mdx deleted file mode 100644 index adbdc5f8ae..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-typescript-cockroachdb.mdx +++ /dev/null @@ -1,58 +0,0 @@ ---- -title: 'Add Prisma ORM to an existing project (TypeScript and CockroachDB)' -sidebar_label: 'Relational databases' -metaTitle: 'Add Prisma ORM to an existing project using TypeScript and CockroachDB (15 min)' -metaDescription: 'Learn how to add Prisma ORM to an existing TypeScript project by connecting it to your CockroachDB database and generating a Prisma Client for database access.' -hide_table_of_contents: true -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -sidebar_custom_props: { badge: '15 min' } -sidebar_class_name: hidden-sidebar -pagination_next: getting-started/setup-prisma/add-to-existing-project/relational-databases/connect-your-database-typescript-cockroachdb -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/relational-databases- ---- - - - - -Learn how to add Prisma ORM to an existing Node.js or TypeScript project by connecting it to your database and generating a Prisma Client for database access. The following tutorial introduces you to the [Prisma CLI](/orm/tools/prisma-cli), [Prisma Client](/orm/prisma-client), and [Prisma Introspection](/orm/prisma-schema/introspection). - - - -:::tip - -If you're migrating to Prisma ORM from another ORM, see our [Migrate from TypeORM](/guides/migrate-from-typeorm) or [Migrate from Sequelize](/guides/migrate-from-sequelize) migration guides. - -::: - -## Prerequisites - -In order to successfully complete this guide, you need: - -- an existing Node.js project with a `package.json` -- [Node.js](https://nodejs.org/en/) installed on your machine (see [system requirements](/orm/reference/system-requirements) for officially supported versions) -- a [CockroachDB](https://www.cockroachlabs.com) database server running and a database with at least one table - -> See [System requirements](/orm/reference/system-requirements) for exact version requirements. - -Make sure you have your database [connection URL](/orm/reference/connection-urls) (that includes your authentication credentials) at hand! If you don't have a database server running and just want to explore Prisma ORM, check out the [Quickstart](/getting-started/quickstart-sqlite). - -## Set up Prisma ORM - -As a first step, navigate into your project directory that contains the `package.json` file. - -Next, add the Prisma CLI as a development dependency to your project: - -```terminal copy -npm install prisma --save-dev -``` - -:::note - -If your project contains multiple directories with `package.json` files (e.g., `frontend`, `backend`, etc.), note that Prisma ORM is specifically designed for use in the API/backend layer. To set up Prisma, navigate to the appropriate backend directory containing the relevant `package.json` file and configure Prisma there. - -::: - -import PrismaInitPartial from './_prisma-init-partial.mdx' - - diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-typescript-mysql.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-typescript-mysql.mdx deleted file mode 100644 index 1c89468762..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-typescript-mysql.mdx +++ /dev/null @@ -1,47 +0,0 @@ ---- -title: 'Add Prisma ORM to an existing project (TypeScript and MySQL)' -sidebar_label: 'Relational databases' -metaTitle: 'Integrate Prisma into a TypeScript Project with MySQL (15 min)' -metaDescription: 'Step-by-step guide to connecting a MySQL database to an existing TypeScript project using Prisma and generating a Prisma Client.' -hide_table_of_contents: true -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -sidebar_custom_props: { badge: '15 min' } -sidebar_class_name: hidden-sidebar -pagination_next: getting-started/setup-prisma/add-to-existing-project/relational-databases/connect-your-database-typescript-mysql -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/relational-databases- ---- - -## Overview - -This guide walks you through integrating Prisma ORM into an existing Node.js or TypeScript project. You'll learn how to: - -- Connect Prisma to your MySQL database -- Use the [Prisma CLI](/orm/tools/prisma-cli) -- Generate a [Prisma Client](/orm/prisma-client) for database access -- Introspect your existing database schema using [Prisma Introspection](/orm/prisma-schema/introspection) - -:::tip -Migrating from another ORM? Check out our dedicated guides for [TypeORM](/guides/migrate-from-typeorm) and [Sequelize](/guides/migrate-from-sequelize). -::: - -## Prerequisites - -Before you begin, ensure you have: - -- An existing Node.js project with a `package.json` file -- [Node.js](https://nodejs.org/en/) installed (see [system requirements](/orm/reference/system-requirements)) -- A running [MySQL](https://www.mysql.com/) database with at least one table - -> 📌 You'll need your [database connection URL](/orm/reference/connection-urls), including credentials. - -> 💡 Don’t have a database yet? Try our [Quickstart guide](/getting-started/quickstart-sqlite) with SQLite to explore Prisma ORM. - -## Step 1: Set Up Prisma - -1. Open your terminal and navigate to the project directory containing your `package.json`. - -2. Install Prisma CLI as a development dependency: - -```bash -npm install prisma --save-dev diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-typescript-planetscale.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-typescript-planetscale.mdx deleted file mode 100644 index b25b8800ab..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-typescript-planetscale.mdx +++ /dev/null @@ -1,57 +0,0 @@ ---- -title: 'Add Prisma ORM to an existing project (TypeScript and PlanetScale)' -sidebar_label: 'Relational databases' -metaTitle: 'Add Prisma ORM to an existing project using TypeScript and PlanetScale (15 min)' -metaDescription: 'Learn how to add Prisma ORM to an existing TypeScript project by connecting it to your PlanetScale database and generating a Prisma Client for database access.' -hide_table_of_contents: true -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -sidebar_custom_props: { badge: '15 min' } -sidebar_class_name: hidden-sidebar -pagination_next: getting-started/setup-prisma/add-to-existing-project/relational-databases/connect-your-database-typescript-planetscale -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/relational-databases- ---- - - - -Learn how to add Prisma ORM to an existing Node.js or TypeScript project by connecting it to your database and generating a Prisma Client for database access. The following tutorial introduces you to the [Prisma CLI](/orm/tools/prisma-cli), [Prisma Client](/orm/prisma-client), and [Prisma Introspection](/orm/prisma-schema/introspection). - - - -:::tip - -If you're migrating to Prisma ORM from another ORM, see our [Migrate from TypeORM](/guides/migrate-from-typeorm) or [Migrate from Sequelize](/guides/migrate-from-sequelize) migration guides. - -::: - -## Prerequisites - -In order to successfully complete this guide, you need: - -- an existing Node.js project with a `package.json` -- [Node.js](https://nodejs.org/en/) installed on your machine (see [system requirements](/orm/reference/system-requirements) for officially supported versions) -- a [PlanetScale](https://planetscale.com/) database server running and a database with at least one table - -> See [System requirements](/orm/reference/system-requirements) for exact version requirements. - -Make sure you have your database [connection URL](/orm/reference/connection-urls) (that includes your authentication credentials) at hand! If you don't have a database server running and just want to explore Prisma ORM, check out the [Quickstart](/getting-started/quickstart-sqlite). - -## Set up Prisma ORM - -As a first step, navigate into your project directory that contains the `package.json` file. - -Next, add the Prisma CLI as a development dependency to your project: - -```terminal copy -npm install prisma --save-dev -``` - -:::note - -If your project contains multiple directories with `package.json` files (e.g., `frontend`, `backend`, etc.), note that Prisma ORM is specifically designed for use in the API/backend layer. To set up Prisma, navigate to the appropriate backend directory containing the relevant `package.json` file and configure Prisma there. - -::: - -import PrismaInitPartial from './_prisma-init-partial.mdx' - - diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-typescript-postgresql.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-typescript-postgresql.mdx deleted file mode 100644 index 1fd554d7e4..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-typescript-postgresql.mdx +++ /dev/null @@ -1,57 +0,0 @@ ---- -title: 'Add Prisma ORM to an existing project (TypeScript and PostgreSQL)' -sidebar_label: 'Relational databases' -metaTitle: 'Add Prisma ORM to an existing project using TypeScript and PostgreSQL (15 min)' -metaDescription: 'Learn how to add Prisma ORM to an existing TypeScript project by connecting it to your PostgreSQL database and generating a Prisma Client for database access.' -hide_table_of_contents: true -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -sidebar_custom_props: { badge: '15 min' } -sidebar_class_name: hidden-sidebar -pagination_next: getting-started/setup-prisma/add-to-existing-project/relational-databases/connect-your-database-typescript-postgresql -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/relational-databases- ---- - - - -Learn how to add Prisma ORM to an existing Node.js or TypeScript project by connecting it to your database and generating a Prisma Client for database access. The following tutorial introduces you to the [Prisma CLI](/orm/tools/prisma-cli), [Prisma Client](/orm/prisma-client), and [Prisma Introspection](/orm/prisma-schema/introspection). - - - -:::tip - -If you're migrating to Prisma ORM from another ORM, see our [Migrate from TypeORM](/guides/migrate-from-typeorm) or [Migrate from Sequelize](/guides/migrate-from-sequelize) migration guides. - -::: - -## Prerequisites - -In order to successfully complete this guide, you need: - -- an existing Node.js project with a `package.json` -- [Node.js](https://nodejs.org/en/) installed on your machine (see [system requirements](/orm/reference/system-requirements) for officially supported versions) -- a [PostgreSQL](https://www.postgresql.org/) database server running and a database with at least one table - -> See [System requirements](/orm/reference/system-requirements) for exact version requirements. - -Make sure you have your database [connection URL](/orm/reference/connection-urls) (that includes your authentication credentials) at hand! If you don't have a database server running and just want to explore Prisma ORM, check out the [Quickstart](/getting-started/quickstart-sqlite). - -## Set up Prisma ORM - -As a first step, navigate into your project directory that contains the `package.json` file. - -Next, add the Prisma CLI as a development dependency to your project: - -```terminal copy -npm install prisma --save-dev -``` - -:::note - -If your project contains multiple directories with `package.json` files (e.g., `frontend`, `backend`, etc.), note that Prisma ORM is specifically designed for use in the API/backend layer. To set up Prisma, navigate to the appropriate backend directory containing the relevant `package.json` file and configure Prisma there. - -::: - -import PrismaInitPartial from './_prisma-init-partial.mdx' - - diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-typescript-sqlserver.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-typescript-sqlserver.mdx deleted file mode 100644 index a563f5dccc..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-typescript-sqlserver.mdx +++ /dev/null @@ -1,58 +0,0 @@ ---- -title: 'Add Prisma ORM to an existing project (TypeScript and SQL Server)' -sidebar_label: 'Relational databases' -metaTitle: 'Add Prisma ORM to an existing project using TypeScript and SQL Server (15 min)' -metaDescription: 'Learn how to add Prisma ORM to an existing TypeScript project by connecting it to your SQL Server database and generating a Prisma Client for database access.' -hide_table_of_contents: true -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -sidebar_custom_props: { badge: '15 min' } -sidebar_class_name: hidden-sidebar -pagination_next: getting-started/setup-prisma/add-to-existing-project/relational-databases/connect-your-database-typescript-sqlserver -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/relational-databases- ---- - - - -Learn how to add Prisma ORM to an existing Node.js or TypeScript project by connecting it to your database and generating a Prisma Client for database access. The following tutorial introduces you to the [Prisma CLI](/orm/tools/prisma-cli), [Prisma Client](/orm/prisma-client), and [Prisma Introspection](/orm/prisma-schema/introspection). - - - -:::tip - -If you're migrating to Prisma ORM from another ORM, see our [Migrate from TypeORM](/guides/migrate-from-typeorm) or [Migrate from Sequelize](/guides/migrate-from-sequelize) migration guides. - -::: - -## Prerequisites - -In order to successfully complete this guide, you need: - -- [Node.js](https://nodejs.org/en/) installed on your machine (see [system requirements](/orm/reference/system-requirements) for officially supported versions) -- A [Microsoft SQL Server](https://learn.microsoft.com/en-us/sql/?view=sql-server-ver16) database - - [Microsoft SQL Server on Linux for Docker](/orm/overview/databases/sql-server/sql-server-docker) - - [Microsoft SQL Server on Windows (local)](/orm/overview/databases/sql-server/sql-server-local) - -> See [System requirements](/orm/reference/system-requirements) for exact version requirements. - -Make sure you have your database [connection URL](/orm/reference/connection-urls) (that includes your authentication credentials) at hand! If you don't have a database server running and just want to explore Prisma ORM, check out the [Quickstart](/getting-started/quickstart-sqlite). - -## Set up Prisma ORM - -As a first step, navigate into your project directory that contains the `package.json` file. - -Next, add the Prisma CLI as a development dependency to your project: - -```terminal copy -npm install prisma --save-dev -``` - -:::note - -If your project contains multiple directories with `package.json` files (e.g., `frontend`, `backend`, etc.), note that Prisma ORM is specifically designed for use in the API/backend layer. To set up Prisma, navigate to the appropriate backend directory containing the relevant `package.json` file and configure Prisma there. - -::: - -import PrismaInitPartial from './_prisma-init-partial.mdx' - - diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/100-connect-your-database-node-cockroachdb.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/100-connect-your-database-node-cockroachdb.mdx deleted file mode 100644 index 3ce1f6f2d0..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/100-connect-your-database-node-cockroachdb.mdx +++ /dev/null @@ -1,59 +0,0 @@ ---- -title: 'Connect your existing database using JavaScript and CockroachDB' -sidebar_label: 'Connect your database' -metaTitle: 'Connect your existing database using JavaScript and CockroachDB' -metaDescription: 'Connect your database to your existing project using JavaScript and CockroachDB' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -toc: false -hide_table_of_contents: true -sidebar_class_name: hidden-sidebar -pagination_prev: getting-started/setup-prisma/add-to-existing-project/relational-databases-node-cockroachdb -pagination_next: getting-started/setup-prisma/add-to-existing-project/relational-databases/introspection-node-cockroachdb -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/relational-databases/connect-your-database- ---- - -## Connecting your database - -To connect your database, you need to set the `url` field of the `datasource` block in your Prisma schema to your database [connection URL](/orm/reference/connection-urls): - -```prisma file=prisma/schema.prisma showLineNumbers -datasource db { - provider = "postgresql" - url = env("DATABASE_URL") -} -``` - -The `url` is [set via an environment variable](/orm/more/development-environment/environment-variables) which is defined in `.env`. You now need to adjust the connection URL to point to your own database. - -

Connection URL

- -The [format of the connection URL](/orm/reference/connection-urls) for your database depends on the database you use. CockroachDB uses the PostgreSQL connection URL format, which has the following structure (the parts spelled all-uppercased are _placeholders_ for your specific connection details): - -```no-lines -postgresql://USER:PASSWORD@HOST:PORT/DATABASE?PARAMETERS -``` - -Here's a short explanation of each component: - -- `USER`: The name of your database user -- `PASSWORD`: The password for your database user -- `PORT`: The port where your database server is running. The default for CockroachDB is `26257`. -- `DATABASE`: The name of the database -- `PARAMETERS`: Any additional connection parameters. See the CockroachDB documentation [here](https://www.cockroachlabs.com/docs/stable/connection-parameters.html#additional-connection-parameters). - -For a [CockroachDB Serverless](https://www.cockroachlabs.com/docs/cockroachcloud/quickstart.html) or [Cockroach Dedicated](https://www.cockroachlabs.com/docs/cockroachcloud/quickstart-trial-cluster) database hosted on [CockroachDB Cloud](https://www.cockroachlabs.com/docs/cockroachcloud/quickstart/), the [connection URL](/orm/reference/connection-urls) looks similar to this: - -```bash file=.env -DATABASE_URL="postgresql://:@..cockroachlabs.cloud:26257/defaultdb?sslmode=verify-full&sslrootcert=$HOME/.postgresql/root.crt&options=--" -``` - -To find your connection string on CockroachDB Cloud, click the 'Connect' button on the overview page for your database cluster, and select the 'Connection string' tab. - -For a [CockroachDB database hosted locally](https://www.cockroachlabs.com/docs/stable/secure-a-cluster.html), the [connection URL](/orm/reference/connection-urls) looks similar to this: - -```bash file=.env -DATABASE_URL="postgresql://root@localhost:26257?sslmode=disable" -``` - -Your connection string is displayed as part of the welcome text when starting CockroachDB from the command line. diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/100-connect-your-database-node-mysql.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/100-connect-your-database-node-mysql.mdx deleted file mode 100644 index 6f9b36cfb5..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/100-connect-your-database-node-mysql.mdx +++ /dev/null @@ -1,60 +0,0 @@ ---- -title: 'Connect your existing database using JavaScript and MySQL' -sidebar_label: 'Connect your database' -metaTitle: 'Connect your existing database using JavaScript and MySQL' -metaDescription: 'Connect your database to your existing project using JavaScript and MySQL' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -sidebar_class_name: hidden-sidebar -hide_table_of_contents: true -toc: false -pagination_prev: getting-started/setup-prisma/add-to-existing-project/relational-databases-node-mysql -pagination_next: getting-started/setup-prisma/add-to-existing-project/relational-databases/introspection-node-mysql -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/relational-databases/connect-your-database- ---- - -## Connecting your database - -To connect your database, you need to set the `url` field of the `datasource` block in your Prisma schema to your database [connection URL](/orm/reference/connection-urls): - -```prisma file=prisma/schema.prisma showLineNumbers -datasource db { - provider = "mysql" - url = env("DATABASE_URL") -} -``` - -In this case, the `url` is [set via an environment variable](/orm/prisma-schema/overview#accessing-environment-variables-from-the-schema) which is defined in `.env`: - -```bash file=.env -DATABASE_URL="mysql://johndoe:randompassword@localhost:3306/mydb" -``` - -You now need to adjust the connection URL to point to your own database. - -

Connection URL

- -The [format of the connection URL](/orm/reference/connection-urls) for your database typically depends on the database you use. For MySQL, it looks as follows (the parts spelled all-uppercased are _placeholders_ for your specific connection details): - -```no-lines -mysql://USER:PASSWORD@HOST:PORT/DATABASE -``` - -Here's a short explanation of each component: - -- `USER`: The name of your database user -- `PASSWORD`: The password for your database user -- `PORT`: The port where your database server is running (typically `3306` for MySQL) -- `DATABASE`: The name of the [database](https://dev.mysql.com/doc/refman/8.0/en/creating-database.html) - -As an example, for a MySQL database hosted on AWS RDS, the [connection URL](/orm/reference/connection-urls) might look similar to this: - -```bash file=.env -DATABASE_URL="mysql://johndoe:XXX@mysql–instance1.123456789012.us-east-1.rds.amazonaws.com:3306/mydb" -``` - -When running MySQL locally, your connection URL typically looks similar to this: - -```bash file=.env -DATABASE_URL="mysql://root:randompassword@localhost:3306/mydb" -``` diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/100-connect-your-database-node-planetscale.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/100-connect-your-database-node-planetscale.mdx deleted file mode 100644 index 5e59471d9b..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/100-connect-your-database-node-planetscale.mdx +++ /dev/null @@ -1,89 +0,0 @@ ---- -title: 'Connect your existing database using JavaScript and PlanetScale' -sidebar_label: 'Connect your database' -metaTitle: 'Connect your existing database using JavaScript and PlanetScale' -metaDescription: 'Connect your database to your existing project using JavaScript and PlanetScale' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -sidebar_class_name: hidden-sidebar -hide_table_of_contents: true -pagination_prev: getting-started/setup-prisma/add-to-existing-project/relational-databases-node-planetscale -pagination_next: getting-started/setup-prisma/start-from-scratch/relational-databases/using-prisma-migrate-node-planetscale -slugSwitch: /getting-started/setup-prisma/start-from-scratch/relational-databases/connect-your-database- ---- - -To connect your database, you need to set the `url` field of the `datasource` block in your Prisma schema to your database [connection URL](/orm/reference/connection-urls): - -```prisma file=prisma/schema.prisma showLineNumbers -datasource db { - provider = "postgresql" - url = env("DATABASE_URL") -} -``` - -You will also need to set the relation mode type to `prisma` in order to [emulate foreign key constraints](/orm/overview/databases/planetscale#option-1-emulate-relations-in-prisma-client) in the `datasource` block: - -```prisma file=schema.prisma highlight=4;add showLineNumbers -datasource db { - provider = "mysql" - url = env("DATABASE_URL") - //add-next-line - relationMode = "prisma" -} -``` - -> **Note**: Since February 2024, you can alternatively [use foreign key constraints on a database-level in PlanetScale](/orm/overview/databases/planetscale#option-2-enable-foreign-key-constraints-in-the-planetscale-database-settings), which omits the need for setting `relationMode = "prisma"`. - -The `url` is [set via an environment variable](/orm/prisma-schema/overview#accessing-environment-variables-from-the-schema) which is defined in `.env`: - -```bash file=.env -DATABASE_URL="mysql://janedoe:mypassword@server.us-east-2.psdb.cloud/mydb?sslaccept=strict" -``` - -You now need to adjust the connection URL to point to your own database. - -The [format of the connection URL](/orm/reference/connection-urls) for your database typically depends on the database you use. PlanetScale uses the MySQL connection URL format, which has the following structure (the parts spelled all-uppercased are _placeholders_ for your specific connection details): - -```no-lines -mysql://USER:PASSWORD@HOST:PORT/DATABASE -``` - -Here's a short explanation of each component: - -- `USER`: The name of your database user -- `PASSWORD`: The password for your database user -- `PORT`: The port where your database server is running (typically `3306` for MySQL) -- `DATABASE`: The name of the [database](https://dev.mysql.com/doc/refman/8.0/en/creating-database.html) - -For a database hosted with PlanetScale, the [connection URL](/orm/reference/connection-urls) looks similar to this: - -```bash file=.env -DATABASE_URL="mysql://myusername:mypassword@server.us-east-2.psdb.cloud/mydb?sslaccept=strict" -``` - -The connection URL for a given database branch can be found from your PlanetScale account by going to the overview page for the branch and selecting the 'Connect' dropdown. In the 'Passwords' section, generate a new password and select 'Prisma' to get the Prisma format for the connection URL. - -
-Alternative method: connecting using the PlanetScale CLI - -Alternatively, you can connect to your PlanetScale database server using the [PlanetScale CLI](https://planetscale.com/docs/concepts/planetscale-environment-setup), and use a local connection URL. In this case the connection URL will look like this: - -```bash file=.env -DATABASE_URL="mysql://root@localhost:PORT/mydb" -``` - - - -We recommend adding `.env` to your `.gitignore` file to prevent committing your environment variables. - - - -To connect to your branch, use the following command: - -```terminal -pscale connect prisma-test branchname --port PORT -``` - -The `--port` flag can be omitted if you are using the default port `3306`. - -
\ No newline at end of file diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/100-connect-your-database-node-postgresql.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/100-connect-your-database-node-postgresql.mdx deleted file mode 100644 index 33a3055f80..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/100-connect-your-database-node-postgresql.mdx +++ /dev/null @@ -1,57 +0,0 @@ ---- -title: 'Connect your existing database using JavaScript and PostgreSQL' -sidebar_label: 'Connect your database' -metaTitle: 'Connect your existing database using JavaScript and PostgreSQL' -metaDescription: 'Connect your database to your existing project using JavaScript and PostgreSQL' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -sidebar_class_name: hidden-sidebar -hide_table_of_contents: true -toc: false -pagination_prev: getting-started/setup-prisma/add-to-existing-project/relational-databases-node-postgresql -pagination_next: getting-started/setup-prisma/add-to-existing-project/relational-databases/introspection-node-postgresql -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/relational-databases/connect-your-database- ---- - -## Connecting your database - -To connect your database, you need to set the `url` field of the `datasource` block in your Prisma schema to your database [connection URL](/orm/reference/connection-urls): - -```prisma file=prisma/schema.prisma showLineNumbers -datasource db { - provider = "postgresql" - url = env("DATABASE_URL") -} -``` - -In this case, the `url` is [set via an environment variable](/orm/more/development-environment/environment-variables) which is defined in `.env`: - -```bash file=.env -DATABASE_URL="postgresql://johndoe:randompassword@localhost:5432/mydb?schema=public" -``` - -You now need to adjust the connection URL to point to your own database. - -

Connection URL

- -The [format of the connection URL](/orm/reference/connection-urls) for your database depends on the database you use. For PostgreSQL, it looks as follows (the parts spelled all-uppercased are _placeholders_ for your specific connection details): - -```no-lines -postgresql://USER:PASSWORD@HOST:PORT/DATABASE?schema=SCHEMA -``` - -> **Note**: In most cases, you can use the [`postgres://` and `postgresql:// URI scheme designators interchangeably`](https://www.postgresql.org/docs/10/libpq-connect.html#id-1.7.3.8.3.6) - however, depending on how your database is hosted, you might need to be specific. - -If you're unsure what to provide for the `schema` parameter for a PostgreSQL connection URL, you can probably omit it. In that case, the default schema name `public` will be used. - -As an example, for a PostgreSQL database hosted on Heroku, the connection URL might look similar to this: - -```bash file=.env -DATABASE_URL="postgresql://opnmyfngbknppm:XXX@ec2-46-137-91-216.eu-west-1.compute.amazonaws.com:5432/d50rgmkqi2ipus?schema=hello-prisma" -``` - -When running PostgreSQL locally on macOS, your user and password as well as the database name _typically_ correspond to the current _user_ of your OS, e.g. assuming the user is called `janedoe`: - -```bash file=.env -DATABASE_URL="postgresql://janedoe:janedoe@localhost:5432/janedoe?schema=hello-prisma" -``` diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/100-connect-your-database-node-sqlserver.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/100-connect-your-database-node-sqlserver.mdx deleted file mode 100644 index 57fa9a847d..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/100-connect-your-database-node-sqlserver.mdx +++ /dev/null @@ -1,35 +0,0 @@ ---- -title: 'Connect your existing database using JavaScript and SQL Server' -sidebar_label: 'Connect your database' -metaTitle: 'Connect your existing database using JavaScript and SQL Server' -metaDescription: 'Connect your existing database to your project using JavaScript and SQL Server' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -sidebar_class_name: hidden-sidebar -hide_table_of_contents: true -toc: false -pagination_prev: getting-started/setup-prisma/add-to-existing-project/relational-databases-node-sqlserver -pagination_next: getting-started/setup-prisma/add-to-existing-project/relational-databases/introspection-node-sqlserver -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/relational-databases/connect-your-database- ---- - -## Connecting your database - -To connect your database, you need to set the `url` field of the `datasource` block in your Prisma schema to your database [connection URL](/orm/reference/connection-urls): - -```prisma file=prisma/schema.prisma showLineNumbers -datasource db { - provider = "sqlserver" - url = env("DATABASE_URL") -} -``` - -The `url` is [set via an environment variable](/orm/prisma-schema/overview#accessing-environment-variables-from-the-schema), the following example connection URL [uses SQL authentication](/orm/overview/databases/sql-server), but there are [other ways to format your connection URL](/orm/overview/databases/sql-server) - -```bash file=.env -DATABASE_URL="sqlserver://localhost:1433;database=mydb;user=sa;password=r@ndomP@$$w0rd;trustServerCertificate=true" -``` - -Adjust the connection URL to match your setup - see [Microsoft SQL Server connection URL](/orm/overview/databases/sql-server) for more information. - -> Make sure TCP/IP connections are enabled via [SQL Server Configuration Manager](https://learn.microsoft.com/en-us/sql/relational-databases/sql-server-configuration-manager?view=sql-server-ver16&viewFallbackFrom=sql-server-ver16) to avoid `No connection could be made because the target machine actively refused it. (os error 10061)` diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/100-connect-your-database-typescript-cockroachdb.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/100-connect-your-database-typescript-cockroachdb.mdx deleted file mode 100644 index 2a80965129..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/100-connect-your-database-typescript-cockroachdb.mdx +++ /dev/null @@ -1,59 +0,0 @@ ---- -title: 'Connect your existing database using TypeScript and CockroachDB' -sidebar_label: 'Connect your database' -metaTitle: 'Connect your existing database using TypeScript and CockroachDB' -metaDescription: 'Connect your existing database to your project using TypeScript and CockroachDB' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -sidebar_class_name: 'hidden-sidebar tech-switch' -hide_table_of_contents: true -toc: false -pagination_prev: getting-started/setup-prisma/add-to-existing-project/relational-databases-typescript-cockroachdb -pagination_next: getting-started/setup-prisma/add-to-existing-project/relational-databases/introspection-typescript-cockroachdb -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/relational-databases/connect-your-database- ---- - -## Connecting your database - -To connect your database, you need to set the `url` field of the `datasource` block in your Prisma schema to your database [connection URL](/orm/reference/connection-urls): - -```prisma file=prisma/schema.prisma showLineNumbers -datasource db { - provider = "postgresql" - url = env("DATABASE_URL") -} -``` - -The `url` is [set via an environment variable](/orm/more/development-environment/environment-variables) which is defined in `.env`. You now need to adjust the connection URL to point to your own database. - -

Connection URL

- -The [format of the connection URL](/orm/reference/connection-urls) for your database depends on the database you use. CockroachDB uses the PostgreSQL connection URL format, which has the following structure (the parts spelled all-uppercased are _placeholders_ for your specific connection details): - -```no-lines -postgresql://USER:PASSWORD@HOST:PORT/DATABASE?PARAMETERS -``` - -Here's a short explanation of each component: - -- `USER`: The name of your database user -- `PASSWORD`: The password for your database user -- `PORT`: The port where your database server is running. The default for CockroachDB is `26257`. -- `DATABASE`: The name of the database -- `PARAMETERS`: Any additional connection parameters. See the CockroachDB documentation [here](https://www.cockroachlabs.com/docs/stable/connection-parameters.html#additional-connection-parameters). - -For a [CockroachDB Serverless](https://www.cockroachlabs.com/docs/cockroachcloud/quickstart.html) or [Cockroach Dedicated](https://www.cockroachlabs.com/docs/cockroachcloud/quickstart-trial-cluster) database hosted on [CockroachDB Cloud](https://www.cockroachlabs.com/docs/cockroachcloud/quickstart/), the [connection URL](/orm/reference/connection-urls) looks similar to this: - -```bash file=.env -DATABASE_URL="postgresql://:@..cockroachlabs.cloud:26257/defaultdb?sslmode=verify-full&sslrootcert=$HOME/.postgresql/root.crt&options=--" -``` - -To find your connection string on CockroachDB Cloud, click the 'Connect' button on the overview page for your database cluster, and select the 'Connection string' tab. - -For a [CockroachDB database hosted locally](https://www.cockroachlabs.com/docs/stable/secure-a-cluster.html), the [connection URL](/orm/reference/connection-urls) looks similar to this: - -```bash file=.env -DATABASE_URL="postgresql://root@localhost:26257?sslmode=disable" -``` - -Your connection string is displayed as part of the welcome text when starting CockroachDB from the command line. diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/100-connect-your-database-typescript-mysql.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/100-connect-your-database-typescript-mysql.mdx deleted file mode 100644 index 412a150be7..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/100-connect-your-database-typescript-mysql.mdx +++ /dev/null @@ -1,60 +0,0 @@ ---- -title: 'Connect your existing database using TypeScript and MySQL' -sidebar_label: 'Connect your database' -metaTitle: 'Connect your existing database using TypeScript and MySQL' -metaDescription: 'Connect your existing database to your project using TypeScript and MySQL' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -sidebar_class_name: hidden-sidebar -hide_table_of_contents: true -toc: false -pagination_prev: getting-started/setup-prisma/add-to-existing-project/relational-databases-typescript-mysql -pagination_next: getting-started/setup-prisma/add-to-existing-project/relational-databases/introspection-typescript-mysql -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/relational-databases/connect-your-database- ---- - -## Connecting your database - -To connect your database, you need to set the `url` field of the `datasource` block in your Prisma schema to your database [connection URL](/orm/reference/connection-urls): - -```prisma file=prisma/schema.prisma showLineNumbers -datasource db { - provider = "mysql" - url = env("DATABASE_URL") -} -``` - -In this case, the `url` is [set via an environment variable](/orm/prisma-schema/overview#accessing-environment-variables-from-the-schema) which is defined in `.env`: - -```bash file=.env -DATABASE_URL="mysql://johndoe:randompassword@localhost:3306/mydb" -``` - -You now need to adjust the connection URL to point to your own database. - -

Connection URL

- -The [format of the connection URL](/orm/reference/connection-urls) for your database typically depends on the database you use. For MySQL, it looks as follows (the parts spelled all-uppercased are _placeholders_ for your specific connection details): - -```no-lines -mysql://USER:PASSWORD@HOST:PORT/DATABASE -``` - -Here's a short explanation of each component: - -- `USER`: The name of your database user -- `PASSWORD`: The password for your database user -- `PORT`: The port where your database server is running (typically `3306` for MySQL) -- `DATABASE`: The name of the [database](https://dev.mysql.com/doc/refman/8.0/en/creating-database.html) - -As an example, for a MySQL database hosted on AWS RDS, the [connection URL](/orm/reference/connection-urls) might look similar to this: - -```bash file=.env -DATABASE_URL="mysql://johndoe:XXX@mysql–instance1.123456789012.us-east-1.rds.amazonaws.com:3306/mydb" -``` - -When running MySQL locally, your connection URL typically looks similar to this: - -```bash file=.env -DATABASE_URL="mysql://root:randompassword@localhost:3306/mydb" -``` diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/100-connect-your-database-typescript-planetscale.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/100-connect-your-database-typescript-planetscale.mdx deleted file mode 100644 index 3dfe674538..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/100-connect-your-database-typescript-planetscale.mdx +++ /dev/null @@ -1,86 +0,0 @@ ---- -title: 'Connect your existing database using TypeScript and PlanetScale' -sidebar_label: 'Connect your database' -metaTitle: 'Connect your existing database using TypeScript and PlanetScale' -metaDescription: 'Connect your existing database to your project using TypeScript and PlanetScale' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -sidebar_class_name: hidden-sidebar -hide_table_of_contents: true -toc: false -pagination_prev: getting-started/setup-prisma/add-to-existing-project/relational-databases-typescript-planetscale -pagination_next: getting-started/setup-prisma/add-to-existing-project/relational-databases/introspection-typescript-planetscale -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/relational-databases/connect-your-database- ---- - -## Connecting your database - -To connect your database, you need to set the `url` field of the `datasource` block in your Prisma schema to your database [connection URL](/orm/reference/connection-urls): - -```prisma file=prisma/schema.prisma showLineNumbers -datasource db { - provider = "postgresql" - url = env("DATABASE_URL") -} -``` - -You will also need to [set the relation mode type to `prisma`](/orm/prisma-schema/data-model/relations/relation-mode#emulate-relations-in-prisma-orm-with-the-prisma-relation-mode) in the `datasource` block: - -```prisma file=schema.prisma highlight=4;add showLineNumbers -datasource db { - provider = "mysql" - url = env("DATABASE_URL") - //add-next-line - relationMode = "prisma" -} -``` - -The `url` is [set via an environment variable](/orm/prisma-schema/overview#accessing-environment-variables-from-the-schema) which is defined in `.env`: - -```bash file=.env -DATABASE_URL="mysql://janedoe:mypassword@server.us-east-2.psdb.cloud/mydb?sslaccept=strict" -``` - -You now need to adjust the connection URL to point to your own database. - -

Connection URL

- -The [format of the connection URL](/orm/reference/connection-urls) for your database typically depends on the database you use. PlanetScale uses the MySQL connection URL format, which has the following structure (the parts spelled all-uppercased are _placeholders_ for your specific connection details): - -```no-lines -mysql://USER:PASSWORD@HOST:PORT/DATABASE -``` - -Here's a short explanation of each component: - -- `USER`: The name of your database user -- `PASSWORD`: The password for your database user -- `PORT`: The port where your database server is running (typically `3306` for MySQL) -- `DATABASE`: The name of the [database](https://dev.mysql.com/doc/refman/8.0/en/creating-database.html) - -For a database hosted with PlanetScale, the [connection URL](/orm/reference/connection-urls) looks similar to this: - -```bash file=.env -DATABASE_URL="mysql://myusername:mypassword@server.us-east-2.psdb.cloud/mydb?sslaccept=strict" -``` - -The connection URL for a given database branch can be found from your PlanetScale account by going to the overview page for the branch and selecting the 'Connect' dropdown. In the 'Passwords' section, generate a new password and select 'Prisma' to get the Prisma format for the connection URL. - -
-Alternative method: connecting using the PlanetScale CLI - -Alternatively, you can connect to your PlanetScale database server using the [PlanetScale CLI](https://planetscale.com/docs/concepts/planetscale-environment-setup), and use a local connection URL. In this case the connection URL will look like this: - -```bash file=.env -DATABASE_URL="mysql://root@localhost:PORT/mydb" -``` - -To connect to your branch, use the following command: - -```terminal -pscale connect prisma-test branchname --port PORT -``` - -The `--port` flag can be omitted if you are using the default port `3306`. - -
diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/100-connect-your-database-typescript-postgresql.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/100-connect-your-database-typescript-postgresql.mdx deleted file mode 100644 index 6035f3ee0f..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/100-connect-your-database-typescript-postgresql.mdx +++ /dev/null @@ -1,56 +0,0 @@ ---- -title: 'Connect your existing database using TypeScript and PostgresSQL' -sidebar_label: 'Connect your database' -metaTitle: 'Connect your existing database using TypeScript and PostgresSQL' -metaDescription: 'Connect your existing database to your project using TypeScript and PostgresSQL' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -hide_table_of_contents: true -toc: false -pagination_prev: getting-started/setup-prisma/add-to-existing-project/relational-databases-typescript-postgresql -pagination_next: getting-started/setup-prisma/add-to-existing-project/relational-databases/introspection-typescript-postgresql -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/relational-databases/connect-your-database- ---- - -## Connecting your database - -To connect your database, you need to set the `url` field of the `datasource` block in your Prisma schema to your database [connection URL](/orm/reference/connection-urls): - -```prisma file=prisma/schema.prisma showLineNumbers -datasource db { - provider = "postgresql" - url = env("DATABASE_URL") -} -``` - -In this case, the `url` is [set via an environment variable](/orm/more/development-environment/environment-variables) which is defined in `.env`: - -```bash file=.env -DATABASE_URL="postgresql://johndoe:randompassword@localhost:5432/mydb?schema=public" -``` - -You now need to adjust the connection URL to point to your own database. - -

Connection URL

- -The [format of the connection URL](/orm/reference/connection-urls) for your database depends on the database you use. For PostgreSQL, it looks as follows (the parts spelled all-uppercased are _placeholders_ for your specific connection details): - -```no-lines -postgresql://USER:PASSWORD@HOST:PORT/DATABASE?schema=SCHEMA -``` - -> **Note**: In most cases, you can use the [`postgres://` and `postgresql:// URI scheme designators interchangeably`](https://www.postgresql.org/docs/10/libpq-connect.html#id-1.7.3.8.3.6) - however, depending on how your database is hosted, you might need to be specific. - -If you're unsure what to provide for the `schema` parameter for a PostgreSQL connection URL, you can probably omit it. In that case, the default schema name `public` will be used. - -As an example, for a PostgreSQL database hosted on Heroku, the connection URL might look similar to this: - -```bash file=.env -DATABASE_URL="postgresql://opnmyfngbknppm:XXX@ec2-46-137-91-216.eu-west-1.compute.amazonaws.com:5432/d50rgmkqi2ipus?schema=hello-prisma" -``` - -When running PostgreSQL locally on macOS, your user and password as well as the database name _typically_ correspond to the current _user_ of your OS, e.g. assuming the user is called `janedoe`: - -```bash file=.env -DATABASE_URL="postgresql://janedoe:janedoe@localhost:5432/janedoe?schema=hello-prisma" -``` diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/100-connect-your-database-typescript-sqlserver.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/100-connect-your-database-typescript-sqlserver.mdx deleted file mode 100644 index e898b23b12..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/100-connect-your-database-typescript-sqlserver.mdx +++ /dev/null @@ -1,35 +0,0 @@ ---- -title: 'Connect your existing database using TypeScript and SQL Server' -sidebar_label: 'Connect your database' -metaTitle: 'Connect your existing database using TypeScript and SQL Server' -metaDescription: 'Connect your existing database to your project using TypeScript and SQL Server' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -toc: false -hide_table_of_contents: true -sidebar_class_name: hidden-sidebar -pagination_prev: getting-started/setup-prisma/add-to-existing-project/relational-databases-typescript-sqlserver -pagination_next: getting-started/setup-prisma/add-to-existing-project/relational-databases/introspection-typescript-sqlserver -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/relational-databases/connect-your-database- ---- - -## Connecting your database - -To connect your database, you need to set the `url` field of the `datasource` block in your Prisma schema to your database [connection URL](/orm/reference/connection-urls): - -```prisma file=prisma/schema.prisma showLineNumbers -datasource db { - provider = "sqlserver" - url = env("DATABASE_URL") -} -``` - -The `url` is [set via an environment variable](/orm/prisma-schema/overview#accessing-environment-variables-from-the-schema), the following example connection URL [uses SQL authentication](/orm/overview/databases/sql-server), but there are [other ways to format your connection URL](/orm/overview/databases/sql-server) - -```bash file=.env -DATABASE_URL="sqlserver://localhost:1433;database=mydb;user=sa;password=r@ndomP@$$w0rd;trustServerCertificate=true" -``` - -Adjust the connection URL to match your setup - see [Microsoft SQL Server connection URL](/orm/overview/databases/sql-server) for more information. - -> Make sure TCP/IP connections are enabled via [SQL Server Configuration Manager](https://learn.microsoft.com/en-us/sql/relational-databases/sql-server-configuration-manager?view=sql-server-ver16&viewFallbackFrom=sql-server-ver16) to avoid `No connection could be made because the target machine actively refused it. (os error 10061)` diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/150-introspection-node-cockroachdb.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/150-introspection-node-cockroachdb.mdx deleted file mode 100644 index d7d5f1cda4..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/150-introspection-node-cockroachdb.mdx +++ /dev/null @@ -1,217 +0,0 @@ ---- -title: 'Introspection for CockroachDB in a JavaScript project' -sidebar_label: 'Introspection' -metaTitle: 'Introspection with Prisma ORM, JavaScript, and CockroachDB' -metaDescription: 'Introspect your existing project with Prisma ORM, JavaScript, and CockroachDB' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -hide_table_of_contents: true -sidebar_class_name: hidden-sidebar -pagination_prev: getting-started/setup-prisma/add-to-existing-project/relational-databases/connect-your-database-node-cockroachdb -pagination_next: getting-started/setup-prisma/add-to-existing-project/relational-databases/baseline-your-database-node-cockroachdb -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/relational-databases/introspection- ---- - -## Introspect your database with Prisma ORM - -For the purpose of this guide, we'll use a demo SQL schema with three tables: - -```sql no-lines -CREATE TABLE "User" ( - id INT8 PRIMARY KEY DEFAULT unique_rowid(), - name STRING(255), - email STRING(255) UNIQUE NOT NULL -); - -CREATE TABLE "Post" ( - id INT8 PRIMARY KEY DEFAULT unique_rowid(), - title STRING(255) UNIQUE NOT NULL, - "createdAt" TIMESTAMP NOT NULL DEFAULT now(), - content STRING, - published BOOLEAN NOT NULL DEFAULT false, - "authorId" INT8 NOT NULL, - FOREIGN KEY ("authorId") REFERENCES "User"(id) -); - -CREATE TABLE "Profile" ( - id INT8 PRIMARY KEY DEFAULT unique_rowid(), - bio STRING, - "userId" INT8 UNIQUE NOT NULL, - FOREIGN KEY ("userId") REFERENCES "User"(id) -); -``` - -> **Note**: Some fields are written in double quotes to ensure CockroachDB uses proper casing. If no double-quotes were used, CockroachDB would just read everything as _lowercase_ characters. - -
-Expand for a graphical overview of the tables - -**User** - -| Column name | Type | Primary key | Foreign key | Required | Default | -| :---------- | :------------ | :---------- | :---------- | :------- | :----------------- | -| `id` | `INT8` | **✔️** | No | **✔️** | _autoincrementing_ | -| `name` | `STRING(255)` | No | No | No | - | -| `email` | `STRING(255)` | No | No | **✔️** | - | - -**Post** - -| Column name | Type | Primary key | Foreign key | Required | Default | -| :---------- | :------------ | :---------- | :---------- | :------- | :----------------- | -| `id` | `INT8` | **✔️** | No | **✔️** | _autoincrementing_ | -| `createdAt` | `TIMESTAMP` | No | No | **✔️** | `now()` | -| `title` | `STRING(255)` | No | No | **✔️** | - | -| `content` | `STRING` | No | No | No | - | -| `published` | `BOOLEAN` | No | No | **✔️** | `false` | -| `authorId` | `INT8` | No | **✔️** | **✔️** | - | - -**Profile** - -| Column name | Type | Primary key | Foreign key | Required | Default | -| :---------- | :------- | :---------- | :---------- | :------- | :----------------- | -| `id` | `INT8` | **✔️** | No | **✔️** | _autoincrementing_ | -| `bio` | `STRING` | No | No | No | - | -| `userId` | `INT8` | No | **✔️** | **✔️** | - | - -
- -As a next step, you will introspect your database. The result of the introspection will be a [data model](/orm/prisma-schema/data-model/models) inside your Prisma schema. - -Run the following command to introspect your database: - -```terminal copy -npx prisma db pull -``` - -This command reads the environment variable used to define the `url` in your `schema.prisma`, `DATABASE_URL`, that in our case is set in `.env` and connects to your database. Once the connection is established, it introspects the database (i.e. it _reads the database schema_). It then translates the database schema from SQL into a Prisma data model. - -After the introspection is complete, your Prisma schema is updated: - -![Introspect your database](/img/getting-started/prisma-db-pull-generate-schema.png) - -The data model now looks similar to this: - -```prisma file=prisma/schema.prisma showLineNumbers -model Post { - id BigInt @id @default(autoincrement()) - title String @unique @db.String(255) - createdAt DateTime @default(now()) @db.Timestamp(6) - content String? - published Boolean @default(false) - authorId BigInt - User User @relation(fields: [authorId], references: [id], onDelete: NoAction, onUpdate: NoAction) -} - -model Profile { - id BigInt @id @default(autoincrement()) - bio String? - userId BigInt @unique - User User @relation(fields: [userId], references: [id], onDelete: NoAction, onUpdate: NoAction) -} - -model User { - id BigInt @id @default(autoincrement()) - name String? @db.String(255) - email String @unique @db.String(255) - Post Post[] - Profile Profile? -} -``` - -Prisma ORM's data model is a declarative representation of your database schema and serves as the foundation for the generated Prisma Client library. Your Prisma Client instance will expose queries that are _tailored_ to these models. - -Right now, there's a few minor "issues" with the data model: - -- The `User` relation field is uppercased and therefore doesn't adhere to Prisma's [naming conventions](/orm/reference/prisma-schema-reference#naming-conventions-1) . To express more "semantics", it would also be nice if this field was called `author` to _describe_ the relationship between `User` and `Post` better. -- The `Post` and `Profile` relation fields on `User` as well as the `User` relation field on `Profile` are all uppercased. To adhere to Prisma's [naming conventions](/orm/reference/prisma-schema-reference#naming-conventions-1) , both fields should be lowercased to `post`, `profile` and `user`. -- Even after lowercasing, the `post` field on `User` is still slightly misnamed. That's because it actually refers to a [list](/orm/prisma-schema/data-model/models#type-modifiers) of posts – a better name therefore would be the plural form: `posts`. - -These changes are relevant for the generated Prisma Client API where using lowercased relation fields `author`, `posts`, `profile` and `user` will feel more natural and idiomatic to JavaScript/TypeScript developers. You can therefore [configure your Prisma Client API](/orm/prisma-client/setup-and-configuration/custom-model-and-field-names). - -Because [relation fields](/orm/prisma-schema/data-model/relations#relation-fields) are _virtual_ (i.e. they _do not directly manifest in the database_), you can manually rename them in your Prisma schema without touching the database: - -```prisma file=prisma/schema.prisma highlight=8,15,22,23;edit showLineNumbers -model Post { - id BigInt @id @default(autoincrement()) - title String @unique @db.String(255) - createdAt DateTime @default(now()) @db.Timestamp(6) - content String? - published Boolean @default(false) - authorId BigInt - //edit-next-line - author User @relation(fields: [authorId], references: [id], onDelete: NoAction, onUpdate: NoAction) -} - -model Profile { - id BigInt @id @default(autoincrement()) - bio String? - userId BigInt @unique - //edit-next-line - user User @relation(fields: [userId], references: [id], onDelete: NoAction, onUpdate: NoAction) -} - -model User { - id BigInt @id @default(autoincrement()) - name String? @db.String(255) - email String @unique @db.String(255) - //edit-start - posts Post[] - profile Profile? - //edit-end -} -``` - -In this example, the database schema did follow the [naming conventions](/orm/reference/prisma-schema-reference#naming-conventions) for Prisma ORM models (only the virtual relation fields that were generated from introspection did not adhere to them and needed adjustment). This optimizes the ergonomics of the generated Prisma Client API. - -
- Using custom model and field names - -Sometimes though, you may want to make additional changes to the names of the columns and tables that are exposed in the Prisma Client API. A common example is to translate _snake_case_ notation which is often used in database schemas into _PascalCase_ and _camelCase_ notations which feel more natural for JavaScript/TypeScript developers. - -Assume you obtained the following model from introspection that's based on _snake_case_ notation: - -```prisma no-lines -model my_user { - user_id Int @id @default(sequence()) - first_name String? - last_name String @unique -} -``` - -If you generated a Prisma Client API for this model, it would pick up the _snake_case_ notation in its API: - -```ts no-lines -const user = await prisma.my_user.create({ - data: { - first_name: 'Alice', - last_name: 'Smith', - }, -}) -``` - -If you don't want to use the table and column names from your database in your Prisma Client API, you can configure them with [`@map` and `@@map`](/orm/prisma-schema/data-model/models#mapping-model-names-to-tables-or-collections): - -```prisma no-lines -model MyUser { - userId Int @id @default(sequence()) @map("user_id") - firstName String? @map("first_name") - lastName String @unique @map("last_name") - - @@map("my_user") -} -``` - -With this approach, you can name your model and its fields whatever you like and use the `@map` (for field names) and `@@map` (for models names) to point to the underlying tables and columns. Your Prisma Client API now looks as follows: - -```ts no-lines -const user = await prisma.myUser.create({ - data: { - firstName: 'Alice', - lastName: 'Smith', - }, -}) -``` - -Learn more about this on the [Configuring your Prisma Client API](/orm/prisma-client/setup-and-configuration/custom-model-and-field-names) page. - -
diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/150-introspection-node-mysql.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/150-introspection-node-mysql.mdx deleted file mode 100644 index 64ab5fdfd6..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/150-introspection-node-mysql.mdx +++ /dev/null @@ -1,220 +0,0 @@ ---- -title: 'Introspection for MySQL in a JavaScript project' -sidebar_label: 'Introspection' -metaTitle: 'Introspection with Prisma ORM, JavaScript, and MySQL' -metaDescription: 'Introspect your existing project with Prisma ORM, JavaScript, and MySQL' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -hide_table_of_contents: true -sidebar_class_name: hidden-sidebar -pagination_prev: getting-started/setup-prisma/add-to-existing-project/relational-databases/connect-your-database-node-mysql -pagination_next: getting-started/setup-prisma/add-to-existing-project/relational-databases/baseline-your-database-node-mysql -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/relational-databases/introspection- ---- - -## Introspect your database with Prisma ORM - -For the purpose of this guide, we'll use a demo SQL schema with three tables: - -```sql no-lines -CREATE TABLE User ( - id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL, - name VARCHAR(255), - email VARCHAR(255) UNIQUE NOT NULL -); - -CREATE TABLE Post ( - id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL, - title VARCHAR(255) NOT NULL, - createdAt TIMESTAMP NOT NULL DEFAULT now(), - content TEXT, - published BOOLEAN NOT NULL DEFAULT false, - authorId INTEGER NOT NULL, - FOREIGN KEY (authorId) REFERENCES User(id) -); - -CREATE TABLE Profile ( - id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL, - bio TEXT, - userId INTEGER UNIQUE NOT NULL, - FOREIGN KEY (userId) REFERENCES User(id) -); -``` - -
-Expand for a graphical overview of the tables - -**User** - -| Column name | Type | Primary key | Foreign key | Required | Default | -| :---------- | :------------- | :---------- | :---------- | :------- | :----------------- | -| `id` | `INTEGER` | **✔️** | No | **✔️** | _autoincrementing_ | -| `name` | `VARCHAR(255)` | No | No | No | - | -| `email` | `VARCHAR(255)` | No | No | **✔️** | - | - -**Post** - -| Column name | Type | Primary key | Foreign key | Required | Default | -| :---------- | :------------- | :---------- | :---------- | :------- | :----------------- | -| `id` | `INTEGER` | **✔️** | No | **✔️** | _autoincrementing_ | -| `createdAt` | `DATETIME(3)` | No | No | **✔️** | `now()` | -| `title` | `VARCHAR(255)` | No | No | **✔️** | - | -| `content` | `TEXT` | No | No | No | - | -| `published` | `BOOLEAN` | No | No | **✔️** | `false` | -| `authorId` | `INTEGER` | No | **✔️** | **✔️** | `false` | - -**Profile** - -| Column name | Type | Primary key | Foreign key | Required | Default | -| :---------- | :-------- | :---------- | :---------- | :------- | :----------------- | -| `id` | `INTEGER` | **✔️** | No | **✔️** | _autoincrementing_ | -| `bio` | `TEXT` | No | No | No | - | -| `userId` | `INTEGER` | No | **✔️** | **✔️** | - | - -
- -As a next step, you will introspect your database. The result of the introspection will be a [data model](/orm/prisma-schema/data-model/models) inside your Prisma schema. - -Run the following command to introspect your database: - -```terminal copy -npx prisma db pull -``` - -This command reads the `DATABASE_URL` environment variable that's defined in `.env` and connects to your database. Once the connection is established, it introspects the database (i.e. it _reads the database schema_). It then translates the database schema from SQL into a Prisma data model. - -After the introspection is complete, your Prisma schema is updated: - -![Introspect your database](/img/getting-started/prisma-db-pull-generate-schema.png) - -The data model now looks similar to this (note that the fields on the models have been reordered for better readability): - -```prisma file=prisma/schema.prisma showLineNumbers -model Post { - id Int @id @default(autoincrement()) - title String @db.VarChar(255) - createdAt DateTime @default(now()) @db.Timestamp(0) - content String? @db.Text - published Boolean @default(false) - authorId Int - User User @relation(fields: [authorId], references: [id], onDelete: NoAction, onUpdate: NoAction, map: "Post_ibfk_1") - - @@index([authorId], map: "authorId") -} - -model Profile { - id Int @id @default(autoincrement()) - bio String? @db.Text - userId Int @unique(map: "userId") - User User @relation(fields: [userId], references: [id], onDelete: NoAction, onUpdate: NoAction, map: "Profile_ibfk_1") -} - -model User { - id Int @id @default(autoincrement()) - name String? @db.VarChar(255) - email String @unique(map: "email") @db.VarChar(255) - Post Post[] - Profile Profile? -} -``` - -:::info - -Refer to the [Prisma schema reference](/orm/reference/prisma-schema-reference) for detailed information about the schema definition. - -::: - -Prisma ORM's data model is a declarative representation of your database schema and serves as the foundation for the generated Prisma Client library. Your Prisma Client instance will expose queries that are _tailored_ to these models. - -Right now, there's a few minor "issues" with the data model: - -- The `User` relation field is uppercased and therefore doesn't adhere to Prisma's [naming conventions](/orm/reference/prisma-schema-reference#naming-conventions-1) . To express more "semantics", it would also be nice if this field was called `author` to _describe_ the relationship between `User` and `Post` better. -- The `Post` and `Profile` relation fields on `User` as well as the `User` relation field on `Profile` are all uppercased. To adhere to Prisma's [naming conventions](/orm/reference/prisma-schema-reference#naming-conventions-1) , both fields should be lowercased to `post`, `profile` and `user`. -- Even after lowercasing, the `post` field on `User` is still slightly misnamed. That's because it actually refers to a [list](/orm/prisma-schema/data-model/models#type-modifiers) of posts – a better name therefore would be the plural form: `posts`. - -These changes are relevant for the generated Prisma Client API where using lowercased relation fields `author`, `posts`, `profile` and `user` will feel more natural and idiomatic to JavaScript/TypeScript developers. You can therefore [configure your Prisma Client API](/orm/prisma-client/setup-and-configuration/custom-model-and-field-names). - -Because [relation fields](/orm/prisma-schema/data-model/relations#relation-fields) are _virtual_ (i.e. they _do not directly manifest in the database_), you can manually rename them in your Prisma schema without touching the database: - -```prisma file=prisma/schema.prisma highlight=8,17,24,25;edit showLineNumbers -model Post { - id Int @id @default(autoincrement()) - title String @db.VarChar(255) - createdAt DateTime @default(now()) @db.Timestamp(0) - content String? @db.Text - published Boolean @default(false) - authorId Int - //edit-next-line - author User @relation(fields: [authorId], references: [id], onDelete: NoAction, onUpdate: NoAction, map: "Post_ibfk_1") - - @@index([authorId], map: "authorId") -} - -model Profile { - id Int @id @default(autoincrement()) - bio String? @db.Text - userId Int @unique(map: "userId") - //edit-next-line - user User @relation(fields: [userId], references: [id], onDelete: NoAction, onUpdate: NoAction, map: "Profile_ibfk_1") -} - -model User { - id Int @id @default(autoincrement()) - name String? @db.VarChar(255) - email String @unique(map: "email") @db.VarChar(255) - //edit-start - posts Post[] - profile Profile? - //edit-end -} -``` - -In this example, the database schema did follow the [naming conventions](/orm/reference/prisma-schema-reference#naming-conventions) for Prisma ORM models (only the virtual relation fields that were generated from introspection did not adhere to them and needed adjustment). This optimizes the ergonomics of the generated Prisma Client API. - -Sometimes though, you may want to make additional changes to the names of the columns and tables that are exposed in the Prisma Client API. A common example is to translate _snake_case_ notation which is often used in database schemas into _PascalCase_ and _camelCase_ notations which feel more natural for JavaScript/TypeScript developers. - -Assume you obtained the following model from introspection that's based on _snake_case_ notation: - -```prisma no-lines -model my_user { - user_id Int @id @default(autoincrement()) - first_name String? - last_name String @unique -} -``` - -If you generated a Prisma Client API for this model, it would pick up the _snake_case_ notation in its API: - -```ts no-lines -const user = await prisma.my_user.create({ - data: { - first_name: 'Alice', - last_name: 'Smith', - }, -}) -``` - -If you don't want to use the table and column names from your database in your Prisma Client API, you can configure them with [`@map` and `@@map`](/orm/prisma-schema/data-model/models#mapping-model-names-to-tables-or-collections): - -```prisma no-lines -model MyUser { - userId Int @id @default(autoincrement()) @map("user_id") - firstName String? @map("first_name") - lastName String @unique @map("last_name") - - @@map("my_user") -} -``` - -With this approach, you can name your model and its fields whatever you like and use the `@map` (for field names) and `@@map` (for models names) to point to the underlying tables and columns. Your Prisma Client API now looks as follows: - -```ts no-lines -const user = await prisma.myUser.create({ - data: { - firstName: 'Alice', - lastName: 'Smith', - }, -}) -``` - -Learn more about this on the [Configuring your Prisma Client API](/orm/prisma-client/setup-and-configuration/custom-model-and-field-names) page. diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/150-introspection-node-planetscale.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/150-introspection-node-planetscale.mdx deleted file mode 100644 index 453a978732..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/150-introspection-node-planetscale.mdx +++ /dev/null @@ -1,237 +0,0 @@ ---- -title: 'Introspection for PlanetScale in a JavaScript project' -sidebar_label: 'Introspection' -metaTitle: 'Introspection with Prisma ORM, JavaScript, and PlanetScale' -metaDescription: 'Introspect your existing project with Prisma ORM, JavaScript, and PlanetScale' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -hide_table_of_contents: true -sidebar_class_name: hidden-sidebar -pagination_prev: getting-started/setup-prisma/add-to-existing-project/relational-databases/connect-your-database-node-postgresql -pagination_next: getting-started/setup-prisma/add-to-existing-project/relational-databases/baseline-your-database-node-postgresql -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/relational-databases/introspection- ---- - - -## Introspect your database with Prisma ORM - -For the purpose of this guide, we'll use a demo SQL schema with three tables: - -```sql no-lines -CREATE TABLE `Post` ( - `id` int NOT NULL AUTO_INCREMENT, - `createdAt` datetime(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3), - `updatedAt` datetime(3) NOT NULL, - `title` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, - `content` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, - `published` tinyint(1) NOT NULL DEFAULT '0', - `authorId` int NOT NULL, - PRIMARY KEY (`id`), - KEY `Post_authorId_idx` (`authorId`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; - -CREATE TABLE `Profile` ( - `id` int NOT NULL AUTO_INCREMENT, - `bio` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, - `userId` int NOT NULL, - PRIMARY KEY (`id`), - UNIQUE KEY `Profile_userId_key` (`userId`), - KEY `Profile_userId_idx` (`userId`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; - -CREATE TABLE `User` ( - `id` int NOT NULL AUTO_INCREMENT, - `email` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL, - `name` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, - PRIMARY KEY (`id`), - UNIQUE KEY `User_email_key` (`email`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -``` - -
-Expand for a graphical overview of the tables - -**Post** - -| Column name | Type | Primary key | Foreign key | Required | Default | -| :---------- | :------------- | :---------- | :---------- | :------- | :----------------- | -| `id` | `int` | **✔️** | No | **✔️** | _autoincrementing_ | -| `createdAt` | `datetime(3)` | No | No | **✔️** | `now()` | -| `updatedAt` | `datetime(3)` | No | No | **✔️** | | -| `title` | `varchar(255)` | No | No | **✔️** | - | -| `content` | `varchar(191)` | No | No | No | - | -| `published` | `tinyint(1)` | No | No | **✔️** | `false` | -| `authorId` | `int` | No | No | **✔️** | - | - -**Profile** - -| Column name | Type | Primary key | Foreign key | Required | Default | -| :---------- | :------------- | :---------- | :---------- | :------- | :----------------- | -| `id` | `int` | **✔️** | No | **✔️** | _autoincrementing_ | -| `bio` | `varchar(191)` | No | No | No | - | -| `userId` | `int` | No | No | **✔️** | - | - -**User** - -| Column name | Type | Primary key | Foreign key | Required | Default | -| :---------- | :------------- | :---------- | :---------- | :------- | :----------------- | -| `id` | `int` | **✔️** | No | **✔️** | _autoincrementing_ | -| `name` | `varchar(191)` | No | No | No | - | -| `email` | `varchar(191)` | No | No | **✔️** | - | - -
- -As a next step, you will introspect your database. The result of the introspection will be a [data model](/orm/prisma-schema/data-model/models) inside your Prisma schema. - -Run the following command to introspect your database: - -```terminal copy -npx prisma db pull -``` - -This command reads the `DATABASE_URL` environment variable that's defined in `.env` and connects to your database. Once the connection is established, it introspects the database (i.e. it _reads the database schema_). It then translates the database schema from SQL into a Prisma data model. - -After the introspection is complete, your Prisma schema is updated: - -![Introspect your database](/img/getting-started/prisma-db-pull-generate-schema.png) - -The data model now looks similar to this: - -```prisma file=prisma/schema.prisma showLineNumbers -model Post { - id Int @id @default(autoincrement()) - createdAt DateTime @default(now()) - updatedAt DateTime - title String @db.VarChar(255) - content String? - published Boolean @default(false) - authorId Int - - @@index([authorId]) -} - -model Profile { - id Int @id @default(autoincrement()) - bio String? - userId Int @unique - - @@index([userId]) -} - -model User { - id Int @id @default(autoincrement()) - email String @unique - name String? -} -``` - -:::info - -Refer to the [Prisma schema reference](/orm/reference/prisma-schema-reference) for detailed information about the schema definition. - -::: - -Prisma's data model is a declarative representation of your database schema and serves as the foundation for the generated Prisma Client library. Your Prisma Client instance will expose queries that are _tailored_ to these models. - -You will then need to add in any missing relations between your data using [relation fields](/orm/prisma-schema/data-model/relations#relation-fields): - -```prisma file=prisma/schema.prisma highlight=8,17,27,28;add showLineNumbers -model Post { - id Int @id @default(autoincrement()) - createdAt DateTime @default(now()) - updatedAt DateTime - title String @db.VarChar(255) - content String? - published Boolean @default(false) - //add-next-line - author User @relation(fields: [authorId], references: [id]) - authorId Int - - @@index([authorId]) -} - -model Profile { - id Int @id @default(autoincrement()) - bio String? - //add-next-line - user User @relation(fields: [userId], references: [id]) - userId Int @unique - - @@index([userId]) -} - -model User { - id Int @id @default(autoincrement()) - email String @unique - name String? - //add-start - posts Post[] - profile Profile? - //add-end -} -``` - -After this, run introspection on your database for a second time: - -```terminal copy -npx prisma db pull -``` - -Prisma Migrate will now keep the manually added relation fields. - -Because relation fields are _virtual_ (i.e. they _do not directly manifest in the database_), you can manually rename them in your Prisma schema without touching the database. - -In this example, the database schema follows the [naming conventions](/orm/reference/prisma-schema-reference#naming-conventions) for Prisma ORM models. This optimizes the ergonomics of the generated Prisma Client API. - -
- Using custom model and field names - -Sometimes though, you may want to make additional changes to the names of the columns and tables that are exposed in the Prisma Client API. A common example is to translate _snake_case_ notation which is often used in database schemas into _PascalCase_ and _camelCase_ notations which feel more natural for JavaScript/TypeScript developers. - -Assume you obtained the following model from introspection that's based on _snake_case_ notation: - -```prisma no-lines -model my_user { - user_id Int @id @default(autoincrement()) - first_name String? - last_name String @unique -} -``` - -If you generated a Prisma Client API for this model, it would pick up the _snake_case_ notation in its API: - -```ts no-lines -const user = await prisma.my_user.create({ - data: { - first_name: 'Alice', - last_name: 'Smith', - }, -}) -``` - -If you don't want to use the table and column names from your database in your Prisma Client API, you can configure them with [`@map` and `@@map`](/orm/prisma-schema/data-model/models#mapping-model-names-to-tables-or-collections): - -```prisma no-lines -model MyUser { - userId Int @id @default(autoincrement()) @map("user_id") - firstName String? @map("first_name") - lastName String @unique @map("last_name") - - @@map("my_user") -} -``` - -With this approach, you can name your model and its fields whatever you like and use the `@map` (for field names) and `@@map` (for models names) to point to the underlying tables and columns. Your Prisma Client API now looks as follows: - -```ts no-lines -const user = await prisma.myUser.create({ - data: { - firstName: 'Alice', - lastName: 'Smith', - }, -}) -``` - -Learn more about this on the [Configuring your Prisma Client API](/orm/prisma-client/setup-and-configuration/custom-model-and-field-names) page. - -
diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/150-introspection-node-postgresql.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/150-introspection-node-postgresql.mdx deleted file mode 100644 index 6231b4a6f5..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/150-introspection-node-postgresql.mdx +++ /dev/null @@ -1,218 +0,0 @@ ---- -title: 'Introspection for PostgreSQL in a JavaScript project' -sidebar_label: 'Introspection' -metaTitle: 'Introspection with Prisma ORM, JavaScript, and PostgreSQL' -metaDescription: 'Introspect your existing project with Prisma ORM, JavaScript, and PostgreSQL' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -hide_table_of_contents: true -sidebar_class_name: hidden-sidebar -pagination_prev: getting-started/setup-prisma/add-to-existing-project/relational-databases/connect-your-database-node-postgresql -pagination_next: getting-started/setup-prisma/add-to-existing-project/relational-databases/baseline-your-database-node-postgresql -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/relational-databases/introspection- ---- - - -## Introspect your database with Prisma ORM - -For the purpose of this guide, we'll use a demo SQL schema with three tables: - -```sql no-lines -CREATE TABLE "public"."User" ( - id SERIAL PRIMARY KEY NOT NULL, - name VARCHAR(255), - email VARCHAR(255) UNIQUE NOT NULL -); - -CREATE TABLE "public"."Post" ( - id SERIAL PRIMARY KEY NOT NULL, - title VARCHAR(255) NOT NULL, - "createdAt" TIMESTAMP NOT NULL DEFAULT now(), - content TEXT, - published BOOLEAN NOT NULL DEFAULT false, - "authorId" INTEGER NOT NULL, - FOREIGN KEY ("authorId") REFERENCES "public"."User"(id) -); - -CREATE TABLE "public"."Profile" ( - id SERIAL PRIMARY KEY NOT NULL, - bio TEXT, - "userId" INTEGER UNIQUE NOT NULL, - FOREIGN KEY ("userId") REFERENCES "public"."User"(id) -); -``` - -> **Note**: Some fields are written in double-quotes to ensure PostgreSQL uses proper casing. If no double-quotes were used, PostgreSQL would just read everything as _lowercase_ characters. - -
-Expand for a graphical overview of the tables - -**User** - -| Column name | Type | Primary key | Foreign key | Required | Default | -| :---------- | :------------- | :---------- | :---------- | :------- | :----------------- | -| `id` | `SERIAL` | **✔️** | No | **✔️** | _autoincrementing_ | -| `name` | `VARCHAR(255)` | No | No | No | - | -| `email` | `VARCHAR(255)` | No | No | **✔️** | - | - -**Post** - -| Column name | Type | Primary key | Foreign key | Required | Default | -| :---------- | :------------- | :---------- | :---------- | :------- | :----------------- | -| `id` | `SERIAL` | **✔️** | No | **✔️** | _autoincrementing_ | -| `createdAt` | `TIMESTAMP` | No | No | **✔️** | `now()` | -| `title` | `VARCHAR(255)` | No | No | **✔️** | - | -| `content` | `TEXT` | No | No | No | - | -| `published` | `BOOLEAN` | No | No | **✔️** | `false` | -| `authorId` | `INTEGER` | No | **✔️** | **✔️** | - | - -**Profile** - -| Column name | Type | Primary key | Foreign key | Required | Default | -| :---------- | :-------- | :---------- | :---------- | :------- | :----------------- | -| `id` | `SERIAL` | **✔️** | No | **✔️** | _autoincrementing_ | -| `bio` | `TEXT` | No | No | No | - | -| `userId` | `INTEGER` | No | **✔️** | **✔️** | - | - -
- -As a next step, you will introspect your database. The result of the introspection will be a [data model](/orm/prisma-schema/data-model/models) inside your Prisma schema. - -Run the following command to introspect your database: - -```terminal copy -npx prisma db pull -``` - -This command reads the `DATABASE_URL` environment variable that's defined in `.env` and connects to your database. Once the connection is established, it introspects the database (i.e. it _reads the database schema_). It then translates the database schema from SQL into a data model in your Prisma schema. - -After the introspection is complete, your Prisma schema is updated: - -![Introspect your database with Prisma ORM](/img/getting-started/prisma-db-pull-generate-schema.png) - -The data model now looks similar to this (note that the fields on the models have been reordered for better readability): - -```prisma file=prisma/schema.prisma showLineNumbers -model Post { - id Int @id @default(autoincrement()) - title String @db.VarChar(255) - createdAt DateTime @default(now()) @db.Timestamp(6) - content String? - published Boolean @default(false) - authorId Int - User User @relation(fields: [authorId], references: [id], onDelete: NoAction, onUpdate: NoAction) -} - -model Profile { - id Int @id @default(autoincrement()) - bio String? - userId Int @unique - User User @relation(fields: [userId], references: [id], onDelete: NoAction, onUpdate: NoAction) -} - -model User { - id Int @id @default(autoincrement()) - name String? @db.VarChar(255) - email String @unique @db.VarChar(255) - Post Post[] - Profile Profile? -} -``` - -Prisma ORM's data model is a declarative representation of your database schema and serves as the foundation for the generated Prisma Client library. Your Prisma Client instance will expose queries that are _tailored_ to these models. - -Right now, there's a few minor "issues" with the data model: - -- The `User` relation field is uppercased and therefore doesn't adhere to Prisma's [naming conventions](/orm/reference/prisma-schema-reference#naming-conventions-1) . To express more "semantics", it would also be nice if this field was called `author` to _describe_ the relationship between `User` and `Post` better. -- The `Post` and `Profile` relation fields on `User` as well as the `User` relation field on `Profile` are all uppercased. To adhere to Prisma's [naming conventions](/orm/reference/prisma-schema-reference#naming-conventions-1) , both fields should be lowercased to `post`, `profile` and `user`. -- Even after lowercasing, the `post` field on `User` is still slightly misnamed. That's because it actually refers to a [list](/orm/prisma-schema/data-model/models#type-modifiers) of posts – a better name therefore would be the plural form: `posts`. - -These changes are relevant for the generated Prisma Client API where using lowercased relation fields `author`, `posts`, `profile` and `user` will feel more natural and idiomatic to JavaScript/TypeScript developers. You can therefore [configure your Prisma Client API](/orm/prisma-client/setup-and-configuration/custom-model-and-field-names). - -Because [relation fields](/orm/prisma-schema/data-model/relations#relation-fields) are _virtual_ (i.e. they _do not directly manifest in the database_), you can manually rename them in your Prisma schema without touching the database: - -```prisma file=prisma/schema.prisma highlight=8,15,22,23;edit showLineNumbers -model Post { - id Int @id @default(autoincrement()) - title String @db.VarChar(255) - createdAt DateTime @default(now()) @db.Timestamp(6) - content String? - published Boolean @default(false) - authorId Int - //edit-next-line - author User @relation(fields: [authorId], references: [id], onDelete: NoAction, onUpdate: NoAction) -} - -model Profile { - id Int @id @default(autoincrement()) - bio String? - userId Int @unique - //edit-next-line - user User @relation(fields: [userId], references: [id], onDelete: NoAction, onUpdate: NoAction) -} - -model User { - id Int @id @default(autoincrement()) - name String? @db.VarChar(255) - email String @unique @db.VarChar(255) - //edit-start - posts Post[] - profile Profile? - //edit-end -} -``` - -In this example, the database schema did follow the [naming conventions](/orm/reference/prisma-schema-reference#naming-conventions) for Prisma ORM models (only the virtual relation fields that were generated from introspection did not adhere to them and needed adjustment). This optimizes the ergonomics of the generated Prisma Client API. - -
- Using custom model and field names - -Sometimes though, you may want to make additional changes to the names of the columns and tables that are exposed in the Prisma Client API. A common example is to translate _snake_case_ notation which is often used in database schemas into _PascalCase_ and _camelCase_ notations which feel more natural for JavaScript/TypeScript developers. - -Assume you obtained the following model from introspection that's based on _snake_case_ notation: - -```prisma no-lines -model my_user { - user_id Int @id @default(autoincrement()) - first_name String? - last_name String @unique -} -``` - -If you generated a Prisma Client API for this model, it would pick up the _snake_case_ notation in its API: - -```ts no-lines -const user = await prisma.my_user.create({ - data: { - first_name: 'Alice', - last_name: 'Smith', - }, -}) -``` - -If you don't want to use the table and column names from your database in your Prisma Client API, you can configure them with [`@map` and `@@map`](/orm/prisma-schema/data-model/models#mapping-model-names-to-tables-or-collections): - -```prisma no-lines -model MyUser { - userId Int @id @default(autoincrement()) @map("user_id") - firstName String? @map("first_name") - lastName String @unique @map("last_name") - - @@map("my_user") -} -``` - -With this approach, you can name your model and its fields whatever you like and use the `@map` (for field names) and `@@map` (for models names) to point to the underlying tables and columns. Your Prisma Client API now looks as follows: - -```ts no-lines -const user = await prisma.myUser.create({ - data: { - firstName: 'Alice', - lastName: 'Smith', - }, -}) -``` - -Learn more about this on the [Configuring your Prisma Client API](/orm/prisma-client/setup-and-configuration/custom-model-and-field-names) page. - -
diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/150-introspection-node-sqlserver.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/150-introspection-node-sqlserver.mdx deleted file mode 100644 index 983267bd6e..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/150-introspection-node-sqlserver.mdx +++ /dev/null @@ -1,225 +0,0 @@ ---- -title: 'Introspection for SQL Server in a JavaScript project' -sidebar_label: 'Introspection' -metaTitle: 'Introspection with Prisma ORM, JavaScript, and SQL Server' -metaDescription: 'Introspect your database with Prisma ORM, JavaScript, and SQL Server' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -hide_table_of_contents: true -sidebar_class_name: hidden-sidebar -pagination_prev: getting-started/setup-prisma/add-to-existing-project/relational-databases/connect-your-database-node-sqlserver -pagination_next: getting-started/setup-prisma/add-to-existing-project/relational-databases/baseline-your-database-node-sqlserver -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/relational-databases/introspection- ---- - - -## Introspect your database with Prisma ORM - -For the purpose of this guide, we'll use a demo SQL schema with three tables: - -```sql no-lines -CREATE TABLE [dbo].[Post] ( - [id] INT NOT NULL IDENTITY(1,1), - [createdAt] DATETIME2 NOT NULL CONSTRAINT [Post_createdAt_df] DEFAULT CURRENT_TIMESTAMP, - [updatedAt] DATETIME2 NOT NULL, - [title] VARCHAR(255) NOT NULL, - [content] NVARCHAR(1000), - [published] BIT NOT NULL CONSTRAINT [Post_published_df] DEFAULT 0, - [authorId] INT NOT NULL, - CONSTRAINT [Post_pkey] PRIMARY KEY ([id]) -); - -CREATE TABLE [dbo].[Profile] ( - [id] INT NOT NULL IDENTITY(1,1), - [bio] NVARCHAR(1000), - [userId] INT NOT NULL, - CONSTRAINT [Profile_pkey] PRIMARY KEY ([id]), - CONSTRAINT [Profile_userId_key] UNIQUE ([userId]) -); - -CREATE TABLE [dbo].[User] ( - [id] INT NOT NULL IDENTITY(1,1), - [email] NVARCHAR(1000) NOT NULL, - [name] NVARCHAR(1000), - CONSTRAINT [User_pkey] PRIMARY KEY ([id]), - CONSTRAINT [User_email_key] UNIQUE ([email]) -); - -ALTER TABLE [dbo].[Post] ADD CONSTRAINT [Post_authorId_fkey] FOREIGN KEY ([authorId]) REFERENCES [dbo].[User]([id]) ON DELETE NO ACTION ON UPDATE CASCADE; - -ALTER TABLE [dbo].[Profile] ADD CONSTRAINT [Profile_userId_fkey] FOREIGN KEY ([userId]) REFERENCES [dbo].[User]([id]) ON DELETE NO ACTION ON UPDATE CASCADE; -``` - -
-Expand for a graphical overview of the tables - -**User** - -| Column name | Type | Primary key | Foreign key | Required | Default | -| :---------- | :--------------- | :---------- | :---------- | :------- | :----------------- | -| `id` | `INT` | **✔️** | No | **✔️** | _autoincrementing_ | -| `name` | `NVARCHAR(1000)` | No | No | No | - | -| `email` | `NVARCHAR(1000)` | No | No | **✔️** | - | - -**Post** - -| Column name | Type | Primary key | Foreign key | Required | Default | -| :---------- | :--------------- | :---------- | :---------- | :------- | :----------------- | -| `id` | `INT` | **✔️** | No | **✔️** | _autoincrementing_ | -| `createdAt` | `DATETIME2` | No | No | **✔️** | `now()` | -| `updatedAt` | `DATETIME2` | No | No | **✔️** | | -| `title` | `VARCHAR(255)` | No | No | **✔️** | - | -| `content` | `NVARCHAR(1000)` | No | No | No | - | -| `published` | `BIT` | No | No | **✔️** | `false` | -| `authorId` | `INT` | No | **✔️** | **✔️** | - | - -**Profile** - -| Column name | Type | Primary key | Foreign key | Required | Default | -| :---------- | :--------------- | :---------- | :---------- | :------- | :----------------- | -| `id` | `INT` | **✔️** | No | **✔️** | _autoincrementing_ | -| `bio` | `NVARCHAR(1000)` | No | No | No | - | -| `userId` | `INT` | No | **✔️** | **✔️** | - | - -
- -As a next step, you will introspect your database. The result of the introspection will be a [data model](/orm/prisma-schema/data-model/models) inside your Prisma schema. - -Run the following command to introspect your database: - -```terminal copy -npx prisma db pull -``` - -This command reads the `DATABASE_URL` environment variable that's defined in `.env` and connects to your database. Once the connection is established, it introspects the database (i.e. it _reads the database schema_). It then translates the database schema from SQL into a Prisma data model. - -After the introspection is complete, your Prisma schema is updated: - -![Introspect your database](/img/getting-started/prisma-db-pull-generate-schema.png) - -The data model now looks similar to this (note that the fields on the models have been reordered for better readability): - -```prisma file=prisma/schema.prisma showLineNumbers -model Post { - id Int @id @default(autoincrement()) - title String @db.VarChar(255) - createdAt DateTime @default(now()) @db.Timestamp(6) - content String? - published Boolean @default(false) - authorId Int - User User @relation(fields: [authorId], references: [id]) -} - -model Profile { - id Int @id @default(autoincrement()) - bio String? - userId Int @unique - User User @relation(fields: [userId], references: [id]) -} - -model User { - id Int @id @default(autoincrement()) - name String? @db.VarChar(255) - email String @unique @db.VarChar(255) - Post Post[] - Profile Profile? -} -``` - -Prisma's data model is a declarative representation of your database schema and serves as the foundation for the generated Prisma Client library. Your Prisma Client instance will expose queries that are _tailored_ to these models. - -Right now, there's a few minor "issues" with the data model: - -- The `User` relation field is uppercased and therefore doesn't adhere to Prisma's [naming conventions](/orm/reference/prisma-schema-reference#naming-conventions-1) . To express more "semantics", it would also be nice if this field was called `author` to _describe_ the relationship between `User` and `Post` better. -- The `Post` and `Profile` relation fields on `User` as well as the `User` relation field on `Profile` are all uppercased. To adhere to Prisma's [naming conventions](/orm/reference/prisma-schema-reference#naming-conventions-1) , both fields should be lowercased to `post`, `profile` and `user`. -- Even after lowercasing, the `post` field on `User` is still slightly misnamed. That's because it actually refers to a [list](/orm/prisma-schema/data-model/models#type-modifiers) of posts – a better name therefore would be the plural form: `posts`. - -These changes are relevant for the generated Prisma Client API where using lowercased relation fields `author`, `posts`, `profile` and `user` will feel more natural and idiomatic to JavaScript/TypeScript developers. You can therefore [configure your Prisma Client API](/orm/prisma-client/setup-and-configuration/custom-model-and-field-names). - -Because [relation fields](/orm/prisma-schema/data-model/relations#relation-fields) are _virtual_ (i.e. they _do not directly manifest in the database_), you can manually rename them in your Prisma schema without touching the database: - -```prisma file=prisma/schema.prisma highlight=7,14,22,23;edit showLineNumbers -model Post { - id Int @id @default(autoincrement()) - title String @db.VarChar(255) - createdAt DateTime @default(now()) @db.Timestamp(6) - content String? - published Boolean @default(false) - //edit-next-line - author User @relation(fields: [authorId], references: [id]) - authorId Int -} - -model Profile { - id Int @id @default(autoincrement()) - bio String? - //edit-next-line - user User @relation(fields: [userId], references: [id]) - userId Int @unique -} - -model User { - id Int @id @default(autoincrement()) - email String @unique @db.VarChar(255) - name String? @db.VarChar(255) - //edit-start - posts Post[] - profile Profile? - //edit-end -} -``` - -In this example, the database schema did follow the [naming conventions](/orm/reference/prisma-schema-reference#naming-conventions) for Prisma ORM models (only the virtual relation fields that were generated from introspection did not adhere to them and needed adjustment). This optimizes the ergonomics of the generated Prisma Client API. - -
- Using custom model and field names - -Sometimes though, you may want to make additional changes to the names of the columns and tables that are exposed in the Prisma Client API. A common example is to translate _snake_case_ notation which is often used in database schemas into _PascalCase_ and _camelCase_ notations which feel more natural for JavaScript/TypeScript developers. - -Assume you obtained the following model from introspection that's based on _snake_case_ notation: - -```prisma no-lines -model my_user { - user_id Int @id @default(autoincrement()) - first_name String? - last_name String @unique -} -``` - -If you generated a Prisma Client API for this model, it would pick up the _snake_case_ notation in its API: - -```ts no-lines -const user = await prisma.my_user.create({ - data: { - first_name: 'Alice', - last_name: 'Smith', - }, -}) -``` - -If you don't want to use the table and column names from your database in your Prisma Client API, you can configure them with [`@map` and `@@map`](/orm/prisma-schema/data-model/models#mapping-model-names-to-tables-or-collections): - -```prisma no-lines -model MyUser { - userId Int @id @default(autoincrement()) @map("user_id") - firstName String? @map("first_name") - lastName String @unique @map("last_name") - - @@map("my_user") -} -``` - -With this approach, you can name your model and its fields whatever you like and use the `@map` (for field names) and `@@map` (for models names) to point to the underlying tables and columns. Your Prisma Client API now looks as follows: - -```ts no-lines -const user = await prisma.myUser.create({ - data: { - firstName: 'Alice', - lastName: 'Smith', - }, -}) -``` - -Learn more about this on the [Configuring your Prisma Client API](/orm/prisma-client/setup-and-configuration/custom-model-and-field-names) page. - -
diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/150-introspection-typescript-cockroachdb.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/150-introspection-typescript-cockroachdb.mdx deleted file mode 100644 index 64a55d9a57..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/150-introspection-typescript-cockroachdb.mdx +++ /dev/null @@ -1,218 +0,0 @@ ---- -title: 'Introspection for CockroachDB in a TypeScript project' -sidebar_label: 'Introspection' -metaTitle: 'Introspection with Prisma ORM, TypeScript, and CockroachDB' -metaDescription: 'Introspect your database with Prisma ORM, TypeScript, and CockroachDB' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -hide_table_of_contents: true -sidebar_class_name: hidden-sidebar -pagination_prev: getting-started/setup-prisma/add-to-existing-project/relational-databases/connect-your-database-typescript-cockroachdb -pagination_next: getting-started/setup-prisma/add-to-existing-project/relational-databases/baseline-your-database-typescript-cockroachdb -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/relational-databases/introspection- ---- - - -## Introspect your database with Prisma ORM - -For the purpose of this guide, we'll use a demo SQL schema with three tables: - -```sql no-lines -CREATE TABLE "User" ( - id INT8 PRIMARY KEY DEFAULT unique_rowid(), - name STRING(255), - email STRING(255) UNIQUE NOT NULL -); - -CREATE TABLE "Post" ( - id INT8 PRIMARY KEY DEFAULT unique_rowid(), - title STRING(255) UNIQUE NOT NULL, - "createdAt" TIMESTAMP NOT NULL DEFAULT now(), - content STRING, - published BOOLEAN NOT NULL DEFAULT false, - "authorId" INT8 NOT NULL, - FOREIGN KEY ("authorId") REFERENCES "User"(id) -); - -CREATE TABLE "Profile" ( - id INT8 PRIMARY KEY DEFAULT unique_rowid(), - bio STRING, - "userId" INT8 UNIQUE NOT NULL, - FOREIGN KEY ("userId") REFERENCES "User"(id) -); -``` - -> **Note**: Some fields are written in double quotes to ensure CockroachDB uses proper casing. If no double-quotes were used, CockroachDB would just read everything as _lowercase_ characters. - -
-Expand for a graphical overview of the tables - -**User** - -| Column name | Type | Primary key | Foreign key | Required | Default | -| :---------- | :------------ | :---------- | :---------- | :------- | :----------------- | -| `id` | `INT8` | **✔️** | No | **✔️** | _autoincrementing_ | -| `name` | `STRING(255)` | No | No | No | - | -| `email` | `STRING(255)` | No | No | **✔️** | - | - -**Post** - -| Column name | Type | Primary key | Foreign key | Required | Default | -| :---------- | :------------ | :---------- | :---------- | :------- | :----------------- | -| `id` | `INT8` | **✔️** | No | **✔️** | _autoincrementing_ | -| `createdAt` | `TIMESTAMP` | No | No | **✔️** | `now()` | -| `title` | `STRING(255)` | No | No | **✔️** | - | -| `content` | `STRING` | No | No | No | - | -| `published` | `BOOLEAN` | No | No | **✔️** | `false` | -| `authorId` | `INT8` | No | **✔️** | **✔️** | - | - -**Profile** - -| Column name | Type | Primary key | Foreign key | Required | Default | -| :---------- | :------- | :---------- | :---------- | :------- | :----------------- | -| `id` | `INT8` | **✔️** | No | **✔️** | _autoincrementing_ | -| `bio` | `STRING` | No | No | No | - | -| `userId` | `INT8` | No | **✔️** | **✔️** | - | - -
- -As a next step, you will introspect your database. The result of the introspection will be a [data model](/orm/prisma-schema/data-model/models) inside your Prisma schema. - -Run the following command to introspect your database: - -```terminal copy -npx prisma db pull -``` - -This command reads the environment variable used to define the `url` in your `schema.prisma`, `DATABASE_URL`, that in our case is set in `.env` and connects to your database. Once the connection is established, it introspects the database (i.e. it _reads the database schema_). It then translates the database schema from SQL into a Prisma data model. - -After the introspection is complete, your Prisma schema is updated: - -![Introspect your database](/img/getting-started/prisma-db-pull-generate-schema.png) - -The data model now looks similar to this: - -```prisma file=prisma/schema.prisma showLineNumbers -model Post { - id BigInt @id @default(autoincrement()) - title String @unique @db.String(255) - createdAt DateTime @default(now()) @db.Timestamp(6) - content String? - published Boolean @default(false) - authorId BigInt - User User @relation(fields: [authorId], references: [id], onDelete: NoAction, onUpdate: NoAction) -} - -model Profile { - id BigInt @id @default(autoincrement()) - bio String? - userId BigInt @unique - User User @relation(fields: [userId], references: [id], onDelete: NoAction, onUpdate: NoAction) -} - -model User { - id BigInt @id @default(autoincrement()) - name String? @db.String(255) - email String @unique @db.String(255) - Post Post[] - Profile Profile? -} -``` - -Prisma ORM's data model is a declarative representation of your database schema and serves as the foundation for the generated Prisma Client library. Your Prisma Client instance will expose queries that are _tailored_ to these models. - -Right now, there's a few minor "issues" with the data model: - -- The `User` relation field is uppercased and therefore doesn't adhere to Prisma's [naming conventions](/orm/reference/prisma-schema-reference#naming-conventions-1) . To express more "semantics", it would also be nice if this field was called `author` to _describe_ the relationship between `User` and `Post` better. -- The `Post` and `Profile` relation fields on `User` as well as the `User` relation field on `Profile` are all uppercased. To adhere to Prisma's [naming conventions](/orm/reference/prisma-schema-reference#naming-conventions-1) , both fields should be lowercased to `post`, `profile` and `user`. -- Even after lowercasing, the `post` field on `User` is still slightly misnamed. That's because it actually refers to a [list](/orm/prisma-schema/data-model/models#type-modifiers) of posts – a better name therefore would be the plural form: `posts`. - -These changes are relevant for the generated Prisma Client API where using lowercased relation fields `author`, `posts`, `profile` and `user` will feel more natural and idiomatic to JavaScript/TypeScript developers. You can therefore [configure your Prisma Client API](/orm/prisma-client/setup-and-configuration/custom-model-and-field-names). - -Because [relation fields](/orm/prisma-schema/data-model/relations#relation-fields) are _virtual_ (i.e. they _do not directly manifest in the database_), you can manually rename them in your Prisma schema without touching the database: - -```prisma file=prisma/schema.prisma highlight=8,15,22,23;edit showLineNumbers -model Post { - id BigInt @id @default(autoincrement()) - title String @unique @db.String(255) - createdAt DateTime @default(now()) @db.Timestamp(6) - content String? - published Boolean @default(false) - authorId BigInt - //edit-next-line - author User @relation(fields: [authorId], references: [id], onDelete: NoAction, onUpdate: NoAction) -} - -model Profile { - id BigInt @id @default(autoincrement()) - bio String? - userId BigInt @unique - //edit-next-line - user User @relation(fields: [userId], references: [id], onDelete: NoAction, onUpdate: NoAction) -} - -model User { - id BigInt @id @default(autoincrement()) - name String? @db.String(255) - email String @unique @db.String(255) - //edit-start - posts Post[] - profile Profile? - //edit-end -} -``` - -In this example, the database schema did follow the [naming conventions](/orm/reference/prisma-schema-reference#naming-conventions) for Prisma ORM models (only the virtual relation fields that were generated from introspection did not adhere to them and needed adjustment). This optimizes the ergonomics of the generated Prisma Client API. - -
- Using custom model and field names - -Sometimes though, you may want to make additional changes to the names of the columns and tables that are exposed in the Prisma Client API. A common example is to translate _snake_case_ notation which is often used in database schemas into _PascalCase_ and _camelCase_ notations which feel more natural for JavaScript/TypeScript developers. - -Assume you obtained the following model from introspection that's based on _snake_case_ notation: - -```prisma no-lines -model my_user { - user_id Int @id @default(sequence()) - first_name String? - last_name String @unique -} -``` - -If you generated a Prisma Client API for this model, it would pick up the _snake_case_ notation in its API: - -```ts no-lines -const user = await prisma.my_user.create({ - data: { - first_name: 'Alice', - last_name: 'Smith', - }, -}) -``` - -If you don't want to use the table and column names from your database in your Prisma Client API, you can configure them with [`@map` and `@@map`](/orm/prisma-schema/data-model/models#mapping-model-names-to-tables-or-collections): - -```prisma no-lines -model MyUser { - userId Int @id @default(sequence()) @map("user_id") - firstName String? @map("first_name") - lastName String @unique @map("last_name") - - @@map("my_user") -} -``` - -With this approach, you can name your model and its fields whatever you like and use the `@map` (for field names) and `@@map` (for models names) to point to the underlying tables and columns. Your Prisma Client API now looks as follows: - -```ts no-lines -const user = await prisma.myUser.create({ - data: { - firstName: 'Alice', - lastName: 'Smith', - }, -}) -``` - -Learn more about this on the [Configuring your Prisma Client API](/orm/prisma-client/setup-and-configuration/custom-model-and-field-names) page. - -
diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/150-introspection-typescript-mysql.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/150-introspection-typescript-mysql.mdx deleted file mode 100644 index 7df914b56b..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/150-introspection-typescript-mysql.mdx +++ /dev/null @@ -1,221 +0,0 @@ ---- -title: 'Introspection for MySQL in a TypeScript project' -sidebar_label: 'Introspection' -metaTitle: 'Introspection with Prisma ORM, TypeScript, and MySQL' -metaDescription: 'Introspect your existing project with Prisma ORM, TypeScript, and MySQL' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -hide_table_of_contents: true -sidebar_class_name: hidden-sidebar -pagination_prev: getting-started/setup-prisma/add-to-existing-project/relational-databases/connect-your-database-typescript-mysql -pagination_next: getting-started/setup-prisma/add-to-existing-project/relational-databases/baseline-your-database-typescript-mysql -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/relational-databases/introspection- ---- - - -## Introspect your database with Prisma ORM - -For the purpose of this guide, we'll use a demo SQL schema with three tables: - -```sql no-lines -CREATE TABLE User ( - id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL, - name VARCHAR(255), - email VARCHAR(255) UNIQUE NOT NULL -); - -CREATE TABLE Post ( - id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL, - title VARCHAR(255) NOT NULL, - createdAt TIMESTAMP NOT NULL DEFAULT now(), - content TEXT, - published BOOLEAN NOT NULL DEFAULT false, - authorId INTEGER NOT NULL, - FOREIGN KEY (authorId) REFERENCES User(id) -); - -CREATE TABLE Profile ( - id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL, - bio TEXT, - userId INTEGER UNIQUE NOT NULL, - FOREIGN KEY (userId) REFERENCES User(id) -); -``` - -
-Expand for a graphical overview of the tables - -**User** - -| Column name | Type | Primary key | Foreign key | Required | Default | -| :---------- | :------------- | :---------- | :---------- | :------- | :----------------- | -| `id` | `INTEGER` | **✔️** | No | **✔️** | _autoincrementing_ | -| `name` | `VARCHAR(255)` | No | No | No | - | -| `email` | `VARCHAR(255)` | No | No | **✔️** | - | - -**Post** - -| Column name | Type | Primary key | Foreign key | Required | Default | -| :---------- | :------------- | :---------- | :---------- | :------- | :----------------- | -| `id` | `INTEGER` | **✔️** | No | **✔️** | _autoincrementing_ | -| `createdAt` | `DATETIME(3)` | No | No | **✔️** | `now()` | -| `title` | `VARCHAR(255)` | No | No | **✔️** | - | -| `content` | `TEXT` | No | No | No | - | -| `published` | `BOOLEAN` | No | No | **✔️** | `false` | -| `authorId` | `INTEGER` | No | **✔️** | **✔️** | `false` | - -**Profile** - -| Column name | Type | Primary key | Foreign key | Required | Default | -| :---------- | :-------- | :---------- | :---------- | :------- | :----------------- | -| `id` | `INTEGER` | **✔️** | No | **✔️** | _autoincrementing_ | -| `bio` | `TEXT` | No | No | No | - | -| `userId` | `INTEGER` | No | **✔️** | **✔️** | - | - -
- -As a next step, you will introspect your database. The result of the introspection will be a [data model](/orm/prisma-schema/data-model/models) inside your Prisma schema. - -Run the following command to introspect your database: - -```terminal copy -npx prisma db pull -``` - -This command reads the `DATABASE_URL` environment variable that's defined in `.env` and connects to your database. Once the connection is established, it introspects the database (i.e. it _reads the database schema_). It then translates the database schema from SQL into a Prisma data model. - -After the introspection is complete, your Prisma schema is updated: - -![Introspect your database](/img/getting-started/prisma-db-pull-generate-schema.png) - -The data model now looks similar to this (note that the fields on the models have been reordered for better readability): - -```prisma file=prisma/schema.prisma showLineNumbers -model Post { - id Int @id @default(autoincrement()) - title String @db.VarChar(255) - createdAt DateTime @default(now()) @db.Timestamp(0) - content String? @db.Text - published Boolean @default(false) - authorId Int - User User @relation(fields: [authorId], references: [id], onDelete: NoAction, onUpdate: NoAction, map: "Post_ibfk_1") - - @@index([authorId], map: "authorId") -} - -model Profile { - id Int @id @default(autoincrement()) - bio String? @db.Text - userId Int @unique(map: "userId") - User User @relation(fields: [userId], references: [id], onDelete: NoAction, onUpdate: NoAction, map: "Profile_ibfk_1") -} - -model User { - id Int @id @default(autoincrement()) - name String? @db.VarChar(255) - email String @unique(map: "email") @db.VarChar(255) - Post Post[] - Profile Profile? -} -``` - -:::info - -Refer to the [Prisma schema reference](/orm/reference/prisma-schema-reference) for detailed information about the schema definition. - -::: - -Prisma ORM's data model is a declarative representation of your database schema and serves as the foundation for the generated Prisma Client library. Your Prisma Client instance will expose queries that are _tailored_ to these models. - -Right now, there's a few minor "issues" with the data model: - -- The `User` relation field is uppercased and therefore doesn't adhere to Prisma's [naming conventions](/orm/reference/prisma-schema-reference#naming-conventions-1) . To express more "semantics", it would also be nice if this field was called `author` to _describe_ the relationship between `User` and `Post` better. -- The `Post` and `Profile` relation fields on `User` as well as the `User` relation field on `Profile` are all uppercased. To adhere to Prisma's [naming conventions](/orm/reference/prisma-schema-reference#naming-conventions-1) , both fields should be lowercased to `post`, `profile` and `user`. -- Even after lowercasing, the `post` field on `User` is still slightly misnamed. That's because it actually refers to a [list](/orm/prisma-schema/data-model/models#type-modifiers) of posts – a better name therefore would be the plural form: `posts`. - -These changes are relevant for the generated Prisma Client API where using lowercased relation fields `author`, `posts`, `profile` and `user` will feel more natural and idiomatic to JavaScript/TypeScript developers. You can therefore [configure your Prisma Client API](/orm/prisma-client/setup-and-configuration/custom-model-and-field-names). - -Because [relation fields](/orm/prisma-schema/data-model/relations#relation-fields) are _virtual_ (i.e. they _do not directly manifest in the database_), you can manually rename them in your Prisma schema without touching the database: - -```prisma file=prisma/schema.prisma highlight=8,17,24,25;edit showLineNumbers -model Post { - id Int @id @default(autoincrement()) - title String @db.VarChar(255) - createdAt DateTime @default(now()) @db.Timestamp(0) - content String? @db.Text - published Boolean @default(false) - authorId Int - //edit-next-line - author User @relation(fields: [authorId], references: [id], onDelete: NoAction, onUpdate: NoAction, map: "Post_ibfk_1") - - @@index([authorId], map: "authorId") -} - -model Profile { - id Int @id @default(autoincrement()) - bio String? @db.Text - userId Int @unique(map: "userId") - //edit-next-line - user User @relation(fields: [userId], references: [id], onDelete: NoAction, onUpdate: NoAction, map: "Profile_ibfk_1") -} - -model User { - id Int @id @default(autoincrement()) - name String? @db.VarChar(255) - email String @unique(map: "email") @db.VarChar(255) - //edit-start - posts Post[] - profile Profile? - //edit-end -} -``` - -In this example, the database schema did follow the [naming conventions](/orm/reference/prisma-schema-reference#naming-conventions) for Prisma ORM models (only the virtual relation fields that were generated from introspection did not adhere to them and needed adjustment). This optimizes the ergonomics of the generated Prisma Client API. - -Sometimes though, you may want to make additional changes to the names of the columns and tables that are exposed in the Prisma Client API. A common example is to translate _snake_case_ notation which is often used in database schemas into _PascalCase_ and _camelCase_ notations which feel more natural for JavaScript/TypeScript developers. - -Assume you obtained the following model from introspection that's based on _snake_case_ notation: - -```prisma no-lines -model my_user { - user_id Int @id @default(autoincrement()) - first_name String? - last_name String @unique -} -``` - -If you generated a Prisma Client API for this model, it would pick up the _snake_case_ notation in its API: - -```ts no-lines -const user = await prisma.my_user.create({ - data: { - first_name: 'Alice', - last_name: 'Smith', - }, -}) -``` - -If you don't want to use the table and column names from your database in your Prisma Client API, you can configure them with [`@map` and `@@map`](/orm/prisma-schema/data-model/models#mapping-model-names-to-tables-or-collections): - -```prisma no-lines -model MyUser { - userId Int @id @default(autoincrement()) @map("user_id") - firstName String? @map("first_name") - lastName String @unique @map("last_name") - - @@map("my_user") -} -``` - -With this approach, you can name your model and its fields whatever you like and use the `@map` (for field names) and `@@map` (for models names) to point to the underlying tables and columns. Your Prisma Client API now looks as follows: - -```ts no-lines -const user = await prisma.myUser.create({ - data: { - firstName: 'Alice', - lastName: 'Smith', - }, -}) -``` - -Learn more about this on the [Configuring your Prisma Client API](/orm/prisma-client/setup-and-configuration/custom-model-and-field-names) page. diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/150-introspection-typescript-planetscale.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/150-introspection-typescript-planetscale.mdx deleted file mode 100644 index 07b8f12df8..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/150-introspection-typescript-planetscale.mdx +++ /dev/null @@ -1,237 +0,0 @@ ---- -title: 'Introspection for PlanetScale in a TypeScript project' -sidebar_label: 'Introspection' -metaTitle: 'Introspection with Prisma ORM, TypeScript, and PlanetScale' -metaDescription: 'Introspect your existing project with Prisma ORM, TypeScript, and PlanetScale' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -hide_table_of_contents: true -sidebar_class_name: hidden-sidebar -pagination_prev: getting-started/setup-prisma/add-to-existing-project/relational-databases/connect-your-database-typescript-planetscale -pagination_next: getting-started/setup-prisma/add-to-existing-project/relational-databases/install-prisma-client-typescript-planetscale -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/relational-databases/introspection- ---- - - -## Introspect your database with Prisma ORM - -For the purpose of this guide, we'll use a demo SQL schema with three tables: - -```sql no-lines -CREATE TABLE `Post` ( - `id` int NOT NULL AUTO_INCREMENT, - `createdAt` datetime(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3), - `updatedAt` datetime(3) NOT NULL, - `title` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, - `content` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, - `published` tinyint(1) NOT NULL DEFAULT '0', - `authorId` int NOT NULL, - PRIMARY KEY (`id`), - KEY `Post_authorId_idx` (`authorId`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; - -CREATE TABLE `Profile` ( - `id` int NOT NULL AUTO_INCREMENT, - `bio` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, - `userId` int NOT NULL, - PRIMARY KEY (`id`), - UNIQUE KEY `Profile_userId_key` (`userId`), - KEY `Profile_userId_idx` (`userId`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; - -CREATE TABLE `User` ( - `id` int NOT NULL AUTO_INCREMENT, - `email` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL, - `name` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, - PRIMARY KEY (`id`), - UNIQUE KEY `User_email_key` (`email`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -``` - -
-Expand for a graphical overview of the tables - -**Post** - -| Column name | Type | Primary key | Foreign key | Required | Default | -| :---------- | :------------- | :---------- | :---------- | :------- | :----------------- | -| `id` | `int` | **✔️** | No | **✔️** | _autoincrementing_ | -| `createdAt` | `datetime(3)` | No | No | **✔️** | `now()` | -| `updatedAt` | `datetime(3)` | No | No | **✔️** | | -| `title` | `varchar(255)` | No | No | **✔️** | - | -| `content` | `varchar(191)` | No | No | No | - | -| `published` | `tinyint(1)` | No | No | **✔️** | `false` | -| `authorId` | `int` | No | No | **✔️** | - | - -**Profile** - -| Column name | Type | Primary key | Foreign key | Required | Default | -| :---------- | :------------- | :---------- | :---------- | :------- | :----------------- | -| `id` | `int` | **✔️** | No | **✔️** | _autoincrementing_ | -| `bio` | `varchar(191)` | No | No | No | - | -| `userId` | `int` | No | No | **✔️** | - | - -**User** - -| Column name | Type | Primary key | Foreign key | Required | Default | -| :---------- | :------------- | :---------- | :---------- | :------- | :----------------- | -| `id` | `int` | **✔️** | No | **✔️** | _autoincrementing_ | -| `name` | `varchar(191)` | No | No | No | - | -| `email` | `varchar(191)` | No | No | **✔️** | - | - -
- -As a next step, you will introspect your database. The result of the introspection will be a [data model](/orm/prisma-schema/data-model/models) inside your Prisma schema. - -Run the following command to introspect your database: - -```terminal copy -npx prisma db pull -``` - -This command reads the `DATABASE_URL` environment variable that's defined in `.env` and connects to your database. Once the connection is established, it introspects the database (i.e. it _reads the database schema_). It then translates the database schema from SQL into a Prisma data model. - -After the introspection is complete, your Prisma schema is updated: - -![Introspect your database](/img/getting-started/prisma-db-pull-generate-schema.png) - -The data model now looks similar to this: - -```prisma file=prisma/schema.prisma showLineNumbers -model Post { - id Int @id @default(autoincrement()) - createdAt DateTime @default(now()) - updatedAt DateTime - title String @db.VarChar(255) - content String? - published Boolean @default(false) - authorId Int - - @@index([authorId]) -} - -model Profile { - id Int @id @default(autoincrement()) - bio String? - userId Int @unique - - @@index([userId]) -} - -model User { - id Int @id @default(autoincrement()) - email String @unique - name String? -} -``` - -:::info - -Refer to the [Prisma schema reference](/orm/reference/prisma-schema-reference) for detailed information about the schema definition. - -::: - -Prisma's data model is a declarative representation of your database schema and serves as the foundation for the generated Prisma Client library. Your Prisma Client instance will expose queries that are _tailored_ to these models. - -You will then need to add in any missing relations between your data using [relation fields](/orm/prisma-schema/data-model/relations#relation-fields): - -```prisma file=prisma/schema.prisma highlight=8,17,27,28;add showLineNumbers -model Post { - id Int @id @default(autoincrement()) - createdAt DateTime @default(now()) - updatedAt DateTime - title String @db.VarChar(255) - content String? - published Boolean @default(false) - //add-next-line - author User @relation(fields: [authorId], references: [id]) - authorId Int - - @@index([authorId]) -} - -model Profile { - id Int @id @default(autoincrement()) - bio String? - //add-next-line - user User @relation(fields: [userId], references: [id]) - userId Int @unique - - @@index([userId]) -} - -model User { - id Int @id @default(autoincrement()) - email String @unique - name String? - //add-start - posts Post[] - profile Profile? - //add-end -} -``` - -After this, run introspection on your database for a second time: - -```terminal copy -npx prisma db pull -``` - -Prisma Migrate will now keep the manually added relation fields. - -Because relation fields are _virtual_ (i.e. they _do not directly manifest in the database_), you can manually rename them in your Prisma schema without touching the database. - -In this example, the database schema follows the [naming conventions](/orm/reference/prisma-schema-reference#naming-conventions) for Prisma ORM models. This optimizes the ergonomics of the generated Prisma Client API. - -
- Using custom model and field names - -Sometimes though, you may want to make additional changes to the names of the columns and tables that are exposed in the Prisma Client API. A common example is to translate _snake_case_ notation which is often used in database schemas into _PascalCase_ and _camelCase_ notations which feel more natural for JavaScript/TypeScript developers. - -Assume you obtained the following model from introspection that's based on _snake_case_ notation: - -```prisma no-lines -model my_user { - user_id Int @id @default(autoincrement()) - first_name String? - last_name String @unique -} -``` - -If you generated a Prisma Client API for this model, it would pick up the _snake_case_ notation in its API: - -```ts no-lines -const user = await prisma.my_user.create({ - data: { - first_name: 'Alice', - last_name: 'Smith', - }, -}) -``` - -If you don't want to use the table and column names from your database in your Prisma Client API, you can configure them with [`@map` and `@@map`](/orm/prisma-schema/data-model/models#mapping-model-names-to-tables-or-collections): - -```prisma no-lines -model MyUser { - userId Int @id @default(autoincrement()) @map("user_id") - firstName String? @map("first_name") - lastName String @unique @map("last_name") - - @@map("my_user") -} -``` - -With this approach, you can name your model and its fields whatever you like and use the `@map` (for field names) and `@@map` (for models names) to point to the underlying tables and columns. Your Prisma Client API now looks as follows: - -```ts no-lines -const user = await prisma.myUser.create({ - data: { - firstName: 'Alice', - lastName: 'Smith', - }, -}) -``` - -Learn more about this on the [Configuring your Prisma Client API](/orm/prisma-client/setup-and-configuration/custom-model-and-field-names) page. - -
diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/150-introspection-typescript-postgresql.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/150-introspection-typescript-postgresql.mdx deleted file mode 100644 index e87d3f4888..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/150-introspection-typescript-postgresql.mdx +++ /dev/null @@ -1,217 +0,0 @@ ---- -title: 'Introspection for PostgreSQL in a TypeScript project' -sidebar_label: 'Introspection' -metaTitle: 'Introspection with Prisma ORM, TypeScript, and PostgreSQL' -metaDescription: 'Introspect your existing project with Prisma ORM, TypeScript, and PostgreSQL' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -hide_table_of_contents: true -pagination_prev: getting-started/setup-prisma/add-to-existing-project/relational-databases/connect-your-database-typescript-postgresql -pagination_next: getting-started/setup-prisma/add-to-existing-project/relational-databases/baseline-your-database-typescript-postgresql -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/relational-databases/introspection- ---- - - -## Introspect your database with Prisma ORM - -For the purpose of this guide, we'll use a demo SQL schema with three tables: - -```sql no-lines -CREATE TABLE "public"."User" ( - id SERIAL PRIMARY KEY NOT NULL, - name VARCHAR(255), - email VARCHAR(255) UNIQUE NOT NULL -); - -CREATE TABLE "public"."Post" ( - id SERIAL PRIMARY KEY NOT NULL, - title VARCHAR(255) NOT NULL, - "createdAt" TIMESTAMP NOT NULL DEFAULT now(), - content TEXT, - published BOOLEAN NOT NULL DEFAULT false, - "authorId" INTEGER NOT NULL, - FOREIGN KEY ("authorId") REFERENCES "public"."User"(id) -); - -CREATE TABLE "public"."Profile" ( - id SERIAL PRIMARY KEY NOT NULL, - bio TEXT, - "userId" INTEGER UNIQUE NOT NULL, - FOREIGN KEY ("userId") REFERENCES "public"."User"(id) -); -``` - -> **Note**: Some fields are written in double-quotes to ensure PostgreSQL uses proper casing. If no double-quotes were used, PostgreSQL would just read everything as _lowercase_ characters. - -
-Expand for a graphical overview of the tables - -**User** - -| Column name | Type | Primary key | Foreign key | Required | Default | -| :---------- | :------------- | :---------- | :---------- | :------- | :----------------- | -| `id` | `SERIAL` | **✔️** | No | **✔️** | _autoincrementing_ | -| `name` | `VARCHAR(255)` | No | No | No | - | -| `email` | `VARCHAR(255)` | No | No | **✔️** | - | - -**Post** - -| Column name | Type | Primary key | Foreign key | Required | Default | -| :---------- | :------------- | :---------- | :---------- | :------- | :----------------- | -| `id` | `SERIAL` | **✔️** | No | **✔️** | _autoincrementing_ | -| `createdAt` | `TIMESTAMP` | No | No | **✔️** | `now()` | -| `title` | `VARCHAR(255)` | No | No | **✔️** | - | -| `content` | `TEXT` | No | No | No | - | -| `published` | `BOOLEAN` | No | No | **✔️** | `false` | -| `authorId` | `INTEGER` | No | **✔️** | **✔️** | - | - -**Profile** - -| Column name | Type | Primary key | Foreign key | Required | Default | -| :---------- | :-------- | :---------- | :---------- | :------- | :----------------- | -| `id` | `SERIAL` | **✔️** | No | **✔️** | _autoincrementing_ | -| `bio` | `TEXT` | No | No | No | - | -| `userId` | `INTEGER` | No | **✔️** | **✔️** | - | - -
- -As a next step, you will introspect your database. The result of the introspection will be a [data model](/orm/prisma-schema/data-model/models) inside your Prisma schema. - -Run the following command to introspect your database: - -```terminal copy -npx prisma db pull -``` - -This command reads the `DATABASE_URL` environment variable that's defined in `.env` and connects to your database. Once the connection is established, it introspects the database (i.e. it _reads the database schema_). It then translates the database schema from SQL into a data model in your Prisma schema. - -After the introspection is complete, your Prisma schema is updated: - -![Introspect your database with Prisma ORM](/img/getting-started/prisma-db-pull-generate-schema.png) - -The data model now looks similar to this (note that the fields on the models have been reordered for better readability): - -```prisma file=prisma/schema.prisma showLineNumbers -model Post { - id Int @id @default(autoincrement()) - title String @db.VarChar(255) - createdAt DateTime @default(now()) @db.Timestamp(6) - content String? - published Boolean @default(false) - authorId Int - User User @relation(fields: [authorId], references: [id], onDelete: NoAction, onUpdate: NoAction) -} - -model Profile { - id Int @id @default(autoincrement()) - bio String? - userId Int @unique - User User @relation(fields: [userId], references: [id], onDelete: NoAction, onUpdate: NoAction) -} - -model User { - id Int @id @default(autoincrement()) - name String? @db.VarChar(255) - email String @unique @db.VarChar(255) - Post Post[] - Profile Profile? -} -``` - -Prisma ORM's data model is a declarative representation of your database schema and serves as the foundation for the generated Prisma Client library. Your Prisma Client instance will expose queries that are _tailored_ to these models. - -Right now, there's a few minor "issues" with the data model: - -- The `User` relation field is uppercased and therefore doesn't adhere to Prisma's [naming conventions](/orm/reference/prisma-schema-reference#naming-conventions-1) . To express more "semantics", it would also be nice if this field was called `author` to _describe_ the relationship between `User` and `Post` better. -- The `Post` and `Profile` relation fields on `User` as well as the `User` relation field on `Profile` are all uppercased. To adhere to Prisma's [naming conventions](/orm/reference/prisma-schema-reference#naming-conventions-1) , both fields should be lowercased to `post`, `profile` and `user`. -- Even after lowercasing, the `post` field on `User` is still slightly misnamed. That's because it actually refers to a [list](/orm/prisma-schema/data-model/models#type-modifiers) of posts – a better name therefore would be the plural form: `posts`. - -These changes are relevant for the generated Prisma Client API where using lowercased relation fields `author`, `posts`, `profile` and `user` will feel more natural and idiomatic to JavaScript/TypeScript developers. You can therefore [configure your Prisma Client API](/orm/prisma-client/setup-and-configuration/custom-model-and-field-names). - -Because [relation fields](/orm/prisma-schema/data-model/relations#relation-fields) are _virtual_ (i.e. they _do not directly manifest in the database_), you can manually rename them in your Prisma schema without touching the database: - -```prisma file=prisma/schema.prisma highlight=8,15,22,23;edit showLineNumbers -model Post { - id Int @id @default(autoincrement()) - title String @db.VarChar(255) - createdAt DateTime @default(now()) @db.Timestamp(6) - content String? - published Boolean @default(false) - authorId Int - //edit-next-line - author User @relation(fields: [authorId], references: [id], onDelete: NoAction, onUpdate: NoAction) -} - -model Profile { - id Int @id @default(autoincrement()) - bio String? - userId Int @unique - //edit-next-line - user User @relation(fields: [userId], references: [id], onDelete: NoAction, onUpdate: NoAction) -} - -model User { - id Int @id @default(autoincrement()) - name String? @db.VarChar(255) - email String @unique @db.VarChar(255) - //edit-start - posts Post[] - profile Profile? - //edit-end -} -``` - -In this example, the database schema did follow the [naming conventions](/orm/reference/prisma-schema-reference#naming-conventions) for Prisma ORM models (only the virtual relation fields that were generated from introspection did not adhere to them and needed adjustment). This optimizes the ergonomics of the generated Prisma Client API. - -
- Using custom model and field names - -Sometimes though, you may want to make additional changes to the names of the columns and tables that are exposed in the Prisma Client API. A common example is to translate _snake_case_ notation which is often used in database schemas into _PascalCase_ and _camelCase_ notations which feel more natural for JavaScript/TypeScript developers. - -Assume you obtained the following model from introspection that's based on _snake_case_ notation: - -```prisma no-lines -model my_user { - user_id Int @id @default(autoincrement()) - first_name String? - last_name String @unique -} -``` - -If you generated a Prisma Client API for this model, it would pick up the _snake_case_ notation in its API: - -```ts no-lines -const user = await prisma.my_user.create({ - data: { - first_name: 'Alice', - last_name: 'Smith', - }, -}) -``` - -If you don't want to use the table and column names from your database in your Prisma Client API, you can configure them with [`@map` and `@@map`](/orm/prisma-schema/data-model/models#mapping-model-names-to-tables-or-collections): - -```prisma no-lines -model MyUser { - userId Int @id @default(autoincrement()) @map("user_id") - firstName String? @map("first_name") - lastName String @unique @map("last_name") - - @@map("my_user") -} -``` - -With this approach, you can name your model and its fields whatever you like and use the `@map` (for field names) and `@@map` (for models names) to point to the underlying tables and columns. Your Prisma Client API now looks as follows: - -```ts no-lines -const user = await prisma.myUser.create({ - data: { - firstName: 'Alice', - lastName: 'Smith', - }, -}) -``` - -Learn more about this on the [Configuring your Prisma Client API](/orm/prisma-client/setup-and-configuration/custom-model-and-field-names) page. - -
diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/150-introspection-typescript-sqlserver.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/150-introspection-typescript-sqlserver.mdx deleted file mode 100644 index 811cbef53c..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/150-introspection-typescript-sqlserver.mdx +++ /dev/null @@ -1,225 +0,0 @@ ---- -title: 'Introspection for SQL Server in a TypeScript project' -sidebar_label: 'Introspection' -metaTitle: 'Introspection with Prisma ORM, TypeScript, and SQL Server' -metaDescription: 'Introspect your existing project with Prisma ORM, TypeScript, and SQL Server' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -hide_table_of_contents: true -sidebar_class_name: hidden-sidebar -pagination_prev: getting-started/setup-prisma/add-to-existing-project/relational-databases/connect-your-database-typescript-sqlserver -pagination_next: getting-started/setup-prisma/add-to-existing-project/relational-databases/baseline-your-database-typescript-sqlserver -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/relational-databases/introspection- ---- - - -## Introspect your database with Prisma ORM - -For the purpose of this guide, we'll use a demo SQL schema with three tables: - -```sql no-lines -CREATE TABLE [dbo].[Post] ( - [id] INT NOT NULL IDENTITY(1,1), - [createdAt] DATETIME2 NOT NULL CONSTRAINT [Post_createdAt_df] DEFAULT CURRENT_TIMESTAMP, - [updatedAt] DATETIME2 NOT NULL, - [title] VARCHAR(255) NOT NULL, - [content] NVARCHAR(1000), - [published] BIT NOT NULL CONSTRAINT [Post_published_df] DEFAULT 0, - [authorId] INT NOT NULL, - CONSTRAINT [Post_pkey] PRIMARY KEY ([id]) -); - -CREATE TABLE [dbo].[Profile] ( - [id] INT NOT NULL IDENTITY(1,1), - [bio] NVARCHAR(1000), - [userId] INT NOT NULL, - CONSTRAINT [Profile_pkey] PRIMARY KEY ([id]), - CONSTRAINT [Profile_userId_key] UNIQUE ([userId]) -); - -CREATE TABLE [dbo].[User] ( - [id] INT NOT NULL IDENTITY(1,1), - [email] NVARCHAR(1000) NOT NULL, - [name] NVARCHAR(1000), - CONSTRAINT [User_pkey] PRIMARY KEY ([id]), - CONSTRAINT [User_email_key] UNIQUE ([email]) -); - -ALTER TABLE [dbo].[Post] ADD CONSTRAINT [Post_authorId_fkey] FOREIGN KEY ([authorId]) REFERENCES [dbo].[User]([id]) ON DELETE NO ACTION ON UPDATE CASCADE; - -ALTER TABLE [dbo].[Profile] ADD CONSTRAINT [Profile_userId_fkey] FOREIGN KEY ([userId]) REFERENCES [dbo].[User]([id]) ON DELETE NO ACTION ON UPDATE CASCADE; -``` - -
-Expand for a graphical overview of the tables - -**User** - -| Column name | Type | Primary key | Foreign key | Required | Default | -| :---------- | :--------------- | :---------- | :---------- | :------- | :----------------- | -| `id` | `INT` | **✔️** | No | **✔️** | _autoincrementing_ | -| `name` | `NVARCHAR(1000)` | No | No | No | - | -| `email` | `NVARCHAR(1000)` | No | No | **✔️** | - | - -**Post** - -| Column name | Type | Primary key | Foreign key | Required | Default | -| :---------- | :--------------- | :---------- | :---------- | :------- | :----------------- | -| `id` | `INT` | **✔️** | No | **✔️** | _autoincrementing_ | -| `createdAt` | `DATETIME2` | No | No | **✔️** | `now()` | -| `updatedAt` | `DATETIME2` | No | No | **✔️** | | -| `title` | `VARCHAR(255)` | No | No | **✔️** | - | -| `content` | `NVARCHAR(1000)` | No | No | No | - | -| `published` | `BIT` | No | No | **✔️** | `false` | -| `authorId` | `INT` | No | **✔️** | **✔️** | - | - -**Profile** - -| Column name | Type | Primary key | Foreign key | Required | Default | -| :---------- | :--------------- | :---------- | :---------- | :------- | :----------------- | -| `id` | `INT` | **✔️** | No | **✔️** | _autoincrementing_ | -| `bio` | `NVARCHAR(1000)` | No | No | No | - | -| `userId` | `INT` | No | **✔️** | **✔️** | - | - -
- -As a next step, you will introspect your database. The result of the introspection will be a [data model](/orm/prisma-schema/data-model/models) inside your Prisma schema. - -Run the following command to introspect your database: - -```terminal copy -npx prisma db pull -``` - -This command reads the `DATABASE_URL` environment variable that's defined in `.env` and connects to your database. Once the connection is established, it introspects the database (i.e. it _reads the database schema_). It then translates the database schema from SQL into a Prisma data model. - -After the introspection is complete, your Prisma schema is updated: - -![Introspect your database](/img/getting-started/prisma-db-pull-generate-schema.png) - -The data model now looks similar to this (note that the fields on the models have been reordered for better readability): - -```prisma file=prisma/schema.prisma showLineNumbers -model Post { - id Int @id @default(autoincrement()) - title String @db.VarChar(255) - createdAt DateTime @default(now()) @db.Timestamp(6) - content String? - published Boolean @default(false) - authorId Int - User User @relation(fields: [authorId], references: [id]) -} - -model Profile { - id Int @id @default(autoincrement()) - bio String? - userId Int @unique - User User @relation(fields: [userId], references: [id]) -} - -model User { - id Int @id @default(autoincrement()) - name String? @db.VarChar(255) - email String @unique @db.VarChar(255) - Post Post[] - Profile Profile? -} -``` - -Prisma's data model is a declarative representation of your database schema and serves as the foundation for the generated Prisma Client library. Your Prisma Client instance will expose queries that are _tailored_ to these models. - -Right now, there's a few minor "issues" with the data model: - -- The `User` relation field is uppercased and therefore doesn't adhere to Prisma's [naming conventions](/orm/reference/prisma-schema-reference#naming-conventions-1) . To express more "semantics", it would also be nice if this field was called `author` to _describe_ the relationship between `User` and `Post` better. -- The `Post` and `Profile` relation fields on `User` as well as the `User` relation field on `Profile` are all uppercased. To adhere to Prisma's [naming conventions](/orm/reference/prisma-schema-reference#naming-conventions-1) , both fields should be lowercased to `post`, `profile` and `user`. -- Even after lowercasing, the `post` field on `User` is still slightly misnamed. That's because it actually refers to a [list](/orm/prisma-schema/data-model/models#type-modifiers) of posts – a better name therefore would be the plural form: `posts`. - -These changes are relevant for the generated Prisma Client API where using lowercased relation fields `author`, `posts`, `profile` and `user` will feel more natural and idiomatic to JavaScript/TypeScript developers. You can therefore [configure your Prisma Client API](/orm/prisma-client/setup-and-configuration/custom-model-and-field-names). - -Because [relation fields](/orm/prisma-schema/data-model/relations#relation-fields) are _virtual_ (i.e. they _do not directly manifest in the database_), you can manually rename them in your Prisma schema without touching the database: - -```prisma file=prisma/schema.prisma highlight=7,14,22,23;edit showLineNumbers -model Post { - id Int @id @default(autoincrement()) - title String @db.VarChar(255) - createdAt DateTime @default(now()) @db.Timestamp(6) - content String? - published Boolean @default(false) - //edit-next-line - author User @relation(fields: [authorId], references: [id]) - authorId Int -} - -model Profile { - id Int @id @default(autoincrement()) - bio String? - //edit-next-line - user User @relation(fields: [userId], references: [id]) - userId Int @unique -} - -model User { - id Int @id @default(autoincrement()) - email String @unique @db.VarChar(255) - name String? @db.VarChar(255) - //edit-start - posts Post[] - profile Profile? - //edit-end -} -``` - -In this example, the database schema did follow the [naming conventions](/orm/reference/prisma-schema-reference#naming-conventions) for Prisma ORM models (only the virtual relation fields that were generated from introspection did not adhere to them and needed adjustment). This optimizes the ergonomics of the generated Prisma Client API. - -
- Using custom model and field names - -Sometimes though, you may want to make additional changes to the names of the columns and tables that are exposed in the Prisma Client API. A common example is to translate _snake_case_ notation which is often used in database schemas into _PascalCase_ and _camelCase_ notations which feel more natural for JavaScript/TypeScript developers. - -Assume you obtained the following model from introspection that's based on _snake_case_ notation: - -```prisma no-lines -model my_user { - user_id Int @id @default(autoincrement()) - first_name String? - last_name String @unique -} -``` - -If you generated a Prisma Client API for this model, it would pick up the _snake_case_ notation in its API: - -```ts no-lines -const user = await prisma.my_user.create({ - data: { - first_name: 'Alice', - last_name: 'Smith', - }, -}) -``` - -If you don't want to use the table and column names from your database in your Prisma Client API, you can configure them with [`@map` and `@@map`](/orm/prisma-schema/data-model/models#mapping-model-names-to-tables-or-collections): - -```prisma no-lines -model MyUser { - userId Int @id @default(autoincrement()) @map("user_id") - firstName String? @map("first_name") - lastName String @unique @map("last_name") - - @@map("my_user") -} -``` - -With this approach, you can name your model and its fields whatever you like and use the `@map` (for field names) and `@@map` (for models names) to point to the underlying tables and columns. Your Prisma Client API now looks as follows: - -```ts no-lines -const user = await prisma.myUser.create({ - data: { - firstName: 'Alice', - lastName: 'Smith', - }, -}) -``` - -Learn more about this on the [Configuring your Prisma Client API](/orm/prisma-client/setup-and-configuration/custom-model-and-field-names) page. - -
diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/170-baseline-your-database-node-cockroachdb.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/170-baseline-your-database-node-cockroachdb.mdx deleted file mode 100644 index 25c6df618c..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/170-baseline-your-database-node-cockroachdb.mdx +++ /dev/null @@ -1,85 +0,0 @@ ---- -title: 'Baseline with Prisma ORM, JavaScript, and CockroachDB' -sidebar_label: 'Baseline your database' -metaTitle: 'Baseline with Prisma ORM, JavaScript, and CockroachDB' -metaDescription: 'Baseline your database with Prisma ORM, JavaScript, and CockroachDB' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'cockroachdb'] -hide_table_of_contents: true -sidebar_class_name: hidden-sidebar -pagination_prev: getting-started/setup-prisma/add-to-existing-project/relational-databases/introspection-node-cockroachdb -pagination_next: getting-started/setup-prisma/add-to-existing-project/relational-databases/install-prisma-client-node-cockroachdb -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/relational-databases/baseline-your-database- ---- - - -## Create an initial migration - -To use Prisma Migrate with the database you introspected in the last section, you will need to [baseline your database](/orm/prisma-migrate/getting-started). - -Baselining refers to initializing your migration history for a database that might already contain data and **cannot be reset**, such as your production database. Baselining tells Prisma Migrate to assume that one or more migrations have already been applied to your database. - -To baseline your database, use [`prisma migrate diff`](/orm/reference/prisma-cli-reference#migrate-diff) to compare your schema and database, and save the output into a SQL file. - -First, create a `migrations` directory and add a directory inside with your preferred name for the migration. In this example, we will use `0_init` as the migration name: - -```terminal -mkdir -p prisma/migrations/0_init -``` - - - -`-p` will recursively create any missing folders in the path you provide. - - - -Next, generate the migration file with `prisma migrate diff`. Use the following arguments: - -- `--from-empty`: assumes the data model you're migrating from is empty -- `--to-schema-datamodel`: the current database state using the URL in the `datasource` block -- `--script`: output a SQL script - -```terminal wrap -npx prisma migrate diff --from-empty --to-schema-datamodel prisma/schema.prisma --script > prisma/migrations/0_init/migration.sql -``` - -## Review the migration - -The command will generate a migration that should resemble the following script: - -```sql file=prisma/migrations/0_init/migration.sql -CREATE TABLE "User" ( - id INT8 PRIMARY KEY DEFAULT unique_rowid(), - name STRING(255), - email STRING(255) UNIQUE NOT NULL -); - -CREATE TABLE "Post" ( - id INT8 PRIMARY KEY DEFAULT unique_rowid(), - title STRING(255) UNIQUE NOT NULL, - "createdAt" TIMESTAMP NOT NULL DEFAULT now(), - content STRING, - published BOOLEAN NOT NULL DEFAULT false, - "authorId" INT8 NOT NULL, - FOREIGN KEY ("authorId") REFERENCES "User"(id) -); - -CREATE TABLE "Profile" ( - id INT8 PRIMARY KEY DEFAULT unique_rowid(), - bio STRING, - "userId" INT8 UNIQUE NOT NULL, - FOREIGN KEY ("userId") REFERENCES "User"(id) -); -``` - -Review the SQL migration file to ensure everything is correct. - -Next, mark the migration as applied using `prisma migrate resolve` with the `--applied` argument. - -```terminal -npx prisma migrate resolve --applied 0_init -``` - -The command will mark `0_init` as applied by adding it to the `_prisma_migrations` table. - -You now have a baseline for your current database schema. To make further changes to your database schema, you can update your Prisma schema and use `prisma migrate dev` to apply the changes to your database. diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/170-baseline-your-database-node-mysql.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/170-baseline-your-database-node-mysql.mdx deleted file mode 100644 index ec112cdc58..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/170-baseline-your-database-node-mysql.mdx +++ /dev/null @@ -1,101 +0,0 @@ ---- -title: 'Baseline with Prisma ORM, JavaScript, and MySQL' -sidebar_label: 'Baseline your database' -metaTitle: 'Baseline with Prisma ORM, JavaScript, and MySQL' -metaDescription: 'Baseline your database with Prisma ORM, JavaScript, and MySQL' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'cockroachdb'] -hide_table_of_contents: true -sidebar_class_name: hidden-sidebar -pagination_prev: getting-started/setup-prisma/add-to-existing-project/relational-databases/introspection-node-mysql -pagination_next: getting-started/setup-prisma/add-to-existing-project/relational-databases/install-prisma-client-node-mysql -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/relational-databases/baseline-your-database- ---- - - -## Create an initial migration - -To use Prisma Migrate with the database you introspected in the last section, you will need to [baseline your database](/orm/prisma-migrate/getting-started). - -Baselining refers to initializing your migration history for a database that might already contain data and **cannot be reset**, such as your production database. Baselining tells Prisma Migrate to assume that one or more migrations have already been applied to your database. - -To baseline your database, use [`prisma migrate diff`](/orm/reference/prisma-cli-reference#migrate-diff) to compare your schema and database, and save the output into a SQL file. - -First, create a `migrations` directory and add a directory inside with your preferred name for the migration. In this example, we will use `0_init` as the migration name: - -```terminal -mkdir -p prisma/migrations/0_init -``` - - - -`-p` will recursively create any missing folders in the path you provide. - - - -Next, generate the migration file with `prisma migrate diff`. Use the following arguments: - -- `--from-empty`: assumes the data model you're migrating from is empty -- `--to-schema-datamodel`: the current database state using the URL in the `datasource` block -- `--script`: output a SQL script - -```terminal wrap -npx prisma migrate diff --from-empty --to-schema-datamodel prisma/schema.prisma --script > prisma/migrations/0_init/migration.sql -``` - -## Review the migration - -The command will generate a migration that should resemble the following script: - -```sql file=prisma/migrations/0_init/migration.sql --- CreateTable -CREATE TABLE `Post` ( - `id` INTEGER NOT NULL AUTO_INCREMENT, - `title` VARCHAR(255) NOT NULL, - `createdAt` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0), - `content` TEXT NULL, - `published` BOOLEAN NOT NULL DEFAULT false, - `authorId` INTEGER NOT NULL, - - INDEX `authorId`(`authorId`), - PRIMARY KEY (`id`) -) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; - --- CreateTable -CREATE TABLE `Profile` ( - `id` INTEGER NOT NULL AUTO_INCREMENT, - `bio` TEXT NULL, - `userId` INTEGER NOT NULL, - - UNIQUE INDEX `userId`(`userId`), - PRIMARY KEY (`id`) -) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; - --- CreateTable -CREATE TABLE `User` ( - `id` INTEGER NOT NULL AUTO_INCREMENT, - `name` VARCHAR(255) NULL, - `email` VARCHAR(255) NOT NULL, - - UNIQUE INDEX `email`(`email`), - PRIMARY KEY (`id`) -) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; - --- AddForeignKey -ALTER TABLE `Post` ADD CONSTRAINT `Post_ibfk_1` FOREIGN KEY (`authorId`) REFERENCES `User`(`id`) ON DELETE RESTRICT ON UPDATE RESTRICT; - --- AddForeignKey -ALTER TABLE `Profile` ADD CONSTRAINT `Profile_ibfk_1` FOREIGN KEY (`userId`) REFERENCES `User`(`id`) ON DELETE RESTRICT ON UPDATE RESTRICT; -``` - -Review the SQL migration file to ensure everything is correct. - -Next, mark the migration as applied using `prisma migrate resolve` with the `--applied` argument. - -```terminal -npx prisma migrate resolve --applied 0_init -``` - -The command will mark `0_init` as applied by adding it to the `_prisma_migrations` table. - -You now have a baseline for your current database schema. To make further changes to your database schema, you can update your Prisma schema and use `prisma migrate dev` to apply the changes to your database. diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/170-baseline-your-database-node-postgresql.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/170-baseline-your-database-node-postgresql.mdx deleted file mode 100644 index 79cbdc4a08..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/170-baseline-your-database-node-postgresql.mdx +++ /dev/null @@ -1,104 +0,0 @@ ---- -title: 'Baseline with Prisma ORM, JavaScript, and PostgreSQL' -sidebar_label: 'Baseline your database' -metaTitle: 'Baseline with Prisma ORM, JavaScript, and PostgreSQL' -metaDescription: 'Baseline your database with Prisma ORM, JavaScript, and PostgreSQL' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'cockroachdb'] -hide_table_of_contents: true -sidebar_class_name: hidden-sidebar -pagination_prev: getting-started/setup-prisma/add-to-existing-project/relational-databases/introspection-node-postgresql -pagination_next: getting-started/setup-prisma/add-to-existing-project/relational-databases/install-prisma-client-node-postgresql -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/relational-databases/baseline-your-database- ---- - - -## Create an initial migration - -To use Prisma Migrate with the database you introspected in the last section, you will need to [baseline your database](/orm/prisma-migrate/getting-started). - -Baselining refers to initializing your migration history for a database that might already contain data and **cannot be reset**, such as your production database. Baselining tells Prisma Migrate to assume that one or more migrations have already been applied to your database. - -To baseline your database, use [`prisma migrate diff`](/orm/reference/prisma-cli-reference#migrate-diff) to compare your schema and database, and save the output into a SQL file. - -First, create a `migrations` directory and add a directory inside with your preferred name for the migration. In this example, we will use `0_init` as the migration name: - -```terminal -mkdir -p prisma/migrations/0_init -``` - - - -`-p` will recursively create any missing folders in the path you provide. - - - -Next, generate the migration file with `prisma migrate diff`. Use the following arguments: - -- `--from-empty`: assumes the data model you're migrating from is empty -- `--to-schema-datamodel`: the current database state using the URL in the `datasource` block -- `--script`: output a SQL script - -```terminal wrap -npx prisma migrate diff --from-empty --to-schema-datamodel prisma/schema.prisma --script > prisma/migrations/0_init/migration.sql -``` - -## Review the migration - -The command will generate a migration that should resemble the following script: - -```sql file=prisma/migrations/0_init/migration.sql --- CreateTable -CREATE TABLE "Post" ( - "id" SERIAL NOT NULL, - "title" VARCHAR(255) NOT NULL, - "createdAt" TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP, - "content" TEXT, - "published" BOOLEAN NOT NULL DEFAULT false, - "authorId" INTEGER NOT NULL, - - CONSTRAINT "Post_pkey" PRIMARY KEY ("id") -); - --- CreateTable -CREATE TABLE "Profile" ( - "id" SERIAL NOT NULL, - "bio" TEXT, - "userId" INTEGER NOT NULL, - - CONSTRAINT "Profile_pkey" PRIMARY KEY ("id") -); - --- CreateTable -CREATE TABLE "User" ( - "id" SERIAL NOT NULL, - "name" VARCHAR(255), - "email" VARCHAR(255) NOT NULL, - - CONSTRAINT "User_pkey" PRIMARY KEY ("id") -); - --- CreateIndex -CREATE UNIQUE INDEX "Profile_userId_key" ON "Profile"("userId"); - --- CreateIndex -CREATE UNIQUE INDEX "User_email_key" ON "User"("email"); - --- AddForeignKey -ALTER TABLE "Post" ADD CONSTRAINT "Post_authorId_fkey" FOREIGN KEY ("authorId") REFERENCES "User"("id") ON DELETE NO ACTION ON UPDATE NO ACTION; - --- AddForeignKey -ALTER TABLE "Profile" ADD CONSTRAINT "Profile_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE NO ACTION ON UPDATE NO ACTION; -``` - -Review the SQL migration file to ensure everything is correct. - -Next, mark the migration as applied using `prisma migrate resolve` with the `--applied` argument. - -```terminal -npx prisma migrate resolve --applied 0_init -``` - -The command will mark `0_init` as applied by adding it to the `_prisma_migrations` table. - -You now have a baseline for your current database schema. To make further changes to your database schema, you can update your Prisma schema and use `prisma migrate dev` to apply the changes to your database. diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/170-baseline-your-database-node-sqlserver.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/170-baseline-your-database-node-sqlserver.mdx deleted file mode 100644 index 436408fa9d..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/170-baseline-your-database-node-sqlserver.mdx +++ /dev/null @@ -1,93 +0,0 @@ ---- -title: 'Baseline with Prisma ORM, JavaScript, and SQL Server' -sidebar_label: 'Baseline your database' -metaTitle: 'Baseline with Prisma ORM, JavaScript, and SQL Server' -metaDescription: 'Baseline your database with Prisma ORM, JavaScript, and SQL Server' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'cockroachdb'] -hide_table_of_contents: true -sidebar_class_name: hidden-sidebar -pagination_prev: getting-started/setup-prisma/add-to-existing-project/relational-databases/introspection-node-sqlserver -pagination_next: getting-started/setup-prisma/add-to-existing-project/relational-databases/install-prisma-client-node-sqlserver -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/relational-databases/baseline-your-database- ---- - - -## Create an initial migration - -To use Prisma Migrate with the database you introspected in the last section, you will need to [baseline your database](/orm/prisma-migrate/getting-started). - -Baselining refers to initializing your migration history for a database that might already contain data and **cannot be reset**, such as your production database. Baselining tells Prisma Migrate to assume that one or more migrations have already been applied to your database. - -To baseline your database, use [`prisma migrate diff`](/orm/reference/prisma-cli-reference#migrate-diff) to compare your schema and database, and save the output into a SQL file. - -First, create a `migrations` directory and add a directory inside with your preferred name for the migration. In this example, we will use `0_init` as the migration name: - -```terminal -mkdir -p prisma/migrations/0_init -``` - - - -`-p` will recursively create any missing folders in the path you provide. - - - -Next, generate the migration file with `prisma migrate diff`. Use the following arguments: - -- `--from-empty`: assumes the data model you're migrating from is empty -- `--to-schema-datamodel`: the current database state using the URL in the `datasource` block -- `--script`: output a SQL script - -```terminal wrap -npx prisma migrate diff --from-empty --to-schema-datamodel prisma/schema.prisma --script > prisma/migrations/0_init/migration.sql -``` - -## Review the migration - -The command will generate a migration that should resemble the following script: - -```sql file=prisma/migrations/0_init/migration.sql -CREATE TABLE [dbo].[Post] ( - [id] INT NOT NULL IDENTITY(1,1), - [createdAt] DATETIME2 NOT NULL CONSTRAINT [Post_createdAt_df] DEFAULT CURRENT_TIMESTAMP, - [updatedAt] DATETIME2 NOT NULL, - [title] VARCHAR(255) NOT NULL, - [content] NVARCHAR(1000), - [published] BIT NOT NULL CONSTRAINT [Post_published_df] DEFAULT 0, - [authorId] INT NOT NULL, - CONSTRAINT [Post_pkey] PRIMARY KEY ([id]) -); - -CREATE TABLE [dbo].[Profile] ( - [id] INT NOT NULL IDENTITY(1,1), - [bio] NVARCHAR(1000), - [userId] INT NOT NULL, - CONSTRAINT [Profile_pkey] PRIMARY KEY ([id]), - CONSTRAINT [Profile_userId_key] UNIQUE ([userId]) -); - -CREATE TABLE [dbo].[User] ( - [id] INT NOT NULL IDENTITY(1,1), - [email] NVARCHAR(1000) NOT NULL, - [name] NVARCHAR(1000), - CONSTRAINT [User_pkey] PRIMARY KEY ([id]), - CONSTRAINT [User_email_key] UNIQUE ([email]) -); - -ALTER TABLE [dbo].[Post] ADD CONSTRAINT [Post_authorId_fkey] FOREIGN KEY ([authorId]) REFERENCES [dbo].[User]([id]) ON DELETE NO ACTION ON UPDATE CASCADE; - -ALTER TABLE [dbo].[Profile] ADD CONSTRAINT [Profile_userId_fkey] FOREIGN KEY ([userId]) REFERENCES [dbo].[User]([id]) ON DELETE NO ACTION ON UPDATE CASCADE; -``` - -Review the SQL migration file to ensure everything is correct. - -Next, mark the migration as applied using `prisma migrate resolve` with the `--applied` argument. - -```terminal -npx prisma migrate resolve --applied 0_init -``` - -The command will mark `0_init` as applied by adding it to the `_prisma_migrations` table. - -You now have a baseline for your current database schema. To make further changes to your database schema, you can update your Prisma schema and use `prisma migrate dev` to apply the changes to your database. diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/170-baseline-your-database-typescript-cockroachdb.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/170-baseline-your-database-typescript-cockroachdb.mdx deleted file mode 100644 index 65e048db8b..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/170-baseline-your-database-typescript-cockroachdb.mdx +++ /dev/null @@ -1,74 +0,0 @@ ---- -title: 'Baseline with Prisma ORM, TypeScript, and CockroachDB' -sidebar_label: 'Baseline your database' -metaTitle: 'Baseline with Prisma ORM, TypeScript, and CockroachDB' -metaDescription: 'Baseline your database with Prisma ORM, TypeScript, and CockroachDB' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'cockroachdb'] -hide_table_of_contents: true -sidebar_class_name: hidden-sidebar -pagination_prev: getting-started/setup-prisma/add-to-existing-project/relational-databases/introspection-typescript-cockroachdb -pagination_next: getting-started/setup-prisma/add-to-existing-project/relational-databases/install-prisma-client-typescript-cockroachdb -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/relational-databases/baseline-your-database- ---- - - -## Create an initial migration - -To use Prisma Migrate with the database you introspected in the last section, you will need to [baseline your database](/orm/prisma-migrate/getting-started). - -Baselining refers to initializing your migration history for a database that might already contain data and **cannot be reset**, such as your production database. Baselining tells Prisma Migrate to assume that one or more migrations have already been applied to your database. - -To baseline your database, use [`prisma migrate diff`](/orm/reference/prisma-cli-reference#migrate-diff) to compare your schema and database, and save the output into a SQL file. - -First, create a `migrations` directory and add a directory inside with your preferred name for the migration. In this example, we will use `0_init` as the migration name: - -```terminal -mkdir -p prisma/migrations/0_init -``` - - - -`-p` will recursively create any missing folders in the path you provide. - - - -Next, generate the migration file with `prisma migrate diff`. Use the following arguments: - -- `--from-empty`: assumes the data model you're migrating from is empty -- `--to-schema-datamodel`: the current database state using the URL in the `datasource` block -- `--script`: output a SQL script - -```terminal wrap -npx prisma migrate diff --from-empty --to-schema-datamodel prisma/schema.prisma --script > prisma/migrations/0_init/migration.sql -``` - -## Review the migration - -The command will generate a migration that should resemble the following script: - - -```sql file=prisma/migrations/0_init/migration.sql -CREATE TABLE "User" ( - id INT8 PRIMARY KEY DEFAULT unique_rowid(), - name STRING(255), - email STRING(255) UNIQUE NOT NULL -); - -CREATE TABLE "Post" ( - id INT8 PRIMARY KEY DEFAULT unique_rowid(), - title STRING(255) UNIQUE NOT NULL, - "createdAt" TIMESTAMP NOT NULL DEFAULT now(), - content STRING, - published BOOLEAN NOT NULL DEFAULT false, - "authorId" INT8 NOT NULL, - FOREIGN KEY ("authorId") REFERENCES "User"(id) -); - -CREATE TABLE "Profile" ( - id INT8 PRIMARY KEY DEFAULT unique_rowid(), - bio STRING, - "userId" INT8 UNIQUE NOT NULL, - FOREIGN KEY ("userId") REFERENCES "User"(id) -); -``` diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/170-baseline-your-database-typescript-mysql.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/170-baseline-your-database-typescript-mysql.mdx deleted file mode 100644 index f2c4008c40..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/170-baseline-your-database-typescript-mysql.mdx +++ /dev/null @@ -1,102 +0,0 @@ ---- -title: 'Baseline with Prisma ORM, TypeScript, and MySQL' -sidebar_label: 'Baseline your database' -metaTitle: 'Baseline with Prisma ORM, TypeScript, and MySQL' -metaDescription: 'Baseline your database with Prisma ORM, TypeScript, and MySQL' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'cockroachdb'] -hide_table_of_contents: true -sidebar_class_name: hidden-sidebar -pagination_prev: getting-started/setup-prisma/add-to-existing-project/relational-databases/introspection-typescript-mysql -pagination_next: getting-started/setup-prisma/add-to-existing-project/relational-databases/install-prisma-client-typescript-mysql -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/relational-databases/baseline-your-database- ---- - - -## Create an initial migration - -To use Prisma Migrate with the database you introspected in the last section, you will need to [baseline your database](/orm/prisma-migrate/getting-started). - -Baselining refers to initializing your migration history for a database that might already contain data and **cannot be reset**, such as your production database. Baselining tells Prisma Migrate to assume that one or more migrations have already been applied to your database. - -To baseline your database, use [`prisma migrate diff`](/orm/reference/prisma-cli-reference#migrate-diff) to compare your schema and database, and save the output into a SQL file. - -First, create a `migrations` directory and add a directory inside with your preferred name for the migration. In this example, we will use `0_init` as the migration name: - -```terminal -mkdir -p prisma/migrations/0_init -``` - - - -`-p` will recursively create any missing folders in the path you provide. - - - -Next, generate the migration file with `prisma migrate diff`. Use the following arguments: - -- `--from-empty`: assumes the data model you're migrating from is empty -- `--to-schema-datamodel`: the current database state using the URL in the `datasource` block -- `--script`: output a SQL script - -```terminal wrap -npx prisma migrate diff --from-empty --to-schema-datamodel prisma/schema.prisma --script > prisma/migrations/0_init/migration.sql -``` - -## Review the migration - -The command will generate a migration that should resemble the following script: - -```sql file=prisma/migrations/0_init/migration.sql --- CreateTable -CREATE TABLE `Post` ( - `id` INTEGER NOT NULL AUTO_INCREMENT, - `title` VARCHAR(255) NOT NULL, - `createdAt` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0), - `content` TEXT NULL, - `published` BOOLEAN NOT NULL DEFAULT false, - `authorId` INTEGER NOT NULL, - - INDEX `authorId`(`authorId`), - PRIMARY KEY (`id`) -) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; - --- CreateTable -CREATE TABLE `Profile` ( - `id` INTEGER NOT NULL AUTO_INCREMENT, - `bio` TEXT NULL, - `userId` INTEGER NOT NULL, - - UNIQUE INDEX `userId`(`userId`), - PRIMARY KEY (`id`) -) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; - --- CreateTable -CREATE TABLE `User` ( - `id` INTEGER NOT NULL AUTO_INCREMENT, - `name` VARCHAR(255) NULL, - `email` VARCHAR(255) NOT NULL, - - UNIQUE INDEX `email`(`email`), - PRIMARY KEY (`id`) -) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; - --- AddForeignKey -ALTER TABLE `Post` ADD CONSTRAINT `Post_ibfk_1` FOREIGN KEY (`authorId`) REFERENCES `User`(`id`) ON DELETE RESTRICT ON UPDATE RESTRICT; - --- AddForeignKey -ALTER TABLE `Profile` ADD CONSTRAINT `Profile_ibfk_1` FOREIGN KEY (`userId`) REFERENCES `User`(`id`) ON DELETE RESTRICT ON UPDATE RESTRICT; -``` - - -Review the SQL migration file to ensure everything is correct. - -Next, mark the migration as applied using `prisma migrate resolve` with the `--applied` argument. - -```terminal -npx prisma migrate resolve --applied 0_init -``` - -The command will mark `0_init` as applied by adding it to the `_prisma_migrations` table. - -You now have a baseline for your current database schema. To make further changes to your database schema, you can update your Prisma schema and use `prisma migrate dev` to apply the changes to your database. diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/170-baseline-your-database-typescript-postgresql.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/170-baseline-your-database-typescript-postgresql.mdx deleted file mode 100644 index 7041fe9521..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/170-baseline-your-database-typescript-postgresql.mdx +++ /dev/null @@ -1,103 +0,0 @@ ---- -title: 'Baseline with Prisma ORM, TypeScript, and PostgreSQL' -sidebar_label: 'Baseline your database' -metaTitle: 'Baseline with Prisma ORM, TypeScript, and PostgreSQL' -metaDescription: 'Baseline your database with Prisma ORM, TypeScript, and PostgreSQL' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'cockroachdb'] -hide_table_of_contents: true -pagination_prev: getting-started/setup-prisma/add-to-existing-project/relational-databases/introspection-typescript-postgresql -pagination_next: getting-started/setup-prisma/add-to-existing-project/relational-databases/install-prisma-client-typescript-postgresql -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/relational-databases/baseline-your-database- ---- - - -## Create an initial migration - -To use Prisma Migrate with the database you introspected in the last section, you will need to [baseline your database](/orm/prisma-migrate/getting-started). - -Baselining refers to initializing your migration history for a database that might already contain data and **cannot be reset**, such as your production database. Baselining tells Prisma Migrate to assume that one or more migrations have already been applied to your database. - -To baseline your database, use [`prisma migrate diff`](/orm/reference/prisma-cli-reference#migrate-diff) to compare your schema and database, and save the output into a SQL file. - -First, create a `migrations` directory and add a directory inside with your preferred name for the migration. In this example, we will use `0_init` as the migration name: - -```terminal -mkdir -p prisma/migrations/0_init -``` - - - -`-p` will recursively create any missing folders in the path you provide. - - - -Next, generate the migration file with `prisma migrate diff`. Use the following arguments: - -- `--from-empty`: assumes the data model you're migrating from is empty -- `--to-schema-datamodel`: the current database state using the URL in the `datasource` block -- `--script`: output a SQL script - -```terminal wrap -npx prisma migrate diff --from-empty --to-schema-datamodel prisma/schema.prisma --script > prisma/migrations/0_init/migration.sql -``` - -## Review the migration - -The command will generate a migration that should resemble the following script: - -```sql file=prisma/migrations/0_init/migration.sql --- CreateTable -CREATE TABLE "Post" ( - "id" SERIAL NOT NULL, - "title" VARCHAR(255) NOT NULL, - "createdAt" TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP, - "content" TEXT, - "published" BOOLEAN NOT NULL DEFAULT false, - "authorId" INTEGER NOT NULL, - - CONSTRAINT "Post_pkey" PRIMARY KEY ("id") -); - --- CreateTable -CREATE TABLE "Profile" ( - "id" SERIAL NOT NULL, - "bio" TEXT, - "userId" INTEGER NOT NULL, - - CONSTRAINT "Profile_pkey" PRIMARY KEY ("id") -); - --- CreateTable -CREATE TABLE "User" ( - "id" SERIAL NOT NULL, - "name" VARCHAR(255), - "email" VARCHAR(255) NOT NULL, - - CONSTRAINT "User_pkey" PRIMARY KEY ("id") -); - --- CreateIndex -CREATE UNIQUE INDEX "Profile_userId_key" ON "Profile"("userId"); - --- CreateIndex -CREATE UNIQUE INDEX "User_email_key" ON "User"("email"); - --- AddForeignKey -ALTER TABLE "Post" ADD CONSTRAINT "Post_authorId_fkey" FOREIGN KEY ("authorId") REFERENCES "User"("id") ON DELETE NO ACTION ON UPDATE NO ACTION; - --- AddForeignKey -ALTER TABLE "Profile" ADD CONSTRAINT "Profile_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE NO ACTION ON UPDATE NO ACTION; -``` - -Review the SQL migration file to ensure everything is correct. - -Next, mark the migration as applied using `prisma migrate resolve` with the `--applied` argument. - -```terminal -npx prisma migrate resolve --applied 0_init -``` - -The command will mark `0_init` as applied by adding it to the `_prisma_migrations` table. - -You now have a baseline for your current database schema. To make further changes to your database schema, you can update your Prisma schema and use `prisma migrate dev` to apply the changes to your database. diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/170-baseline-your-database-typescript-sqlserver.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/170-baseline-your-database-typescript-sqlserver.mdx deleted file mode 100644 index 61bbb0321a..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/170-baseline-your-database-typescript-sqlserver.mdx +++ /dev/null @@ -1,93 +0,0 @@ ---- -title: 'Baseline with Prisma ORM, TypeScript, and SQL Server' -sidebar_label: 'Baseline your database' -metaTitle: 'Baseline with Prisma ORM, TypeScript, and SQL Server' -metaDescription: 'Baseline your database with Prisma ORM, TypeScript, and SQL Server' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'cockroachdb'] -hide_table_of_contents: true -sidebar_class_name: hidden-sidebar -pagination_prev: getting-started/setup-prisma/add-to-existing-project/relational-databases/introspection-typescript-sqlserver -pagination_next: getting-started/setup-prisma/add-to-existing-project/relational-databases/install-prisma-client-typescript-sqlserver -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/relational-databases/baseline-your-database- ---- - - -## Create an initial migration - -To use Prisma Migrate with the database you introspected in the last section, you will need to [baseline your database](/orm/prisma-migrate/getting-started). - -Baselining refers to initializing your migration history for a database that might already contain data and **cannot be reset**, such as your production database. Baselining tells Prisma Migrate to assume that one or more migrations have already been applied to your database. - -To baseline your database, use [`prisma migrate diff`](/orm/reference/prisma-cli-reference#migrate-diff) to compare your schema and database, and save the output into a SQL file. - -First, create a `migrations` directory and add a directory inside with your preferred name for the migration. In this example, we will use `0_init` as the migration name: - -```terminal -mkdir -p prisma/migrations/0_init -``` - - - -`-p` will recursively create any missing folders in the path you provide. - - - -Next, generate the migration file with `prisma migrate diff`. Use the following arguments: - -- `--from-empty`: assumes the data model you're migrating from is empty -- `--to-schema-datamodel`: the current database state using the URL in the `datasource` block -- `--script`: output a SQL script - -```terminal wrap -npx prisma migrate diff --from-empty --to-schema-datamodel prisma/schema.prisma --script > prisma/migrations/0_init/migration.sql -``` - -## Review the migration - -The command will generate a migration that should resemble the following script: - -```sql file=prisma/migrations/0_init/migration.sql -CREATE TABLE [dbo].[Post] ( - [id] INT NOT NULL IDENTITY(1,1), - [createdAt] DATETIME2 NOT NULL CONSTRAINT [Post_createdAt_df] DEFAULT CURRENT_TIMESTAMP, - [updatedAt] DATETIME2 NOT NULL, - [title] VARCHAR(255) NOT NULL, - [content] NVARCHAR(1000), - [published] BIT NOT NULL CONSTRAINT [Post_published_df] DEFAULT 0, - [authorId] INT NOT NULL, - CONSTRAINT [Post_pkey] PRIMARY KEY ([id]) -); - -CREATE TABLE [dbo].[Profile] ( - [id] INT NOT NULL IDENTITY(1,1), - [bio] NVARCHAR(1000), - [userId] INT NOT NULL, - CONSTRAINT [Profile_pkey] PRIMARY KEY ([id]), - CONSTRAINT [Profile_userId_key] UNIQUE ([userId]) -); - -CREATE TABLE [dbo].[User] ( - [id] INT NOT NULL IDENTITY(1,1), - [email] NVARCHAR(1000) NOT NULL, - [name] NVARCHAR(1000), - CONSTRAINT [User_pkey] PRIMARY KEY ([id]), - CONSTRAINT [User_email_key] UNIQUE ([email]) -); - -ALTER TABLE [dbo].[Post] ADD CONSTRAINT [Post_authorId_fkey] FOREIGN KEY ([authorId]) REFERENCES [dbo].[User]([id]) ON DELETE NO ACTION ON UPDATE CASCADE; - -ALTER TABLE [dbo].[Profile] ADD CONSTRAINT [Profile_userId_fkey] FOREIGN KEY ([userId]) REFERENCES [dbo].[User]([id]) ON DELETE NO ACTION ON UPDATE CASCADE; -``` - -Review the SQL migration file to ensure everything is correct. - -Next, mark the migration as applied using `prisma migrate resolve` with the `--applied` argument. - -```terminal -npx prisma migrate resolve --applied 0_init -``` - -The command will mark `0_init` as applied by adding it to the `_prisma_migrations` table. - -You now have a baseline for your current database schema. To make further changes to your database schema, you can update your Prisma schema and use `prisma migrate dev` to apply the changes to your database. diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/200-install-prisma-client-node-cockroachdb.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/200-install-prisma-client-node-cockroachdb.mdx deleted file mode 100644 index 306e4ebfbb..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/200-install-prisma-client-node-cockroachdb.mdx +++ /dev/null @@ -1,17 +0,0 @@ ---- -title: 'Install Prisma Client in an existing JavaScript project (CockroachDB)' -sidebar_label: 'Install Prisma Client' -metaTitle: 'Install Prisma Client in your existing project using JavaScript and CockroachDB' -metaDescription: 'Install and generate Prisma Client in your existing JavaScript and CockroachDB project' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -hide_table_of_contents: true -sidebar_class_name: hidden-sidebar -pagination_prev: getting-started/setup-prisma/add-to-existing-project/relational-databases/baseline-your-database-node-cockroachdb -pagination_next: getting-started/setup-prisma/add-to-existing-project/relational-databases/querying-the-database-node-cockroachdb -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/relational-databases/install-prisma-client- ---- - -import InstallPrismaClient from './_install-prisma-client-partial.mdx' - - diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/200-install-prisma-client-node-mysql.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/200-install-prisma-client-node-mysql.mdx deleted file mode 100644 index 6e1d802cd7..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/200-install-prisma-client-node-mysql.mdx +++ /dev/null @@ -1,17 +0,0 @@ ---- -title: 'Install Prisma Client in an existing JavaScript project (MySQL)' -sidebar_label: 'Install Prisma Client' -metaTitle: 'Install Prisma Client in your existing project using JavaScript and MySQL' -metaDescription: 'Install and generate Prisma Client in your existing JavaScript and MySQL project' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -hide_table_of_contents: true -sidebar_class_name: hidden-sidebar -pagination_prev: getting-started/setup-prisma/add-to-existing-project/relational-databases/baseline-your-database-node-mysql -pagination_next: getting-started/setup-prisma/add-to-existing-project/relational-databases/querying-the-database-node-mysql -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/relational-databases/install-prisma-client- ---- - -import InstallPrismaClient from './_install-prisma-client-partial.mdx' - - diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/200-install-prisma-client-node-planetscale.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/200-install-prisma-client-node-planetscale.mdx deleted file mode 100644 index 5e25861d0a..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/200-install-prisma-client-node-planetscale.mdx +++ /dev/null @@ -1,17 +0,0 @@ ---- -title: 'Install Prisma Client in an existing JavaScript project (PlanetScale)' -sidebar_label: 'Install Prisma Client' -metaTitle: 'Install Prisma Client in your existing project using JavaScript and PlanetScale' -metaDescription: 'Install and generate Prisma Client in your existing JavaScript and PlanetScale project' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -hide_table_of_contents: true -sidebar_class_name: hidden-sidebar -pagination_prev: getting-started/setup-prisma/add-to-existing-project/relational-databases/introspection-node-planetscale -pagination_next: getting-started/setup-prisma/add-to-existing-project/relational-databases/querying-the-database-node-planetscale -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/relational-databases/install-prisma-client- ---- - -import InstallPrismaClient from './_install-prisma-client-partial.mdx' - - \ No newline at end of file diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/200-install-prisma-client-node-postgresql.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/200-install-prisma-client-node-postgresql.mdx deleted file mode 100644 index 79a60fe467..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/200-install-prisma-client-node-postgresql.mdx +++ /dev/null @@ -1,17 +0,0 @@ ---- -title: 'Install Prisma Client in an existing JavaScript project (PostgreSQL)' -sidebar_label: 'Install Prisma Client' -metaTitle: 'Install Prisma Client in your existing project using JavaScript and PostgreSQL' -metaDescription: 'Install and generate Prisma Client in your existing JavaScript and PostgreSQL project' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -hide_table_of_contents: true -sidebar_class_name: hidden-sidebar -pagination_prev: getting-started/setup-prisma/add-to-existing-project/relational-databases/baseline-your-database-node-postgresql -pagination_next: getting-started/setup-prisma/add-to-existing-project/relational-databases/querying-the-database-node-postgresql -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/relational-databases/install-prisma-client- ---- - -import InstallPrismaClient from './_install-prisma-client-partial.mdx' - - \ No newline at end of file diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/200-install-prisma-client-node-sqlserver.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/200-install-prisma-client-node-sqlserver.mdx deleted file mode 100644 index cef9feceb5..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/200-install-prisma-client-node-sqlserver.mdx +++ /dev/null @@ -1,17 +0,0 @@ ---- -title: 'Install Prisma Client in an existing JavaScript project (SQL Server)' -sidebar_label: 'Install Prisma Client' -metaTitle: 'Install Prisma Client in your existing project using JavaScript and SQL Server' -metaDescription: 'Install and generate Prisma Client in your existing JavaScript and SQL Server project' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -hide_table_of_contents: true -sidebar_class_name: hidden-sidebar -pagination_prev: getting-started/setup-prisma/add-to-existing-project/relational-databases/baseline-your-database-node-sqlserver -pagination_next: getting-started/setup-prisma/add-to-existing-project/relational-databases/querying-the-database-node-sqlserver -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/relational-databases/install-prisma-client- ---- - -import InstallPrismaClient from './_install-prisma-client-partial.mdx' - - \ No newline at end of file diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/200-install-prisma-client-typescript-cockroachdb.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/200-install-prisma-client-typescript-cockroachdb.mdx deleted file mode 100644 index c1f9a4105d..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/200-install-prisma-client-typescript-cockroachdb.mdx +++ /dev/null @@ -1,17 +0,0 @@ ---- -title: 'Install Prisma Client in an existing TypeScript project (CockroachDB)' -sidebar_label: 'Install Prisma Client' -metaTitle: 'Install Prisma Client in your existing project using TypeScript and CockroachDB' -metaDescription: 'Install and generate Prisma Client in your existing TypeScript and CockroachDB project' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -hide_table_of_contents: true -sidebar_class_name: hidden-sidebar -pagination_prev: getting-started/setup-prisma/add-to-existing-project/relational-databases/baseline-your-database-typescript-cockroachdb -pagination_next: getting-started/setup-prisma/add-to-existing-project/relational-databases/querying-the-database-typescript-cockroachdb -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/relational-databases/install-prisma-client- ---- - -import InstallPrismaClient from './_install-prisma-client-partial.mdx' - - diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/200-install-prisma-client-typescript-mysql.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/200-install-prisma-client-typescript-mysql.mdx deleted file mode 100644 index e970da5f15..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/200-install-prisma-client-typescript-mysql.mdx +++ /dev/null @@ -1,17 +0,0 @@ ---- -title: 'Install Prisma Client in an existing TypeScript project (MySQL)' -sidebar_label: 'Install Prisma Client' -metaTitle: 'Install Prisma Client in your existing project using TypeScript and MySQL' -metaDescription: 'Install and generate Prisma Client in your existing TypeScript and MySQL project' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -hide_table_of_contents: true -sidebar_class_name: hidden-sidebar -pagination_prev: getting-started/setup-prisma/add-to-existing-project/relational-databases/baseline-your-database-typescript-mysql -pagination_next: getting-started/setup-prisma/add-to-existing-project/relational-databases/querying-the-database-typescript-mysql -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/relational-databases/install-prisma-client- ---- - -import InstallPrismaClient from './_install-prisma-client-partial.mdx' - - \ No newline at end of file diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/200-install-prisma-client-typescript-planetscale.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/200-install-prisma-client-typescript-planetscale.mdx deleted file mode 100644 index 8830aaab55..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/200-install-prisma-client-typescript-planetscale.mdx +++ /dev/null @@ -1,17 +0,0 @@ ---- -title: 'Install Prisma Client in an existing TypeScript project (PlanetScale)' -sidebar_label: 'Install Prisma Client' -metaTitle: 'Install Prisma Client in your existing project using TypeScript and PlanetScale' -metaDescription: 'Install and generate Prisma Client in your existing TypeScript and PlanetScale project' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -hide_table_of_contents: true -sidebar_class_name: hidden-sidebar -pagination_prev: getting-started/setup-prisma/add-to-existing-project/relational-databases/introspection-typescript-planetscale -pagination_next: getting-started/setup-prisma/add-to-existing-project/relational-databases/querying-the-database-typescript-planetscale -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/relational-databases/install-prisma-client- ---- - -import InstallPrismaClient from './_install-prisma-client-partial.mdx' - - \ No newline at end of file diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/200-install-prisma-client-typescript-postgresql.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/200-install-prisma-client-typescript-postgresql.mdx deleted file mode 100644 index c56f64a9f2..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/200-install-prisma-client-typescript-postgresql.mdx +++ /dev/null @@ -1,16 +0,0 @@ ---- -title: 'Install Prisma Client in an existing TypeScript project (PostgreSQL)' -sidebar_label: 'Install Prisma Client' -metaTitle: 'Install Prisma Client in your existing project using TypeScript and PostgreSQL' -metaDescription: 'Install and generate Prisma Client in your existing TypeScript and PostgreSQL project' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -hide_table_of_contents: true -pagination_prev: getting-started/setup-prisma/add-to-existing-project/relational-databases/baseline-your-database-typescript-postgresql -pagination_next: getting-started/setup-prisma/add-to-existing-project/relational-databases/querying-the-database-typescript-postgresql -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/relational-databases/install-prisma-client- ---- - -import InstallPrismaClient from './_install-prisma-client-partial.mdx' - - diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/200-install-prisma-client-typescript-sqlserver.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/200-install-prisma-client-typescript-sqlserver.mdx deleted file mode 100644 index cb7201e06a..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/200-install-prisma-client-typescript-sqlserver.mdx +++ /dev/null @@ -1,17 +0,0 @@ ---- -title: 'Install Prisma Client in your existing TypeScript project (SQL Server)' -sidebar_label: 'Install Prisma Client' -metaTitle: 'Install Prisma Client in your existing project using TypeScript and SQL Server' -metaDescription: 'Install and generate Prisma Client in your existing TypeScript and SQL Server project' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -hide_table_of_contents: true -sidebar_class_name: hidden-sidebar -pagination_prev: getting-started/setup-prisma/add-to-existing-project/relational-databases/baseline-your-database-typescript-sqlserver -pagination_next: getting-started/setup-prisma/add-to-existing-project/relational-databases/querying-the-database-typescript-sqlserver -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/relational-databases/install-prisma-client- ---- - -import InstallPrismaClient from './_install-prisma-client-partial.mdx' - - diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/250-querying-the-database-node-cockroachdb.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/250-querying-the-database-node-cockroachdb.mdx deleted file mode 100644 index a015c01fad..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/250-querying-the-database-node-cockroachdb.mdx +++ /dev/null @@ -1,123 +0,0 @@ ---- -title: 'Query your existing CockroachDB database with JavaScript and Prisma ORM' -sidebar_label: 'Querying the database' -metaTitle: 'Query your existing CockroachDB database with JavaScript and Prisma ORM' -metaDescription: 'Write data to and query the CockroachDB database with your JavaScript and Prisma ORM project' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -hide_table_of_contents: true -sidebar_class_name: hidden-sidebar -pagination_prev: getting-started/setup-prisma/add-to-existing-project/relational-databases/install-prisma-client-node-cockroachdb -pagination_next: getting-started/setup-prisma/add-to-existing-project/relational-databases/evolve-your-schema-node-cockroachdb -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/relational-databases/querying-the-database- ---- - - -## Write your first query with Prisma Client - -Now that you have generated Prisma Client, you can start writing queries to read and write data in your database. - -If you're building a REST API, you can use Prisma Client in your route handlers to read and write data in the database based on incoming HTTP requests. If you're building a GraphQL API, you can use Prisma Client in your resolvers to read and write data in the database based on incoming queries and mutations. - -For the purpose of this guide however, you'll just create a plain Node.js script to learn how to send queries to your database using Prisma Client. Once you have an understanding of how the API works, you can start integrating it into your actual application code (e.g. REST route handlers or GraphQL resolvers). - -Create a new file named `index.js` and add the following code to it: - -```js file=index.js showLineNumbers -const { PrismaClient } = require('@prisma/client') - -const prisma = new PrismaClient() - -async function main() { - // ... you will write your Prisma Client queries here -} - -main() - .then(async () => { - await prisma.$disconnect() - }) - .catch(async (e) => { - console.error(e) - await prisma.$disconnect() - process.exit(1) - }) -``` - -```js file=index.js -async function main() { - const allUsers = await prisma.user.findMany() - console.log(allUsers) -} -``` - -Now run the code with this command: - -```terminal copy -node index.js -``` - -If you created a database using the schema from the database introspection step, the query should print an empty array because there are no `User` records in the database yet. - -```no-copy -[] -``` - -If you introspected an existing database with records, the query should return an array of JavaScript objects. - -## Write data into the database - -The `findMany` query you used in the previous section only _reads_ data from the database. In this section, you'll learn how to write a query to _write_ new records into the `Post` and `User` tables. - -Adjust the `main` function to send a `create` query to the database: - -```js file=index.js showLineNumbers -async function main() { - await prisma.user.create({ - data: { - name: 'Alice', - email: 'alice@prisma.io', - posts: { - create: { title: 'Hello World' }, - }, - profile: { - create: { bio: 'I like turtles' }, - }, - }, - }) - - const allUsers = await prisma.user.findMany({ - include: { - posts: true, - profile: true, - }, - }) - console.dir(allUsers, { depth: null }) -} -``` -This code creates a new `User` record together with new `Post` and `Profile` records using a [nested write](/orm/prisma-client/queries/relation-queries#nested-writes) query. The `User` record is connected to the two other ones via the `Post.author` ↔ `User.posts` and `Profile.user` ↔ `User.profile` [relation fields](/orm/prisma-schema/data-model/relations#relation-fields) respectively. - -Notice that you're passing the [`include`](/orm/prisma-client/queries/select-fields#return-nested-objects-by-selecting-relation-fields) option to `findMany` which tells Prisma Client to include the `posts` and `profile` relations on the returned `User` objects. - -Run the code with this command: - -```terminal copy -node index.js -``` - -Before moving on to the next section, you'll "publish" the `Post` record you just created using an `update` query. Adjust the `main` function as follows: - -```js file=index.js showLineNumbers -async function main() { - const post = await prisma.post.update({ - where: { title: 'Hello World' }, - data: { published: true }, - }) - console.log(post) -} -``` - -Now run the code using the same command as before: - -```terminal copy -node index.js -``` diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/250-querying-the-database-node-mysql.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/250-querying-the-database-node-mysql.mdx deleted file mode 100644 index 926e969795..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/250-querying-the-database-node-mysql.mdx +++ /dev/null @@ -1,125 +0,0 @@ ---- -title: 'Query your existing MySQL database with JavaScript and Prisma ORM' -sidebar_label: 'Querying the database' -metaTitle: 'Query your existing MySQL database with JavaScript and Prisma ORM' -metaDescription: 'Write data to and query the MySQL database with your JavaScript and Prisma ORM project' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -hide_table_of_contents: true -sidebar_class_name: hidden-sidebar -pagination_prev: getting-started/setup-prisma/add-to-existing-project/relational-databases/install-prisma-client-node-mysql -pagination_next: getting-started/setup-prisma/add-to-existing-project/relational-databases/evolve-your-schema-node-mysql -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/relational-databases/querying-the-database- ---- - - -## Write your first query with Prisma Client - -Now that you have generated Prisma Client, you can start writing queries to read and write data in your database. - -If you're building a REST API, you can use Prisma Client in your route handlers to read and write data in the database based on incoming HTTP requests. If you're building a GraphQL API, you can use Prisma Client in your resolvers to read and write data in the database based on incoming queries and mutations. - -For the purpose of this guide however, you'll just create a plain Node.js script to learn how to send queries to your database using Prisma Client. Once you have an understanding of how the API works, you can start integrating it into your actual application code (e.g. REST route handlers or GraphQL resolvers). - - -Create a new file named `index.js` and add the following code to it: - -```js file=index.js showLineNumbers -const { PrismaClient } = require('@prisma/client') - -const prisma = new PrismaClient() - -async function main() { - // ... you will write your Prisma Client queries here -} - -main() - .then(async () => { - await prisma.$disconnect() - }) - .catch(async (e) => { - console.error(e) - await prisma.$disconnect() - process.exit(1) - }) -``` - -```js file=index.js -async function main() { - const allUsers = await prisma.user.findMany() - console.log(allUsers) -} -``` - -Now run the code with this command: - -```terminal copy -node index.js -``` - -If you created a database using the schema from the database introspection step, the query should print an empty array because there are no `User` records in the database yet. - -```no-copy -[] -``` - -If you introspected an existing database with records, the query should return an array of JavaScript objects. - -## Write data into the database - -The `findMany` query you used in the previous section only _reads_ data from the database. In this section, you'll learn how to write a query to _write_ new records into the `Post` and `User` tables. - -Adjust the `main` function to send a `create` query to the database: - -```js file=index.js showLineNumbers -async function main() { - await prisma.user.create({ - data: { - name: 'Alice', - email: 'alice@prisma.io', - posts: { - create: { title: 'Hello World' }, - }, - profile: { - create: { bio: 'I like turtles' }, - }, - }, - }) - - const allUsers = await prisma.user.findMany({ - include: { - posts: true, - profile: true, - }, - }) - console.dir(allUsers, { depth: null }) -} -``` - -This code creates a new `User` record together with new `Post` and `Profile` records using a [nested write](/orm/prisma-client/queries/relation-queries#nested-writes) query. The `User` record is connected to the two other ones via the `Post.author` ↔ `User.posts` and `Profile.user` ↔ `User.profile` [relation fields](/orm/prisma-schema/data-model/relations#relation-fields) respectively. - -Notice that you're passing the [`include`](/orm/prisma-client/queries/select-fields#return-nested-objects-by-selecting-relation-fields) option to `findMany` which tells Prisma Client to include the `posts` and `profile` relations on the returned `User` objects. - -Run the code with this command: - -```terminal copy -node index.js -``` - -Before moving on to the next section, you'll "publish" the `Post` record you just created using an `update` query. Adjust the `main` function as follows: - -```js file=index.js showLineNumbers -async function main() { - const post = await prisma.post.update({ - where: { id: 1 }, - data: { published: true }, - }) - console.log(post) -} -``` - -Now run the code using the same command as before: - -```terminal copy -node index.js -``` diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/250-querying-the-database-node-planetscale.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/250-querying-the-database-node-planetscale.mdx deleted file mode 100644 index 055441a96d..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/250-querying-the-database-node-planetscale.mdx +++ /dev/null @@ -1,137 +0,0 @@ ---- -title: 'Query your existing PlanetScale database with JavaScript and Prisma ORM' -sidebar_label: 'Querying the database' -metaTitle: 'Query your existing PlanetScale database with JavaScript and Prisma ORM' -metaDescription: 'Write data to and query the PlanetScale database with your JavaScript and Prisma ORM project' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -hide_table_of_contents: true -sidebar_class_name: hidden-sidebar -pagination_prev: getting-started/setup-prisma/add-to-existing-project/relational-databases/install-prisma-client-node-postgresql -pagination_next: getting-started/setup-prisma/add-to-existing-project/relational-databases/evolve-your-schema-node-postgresql -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/relational-databases/querying-the-database- ---- - -## Write your first query with Prisma Client - -Now that you have generated Prisma Client, you can start writing queries to read and write data in your database. - -If you're building a REST API, you can use Prisma Client in your route handlers to read and write data in the database based on incoming HTTP requests. If you're building a GraphQL API, you can use Prisma Client in your resolvers to read and write data in the database based on incoming queries and mutations. - -For the purpose of this guide however, you'll just create a plain Node.js script to learn how to send queries to your database using Prisma Client. Once you have an understanding of how the API works, you can start integrating it into your actual application code (e.g. REST route handlers or GraphQL resolvers). - -Create a new file named `index.js` and add the following code to it: - -```js file=index.js showLineNumbers -const { PrismaClient } = require('@prisma/client') - -const prisma = new PrismaClient() - -async function main() { - // ... you will write your Prisma Client queries here -} - -main() - .then(async () => { - await prisma.$disconnect() - }) - .catch(async (e) => { - console.error(e) - await prisma.$disconnect() - process.exit(1) - }) -``` - -Here's a quick overview of the different parts of the code snippet: - -1. Import the `PrismaClient` constructor from the `@prisma/client` node module -1. Instantiate `PrismaClient` -1. Define an `async` function named `main` to send queries to the database -1. Call the `main` function -1. Close the database connections when the script terminates - -Depending on what your models look like, the Prisma Client API will look different as well. For example, if you have a `User` model, your `PrismaClient` instance exposes a property called `user` on which you can call [CRUD](/orm/prisma-client/queries/crud) methods like `findMany`, `create` or `update`. The property is named after the model, but the first letter is lowercased (so for the `Post` model it's called `post`, for `Profile` it's called `profile`). - -The following examples are all based on the models in the Prisma schema. - -Inside the `main` function, add the following query to read all `User` records from the database and print the result: - -```js file=index.js showLineNumbers -async function main() { - const allUsers = await prisma.user.findMany() - console.log(allUsers) -} -``` - -Now run the code with this command: - -```terminal copy -node index.js -``` - -If you created a database using the schema from the database introspection step, the query should print an empty array because there are no `User` records in the database yet. - -```no-copy -[] -``` - -If you introspected an existing database with records, the query should return an array of JavaScript objects. - -## Write data into the database - -The `findMany` query you used in the previous section only _reads_ data from the database. In this section, you'll learn how to write a query to _write_ new records into the `Post` and `User` tables. - -Adjust the `main` function to send a `create` query to the database: - -```js file=index.js showLineNumbers -async function main() { - await prisma.user.create({ - data: { - name: 'Alice', - email: 'alice@prisma.io', - posts: { - create: { title: 'Hello World' }, - }, - profile: { - create: { bio: 'I like turtles' }, - }, - }, - }) - - const allUsers = await prisma.user.findMany({ - include: { - posts: true, - profile: true, - }, - }) - console.dir(allUsers, { depth: null }) -} -``` - -This code creates a new `User` record together with new `Post` and `Profile` records using a [nested write](/orm/prisma-client/queries/relation-queries#nested-writes) query. The `User` record is connected to the two other ones via the `Post.author` ↔ `User.posts` and `Profile.user` ↔ `User.profile` [relation fields](/orm/prisma-schema/data-model/relations#relation-fields) respectively. - -Notice that you're passing the [`include`](/orm/prisma-client/queries/select-fields#return-nested-objects-by-selecting-relation-fields) option to `findMany` which tells Prisma Client to include the `posts` and `profile` relations on the returned `User` objects. - -Run the code with this command: - -```terminal copy -node index.js -``` - -Before moving on to the next section, you'll "publish" the `Post` record you just created using an `update` query. Adjust the `main` function as follows: - -```js file=index.js -async function main() { - const post = await prisma.post.update({ - where: { id: 1 }, - data: { published: true }, - }) - console.log(post) -} -``` - -Now run the code using the same command as before: - -```terminal copy -node index.js -``` diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/250-querying-the-database-node-postgresql.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/250-querying-the-database-node-postgresql.mdx deleted file mode 100644 index 552155f8ad..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/250-querying-the-database-node-postgresql.mdx +++ /dev/null @@ -1,124 +0,0 @@ ---- -title: 'Query your existing PostgreSQL database with JavaScript and Prisma ORM' -sidebar_label: 'Querying the database' -metaTitle: 'Query your existing PostgreSQL database with JavaScript and Prisma ORM' -metaDescription: 'Write data to and query the PostgreSQL database with your JavaScript and Prisma ORM project' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -hide_table_of_contents: true -sidebar_class_name: hidden-sidebar -pagination_prev: getting-started/setup-prisma/add-to-existing-project/relational-databases/install-prisma-client-node-postgresql -pagination_next: getting-started/setup-prisma/add-to-existing-project/relational-databases/evolve-your-schema-node-postgresql -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/relational-databases/querying-the-database- ---- - - -## Write your first query with Prisma Client - -Now that you have generated Prisma Client, you can start writing queries to read and write data in your database. - -If you're building a REST API, you can use Prisma Client in your route handlers to read and write data in the database based on incoming HTTP requests. If you're building a GraphQL API, you can use Prisma Client in your resolvers to read and write data in the database based on incoming queries and mutations. - -For the purpose of this guide however, you'll just create a plain Node.js script to learn how to send queries to your database using Prisma Client. Once you have an understanding of how the API works, you can start integrating it into your actual application code (e.g. REST route handlers or GraphQL resolvers). - -Create a new file named `index.js` and add the following code to it: - -```js file=index.js showLineNumbers -const { PrismaClient } = require('@prisma/client') - -const prisma = new PrismaClient() - -async function main() { - // ... you will write your Prisma Client queries here -} - -main() - .then(async () => { - await prisma.$disconnect() - }) - .catch(async (e) => { - console.error(e) - await prisma.$disconnect() - process.exit(1) - }) -``` - -```js file=index.js showLineNumbers -async function main() { - const allUsers = await prisma.user.findMany() - console.log(allUsers) -} -``` - -Now run the code with this command: - -```terminal copy -node index.js -``` - -If you created a database using the schema from the database introspection step, the query should print an empty array because there are no `User` records in the database yet. - -```no-copy -[] -``` - -If you introspected an existing database with records, the query should return an array of JavaScript objects. - -## Write data into the database - -The `findMany` query you used in the previous section only _reads_ data from the database. In this section, you'll learn how to write a query to _write_ new records into the `Post` and `User` tables. - -Adjust the `main` function to send a `create` query to the database: - -```js file=index.js showLineNumbers -async function main() { - await prisma.user.create({ - data: { - name: 'Alice', - email: 'alice@prisma.io', - posts: { - create: { title: 'Hello World' }, - }, - profile: { - create: { bio: 'I like turtles' }, - }, - }, - }) - - const allUsers = await prisma.user.findMany({ - include: { - posts: true, - profile: true, - }, - }) - console.dir(allUsers, { depth: null }) -} -``` - -This code creates a new `User` record together with new `Post` and `Profile` records using a [nested write](/orm/prisma-client/queries/relation-queries#nested-writes) query. The `User` record is connected to the two other ones via the `Post.author` ↔ `User.posts` and `Profile.user` ↔ `User.profile` [relation fields](/orm/prisma-schema/data-model/relations#relation-fields) respectively. - -Notice that you're passing the [`include`](/orm/prisma-client/queries/select-fields#return-nested-objects-by-selecting-relation-fields) option to `findMany` which tells Prisma Client to include the `posts` and `profile` relations on the returned `User` objects. - -Run the code with this command: - -```terminal copy -node index.js -``` - -Before moving on to the next section, you'll "publish" the `Post` record you just created using an `update` query. Adjust the `main` function as follows: - -```js file=index.js -async function main() { - const post = await prisma.post.update({ - where: { id: 1 }, - data: { published: true }, - }) - console.log(post) -} -``` - -Now run the code using the same command as before: - -```terminal copy -node index.js -``` diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/250-querying-the-database-node-sqlserver.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/250-querying-the-database-node-sqlserver.mdx deleted file mode 100644 index ad979dd368..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/250-querying-the-database-node-sqlserver.mdx +++ /dev/null @@ -1,132 +0,0 @@ ---- -title: 'Query your existing SQL Server database with JavaScript and Prisma ORM' -sidebar_label: 'Querying the database' -metaTitle: 'Query your existing SQL Server database with JavaScript and Prisma ORM' -metaDescription: 'Write data to and query the SQL Server database with your JavaScript and Prisma ORM project' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -hide_table_of_contents: true -sidebar_class_name: hidden-sidebar -pagination_prev: getting-started/setup-prisma/add-to-existing-project/relational-databases/install-prisma-client-node-sqlserver -pagination_next: getting-started/setup-prisma/add-to-existing-project/relational-databases/evolve-your-schema-node-sqlserver -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/relational-databases/querying-the-database- ---- - - -## Write your first query with Prisma Client - -Now that you have generated Prisma Client, you can start writing queries to read and write data in your database. - -If you're building a REST API, you can use Prisma Client in your route handlers to read and write data in the database based on incoming HTTP requests. If you're building a GraphQL API, you can use Prisma Client in your resolvers to read and write data in the database based on incoming queries and mutations. - -For the purpose of this guide however, you'll just create a plain Node.js script to learn how to send queries to your database using Prisma Client. Once you have an understanding of how the API works, you can start integrating it into your actual application code (e.g. REST route handlers or GraphQL resolvers). - -Create a new file named `index.js` and add the following code to it: - -```js file=index.js showLineNumbers -const { PrismaClient } = require('@prisma/client') - -const prisma = new PrismaClient() - -async function main() { - // ... you will write your Prisma Client queries here -} - -main() - .then(async () => { - await prisma.$disconnect() - }) - .catch(async (e) => { - console.error(e) - await prisma.$disconnect() - process.exit(1) - }) -``` - -Here's a quick overview of the different parts of the code snippet: - -1. Import the `PrismaClient` constructor from the `@prisma/client` node module -1. Instantiate `PrismaClient` -1. Define an `async` function named `main` to send queries to the database -1. Call the `main` function -1. Close the database connections when the script terminates - -Depending on what your models look like, the Prisma Client API will look different as well. For example, if you have a `User` model, your `PrismaClient` instance exposes a property called `user` on which you can call [CRUD](/orm/prisma-client/queries/crud) methods like `findMany`, `create` or `update`. The property is named after the model, but the first letter is lowercased (so for the `Post` model it's called `post`, for `Profile` it's called `profile`). - -The following examples are all based on the models in the Prisma schema. - -Inside the `main` function, add the following query to read all `User` records from the database and print the result: - -```js file=index.js showLineNumbers -async function main() { - const allUsers = await prisma.user.findMany() - console.log(allUsers) -} -``` - -Now run the code with this command: - -```terminal copy -node index.js -``` - -If you created a database using the schema from the database introspection step, the query should print an empty array because there are no `User` records in the database yet. - -```no-copy -[] -``` - -If you introspected an existing database with records, the query should return an array of JavaScript objects. - -## Write data into the database - -The `findMany` query you used in the previous section only _reads_ data from the database. In this section, you'll learn how to write a query to _write_ new records into the `Post` and `User` tables. - -Adjust the `main` function to send a `create` query to the database: - -```js file=index.js showLineNumbers -async function main() { - await prisma.user.create({ - data: { - name: 'Alice', - email: 'alice@prisma.io', - posts: { - create: { title: 'Hello World' }, - }, - profile: { - create: { bio: 'I like turtles' }, - }, - }, - }) - - const allUsers = await prisma.user.findMany({ - include: { - posts: true, - profile: true, - }, - }) - console.dir(allUsers, { depth: null }) -} -``` - -This code creates a new `User` record together with new `Post` and `Profile` records using a [nested write](/orm/prisma-client/queries/relation-queries#nested-writes) query. The `User` record is connected to the two other ones via the `Post.author` ↔ `User.posts` and `Profile.user` ↔ `User.profile` [relation fields](/orm/prisma-schema/data-model/relations#relation-fields) respectively. - -Notice that you're passing the [`include`](/orm/prisma-client/queries/select-fields#return-nested-objects-by-selecting-relation-fields) option to `findMany` which tells Prisma Client to include the `posts` and `profile` relations on the returned `User` objects. - -Run the code with this command: - -```terminal copy -node index.js -``` - -Before moving on to the next section, you'll "publish" the `Post` record you just created using an `update` query. Adjust the `main` function as follows: - -```js file=index.js -async function main() { - const post = await prisma.post.update({ - where: { id: 1 }, - data: { published: true }, - }) - console.log(post) -} -``` diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/250-querying-the-database-typescript-cockroachdb.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/250-querying-the-database-typescript-cockroachdb.mdx deleted file mode 100644 index 2bec040594..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/250-querying-the-database-typescript-cockroachdb.mdx +++ /dev/null @@ -1,139 +0,0 @@ ---- -title: 'Query your existing CockroachDB database with TypeScript and Prisma ORM' -sidebar_label: 'Querying the database' -metaTitle: 'Query your existing CockroachDB database with TypeScript and Prisma ORM' -metaDescription: 'Write data to and query the CockroachDB database with your TypeScript and Prisma ORM project' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -hide_table_of_contents: true -sidebar_class_name: hidden-sidebar -pagination_prev: getting-started/setup-prisma/add-to-existing-project/relational-databases/install-prisma-client-typescript-cockroachdb -pagination_next: getting-started/setup-prisma/add-to-existing-project/relational-databases/evolve-your-schema-typescript-cockroachdb -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/relational-databases/querying-the-database- ---- - - -## Write your first query with Prisma Client - -Now that you have generated Prisma Client, you can start writing queries to read and write data in your database. - -If you're building a REST API, you can use Prisma Client in your route handlers to read and write data in the database based on incoming HTTP requests. If you're building a GraphQL API, you can use Prisma Client in your resolvers to read and write data in the database based on incoming queries and mutations. - -For the purpose of this guide however, you'll just create a plain Node.js script to learn how to send queries to your database using Prisma Client. Once you have an understanding of how the API works, you can start integrating it into your actual application code (e.g. REST route handlers or GraphQL resolvers). - -Create a new file named `index.ts` and add the following code to it: - -```ts file=index.ts showLineNumbers -import { PrismaClient } from './generated/prisma' - -const prisma = new PrismaClient() - -async function main() { - // ... you will write your Prisma Client queries here -} - -main() - .then(async () => { - await prisma.$disconnect() - }) - .catch(async (e) => { - console.error(e) - await prisma.$disconnect() - process.exit(1) - }) -``` - -Here's a quick overview of the different parts of the code snippet: - -1. Import the `PrismaClient` constructor from the `@prisma/client` node module -1. Instantiate `PrismaClient` -1. Define an `async` function named `main` to send queries to the database -1. Call the `main` function -1. Close the database connections when the script terminates - -Depending on what your models look like, the Prisma Client API will look different as well. For example, if you have a `User` model, your `PrismaClient` instance exposes a property called `user` on which you can call [CRUD](/orm/prisma-client/queries/crud) methods like `findMany`, `create` or `update`. The property is named after the model, but the first letter is lowercased (so for the `Post` model it's called `post`, for `Profile` it's called `profile`). - -The following examples are all based on the models in the Prisma schema. - -Inside the `main` function, add the following query to read all `User` records from the database and print the result: - -```ts file=index.ts showLineNumbers -async function main() { - const allUsers = await prisma.user.findMany() - console.log(allUsers) -} -``` - -Now run the code with your current TypeScript setup. If you're using `tsx`, you can run it like this: - -```terminal copy -npx tsx index.ts -``` - -If you created a database using the schema from the database introspection step, the query should print an empty array because there are no `User` records in the database yet. - -```no-copy -[] -``` - -If you introspected an existing database with records, the query should return an array of JavaScript objects. - -## Write data into the database - -The `findMany` query you used in the previous section only _reads_ data from the database. In this section, you'll learn how to write a query to _write_ new records into the `Post` and `User` tables. - -Adjust the `main` function to send a `create` query to the database: - -```ts file=index.ts showLineNumbers -async function main() { - await prisma.user.create({ - data: { - name: 'Alice', - email: 'alice@prisma.io', - posts: { - create: { title: 'Hello World' }, - }, - profile: { - create: { bio: 'I like turtles' }, - }, - }, - }) - - const allUsers = await prisma.user.findMany({ - include: { - posts: true, - profile: true, - }, - }) - console.dir(allUsers, { depth: null }) -} -``` - -This code creates a new `User` record together with new `Post` and `Profile` records using a [nested write](/orm/prisma-client/queries/relation-queries#nested-writes) query. The `User` record is connected to the two other ones via the `Post.author` ↔ `User.posts` and `Profile.user` ↔ `User.profile` [relation fields](/orm/prisma-schema/data-model/relations#relation-fields) respectively. - -Notice that you're passing the [`include`](/orm/prisma-client/queries/select-fields#return-nested-objects-by-selecting-relation-fields) option to `findMany` which tells Prisma Client to include the `posts` and `profile` relations on the returned `User` objects. - -Run the code with your current TypeScript setup. If you're using `tsx`, you can run it like this: - -```terminal copy -npx tsx index.ts -``` - -Before moving on to the next section, you'll "publish" the `Post` record you just created using an `update` query. Adjust the `main` function as follows: - -```ts file=index.ts showLineNumbers -async function main() { - const post = await prisma.post.update({ - where: { title: 'Hello World' }, - data: { published: true }, - }) - console.log(post) -} -``` - -Run the code with your current TypeScript setup. If you're using `tsx`, you can run it like this: - -```terminal copy -npx tsx index.ts -``` - diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/250-querying-the-database-typescript-mysql.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/250-querying-the-database-typescript-mysql.mdx deleted file mode 100644 index 7379468b73..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/250-querying-the-database-typescript-mysql.mdx +++ /dev/null @@ -1,138 +0,0 @@ ---- -title: 'Query your existing MySQL database with TypeScript and Prisma ORM' -sidebar_label: 'Querying the database' -metaTitle: 'Query your existing MySQL database with TypeScript and Prisma ORM' -metaDescription: 'Write data to and query the MySQL database with your TypeScript and Prisma ORM project' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -hide_table_of_contents: true -sidebar_class_name: hidden-sidebar -pagination_prev: getting-started/setup-prisma/add-to-existing-project/relational-databases/install-prisma-client-typescript-mysql -pagination_next: getting-started/setup-prisma/add-to-existing-project/relational-databases/evolve-your-schema-typescript-mysql -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/relational-databases/querying-the-database- ---- - - -## Write your first query with Prisma Client - -Now that you have generated Prisma Client, you can start writing queries to read and write data in your database. - -If you're building a REST API, you can use Prisma Client in your route handlers to read and write data in the database based on incoming HTTP requests. If you're building a GraphQL API, you can use Prisma Client in your resolvers to read and write data in the database based on incoming queries and mutations. - -For the purpose of this guide however, you'll just create a plain Node.js script to learn how to send queries to your database using Prisma Client. Once you have an understanding of how the API works, you can start integrating it into your actual application code (e.g. REST route handlers or GraphQL resolvers). - -Create a new file named `index.ts` and add the following code to it: - -```ts file=index.ts showLineNumbers -import { PrismaClient } from './generated/prisma' - -const prisma = new PrismaClient() - -async function main() { - // ... you will write your Prisma Client queries here -} - -main() - .then(async () => { - await prisma.$disconnect() - }) - .catch(async (e) => { - console.error(e) - await prisma.$disconnect() - process.exit(1) - }) -``` - -Here's a quick overview of the different parts of the code snippet: - -1. Import the `PrismaClient` constructor from the `@prisma/client` node module -1. Instantiate `PrismaClient` -1. Define an `async` function named `main` to send queries to the database -1. Call the `main` function -1. Close the database connections when the script terminates - -Depending on what your models look like, the Prisma Client API will look different as well. For example, if you have a `User` model, your `PrismaClient` instance exposes a property called `user` on which you can call [CRUD](/orm/prisma-client/queries/crud) methods like `findMany`, `create` or `update`. The property is named after the model, but the first letter is lowercased (so for the `Post` model it's called `post`, for `Profile` it's called `profile`). - -The following examples are all based on the models in the Prisma schema. - -Inside the `main` function, add the following query to read all `User` records from the database and print the result: - -```ts file=index.ts showLineNumbers -async function main() { - const allUsers = await prisma.user.findMany() - console.log(allUsers) -} -``` - -Now run the code with your current TypeScript setup. If you're using `tsx`, you can run it like this: - -```terminal copy -npx tsx index.ts -``` - -If you created a database using the schema from the database introspection step, the query should print an empty array because there are no `User` records in the database yet. - -```no-copy -[] -``` - -If you introspected an existing database with records, the query should return an array of JavaScript objects. - -## Write data into the database - -The `findMany` query you used in the previous section only _reads_ data from the database. In this section, you'll learn how to write a query to _write_ new records into the `Post` and `User` tables. - -Adjust the `main` function to send a `create` query to the database: - -```ts file=index.ts showLineNumbers -async function main() { - await prisma.user.create({ - data: { - name: 'Alice', - email: 'alice@prisma.io', - posts: { - create: { title: 'Hello World' }, - }, - profile: { - create: { bio: 'I like turtles' }, - }, - }, - }) - - const allUsers = await prisma.user.findMany({ - include: { - posts: true, - profile: true, - }, - }) - console.dir(allUsers, { depth: null }) -} -``` - -This code creates a new `User` record together with new `Post` and `Profile` records using a [nested write](/orm/prisma-client/queries/relation-queries#nested-writes) query. The `User` record is connected to the two other ones via the `Post.author` ↔ `User.posts` and `Profile.user` ↔ `User.profile` [relation fields](/orm/prisma-schema/data-model/relations#relation-fields) respectively. - -Notice that you're passing the [`include`](/orm/prisma-client/queries/select-fields#return-nested-objects-by-selecting-relation-fields) option to `findMany` which tells Prisma Client to include the `posts` and `profile` relations on the returned `User` objects. - -Run the code with your current TypeScript setup. If you're using `tsx`, you can run it like this: - -```terminal copy -npx tsx index.ts -``` - -Before moving on to the next section, you'll "publish" the `Post` record you just created using an `update` query. Adjust the `main` function as follows: - -```ts file=index.ts showLineNumbers -async function main() { - const post = await prisma.post.update({ - where: { id: 1 }, - data: { published: true }, - }) - console.log(post) -} -``` - -Run the code with your current TypeScript setup. If you're using `tsx`, you can run it like this: - -```terminal copy -npx tsx index.ts -``` diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/250-querying-the-database-typescript-planetscale.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/250-querying-the-database-typescript-planetscale.mdx deleted file mode 100644 index 5339ab4605..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/250-querying-the-database-typescript-planetscale.mdx +++ /dev/null @@ -1,139 +0,0 @@ ---- -title: 'Query your existing PlanetScale database with TypeScript and Prisma ORM' -sidebar_label: 'Querying the database' -metaTitle: 'Query your existing PlanetScale database with TypeScript and Prisma ORM' -metaDescription: 'Write data to and query the PlanetScale database with your TypeScript and Prisma ORM project' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -hide_table_of_contents: true -sidebar_class_name: hidden-sidebar -pagination_prev: getting-started/setup-prisma/add-to-existing-project/relational-databases/install-prisma-client-typescript-planetscale -pagination_next: getting-started/setup-prisma/add-to-existing-project/relational-databases/next-steps -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/relational-databases/querying-the-database- ---- - - -## Write your first query with Prisma Client - -Now that you have generated Prisma Client, you can start writing queries to read and write data in your database. - -If you're building a REST API, you can use Prisma Client in your route handlers to read and write data in the database based on incoming HTTP requests. If you're building a GraphQL API, you can use Prisma Client in your resolvers to read and write data in the database based on incoming queries and mutations. - -For the purpose of this guide however, you'll just create a plain Node.js script to learn how to send queries to your database using Prisma Client. Once you have an understanding of how the API works, you can start integrating it into your actual application code (e.g. REST route handlers or GraphQL resolvers). - -Create a new file named `index.ts` and add the following code to it: - -```ts file=index.ts showLineNumbers -import { PrismaClient } from './generated/prisma' - -const prisma = new PrismaClient() - -async function main() { - // ... you will write your Prisma Client queries here -} - -main() - .then(async () => { - await prisma.$disconnect() - }) - .catch(async (e) => { - console.error(e) - await prisma.$disconnect() - process.exit(1) - }) -``` - -Here's a quick overview of the different parts of the code snippet: - -1. Import the `PrismaClient` constructor from the `@prisma/client` node module -1. Instantiate `PrismaClient` -1. Define an `async` function named `main` to send queries to the database -1. Call the `main` function -1. Close the database connections when the script terminates - -Depending on what your models look like, the Prisma Client API will look different as well. For example, if you have a `User` model, your `PrismaClient` instance exposes a property called `user` on which you can call [CRUD](/orm/prisma-client/queries/crud) methods like `findMany`, `create` or `update`. The property is named after the model, but the first letter is lowercased (so for the `Post` model it's called `post`, for `Profile` it's called `profile`). - -The following examples are all based on the models in the Prisma schema. - -Inside the `main` function, add the following query to read all `User` records from the database and print the result: - -```ts file=index.ts showLineNumbers -async function main() { - const allUsers = await prisma.user.findMany() - console.log(allUsers) -} -``` - -Now run the code with your current TypeScript setup. If you're using `tsx`, you can run it like this: - -```terminal copy -npx tsx index.ts -``` - - -If you created a database using the schema from the database introspection step, the query should print an empty array because there are no `User` records in the database yet. - -```no-copy -[] -``` - -If you introspected an existing database with records, the query should return an array of JavaScript objects. - -## Write data into the database - -The `findMany` query you used in the previous section only _reads_ data from the database. In this section, you'll learn how to write a query to _write_ new records into the `Post` and `User` tables. - -Adjust the `main` function to send a `create` query to the database: - -```ts file=index.ts showLineNumbers -async function main() { - await prisma.user.create({ - data: { - name: 'Alice', - email: 'alice@prisma.io', - posts: { - create: { title: 'Hello World' }, - }, - profile: { - create: { bio: 'I like turtles' }, - }, - }, - }) - - const allUsers = await prisma.user.findMany({ - include: { - posts: true, - profile: true, - }, - }) - console.dir(allUsers, { depth: null }) -} -``` - -This code creates a new `User` record together with new `Post` and `Profile` records using a [nested write](/orm/prisma-client/queries/relation-queries#nested-writes) query. The `User` record is connected to the two other ones via the `Post.author` ↔ `User.posts` and `Profile.user` ↔ `User.profile` [relation fields](/orm/prisma-schema/data-model/relations#relation-fields) respectively. - -Notice that you're passing the [`include`](/orm/prisma-client/queries/select-fields#return-nested-objects-by-selecting-relation-fields) option to `findMany` which tells Prisma Client to include the `posts` and `profile` relations on the returned `User` objects. - -Run the code with your current TypeScript setup. If you're using `tsx`, you can run it like this: - -```terminal copy -npx tsx index.ts -``` - -Before moving on to the next section, you'll "publish" the `Post` record you just created using an `update` query. Adjust the `main` function as follows: - -```ts file=index.ts showLineNumbers -async function main() { - const post = await prisma.post.update({ - where: { id: 1 }, - data: { published: true }, - }) - console.log(post) -} -``` - -Run the code with your current TypeScript setup. If you're using `tsx`, you can run it like this: - -```terminal copy -npx tsx index.ts -``` diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/250-querying-the-database-typescript-postgresql.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/250-querying-the-database-typescript-postgresql.mdx deleted file mode 100644 index 7cd5bf286b..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/250-querying-the-database-typescript-postgresql.mdx +++ /dev/null @@ -1,137 +0,0 @@ ---- -title: 'Query your existing PostgreSQL database with TypeScript and Prisma ORM' -sidebar_label: 'Querying the database' -metaTitle: 'Query your existing PostgreSQL database with TypeScript and Prisma ORM' -metaDescription: 'Write data to and query the PostgreSQL database with your TypeScript and Prisma ORM project' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -hide_table_of_contents: true -pagination_prev: getting-started/setup-prisma/add-to-existing-project/relational-databases/install-prisma-client-typescript-postgresql -pagination_next: getting-started/setup-prisma/add-to-existing-project/relational-databases/evolve-your-schema-typescript-postgresql -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/relational-databases/querying-the-database- ---- - - -## Write your first query with Prisma Client - -Now that you have generated Prisma Client, you can start writing queries to read and write data in your database. - -If you're building a REST API, you can use Prisma Client in your route handlers to read and write data in the database based on incoming HTTP requests. If you're building a GraphQL API, you can use Prisma Client in your resolvers to read and write data in the database based on incoming queries and mutations. - -For the purpose of this guide however, you'll just create a plain Node.js script to learn how to send queries to your database using Prisma Client. Once you have an understanding of how the API works, you can start integrating it into your actual application code (e.g. REST route handlers or GraphQL resolvers). - -Create a new file named `index.ts` and add the following code to it: - -```ts file=index.ts showLineNumbers -import { PrismaClient } from './generated/prisma' - -const prisma = new PrismaClient() - -async function main() { - // ... you will write your Prisma Client queries here -} - -main() - .then(async () => { - await prisma.$disconnect() - }) - .catch(async (e) => { - console.error(e) - await prisma.$disconnect() - process.exit(1) - }) -``` - -Here's a quick overview of the different parts of the code snippet: - -1. Import the `PrismaClient` constructor from the `@prisma/client` node module -1. Instantiate `PrismaClient` -1. Define an `async` function named `main` to send queries to the database -1. Call the `main` function -1. Close the database connections when the script terminates - -Depending on what your models look like, the Prisma Client API will look different as well. For example, if you have a `User` model, your `PrismaClient` instance exposes a property called `user` on which you can call [CRUD](/orm/prisma-client/queries/crud) methods like `findMany`, `create` or `update`. The property is named after the model, but the first letter is lowercased (so for the `Post` model it's called `post`, for `Profile` it's called `profile`). - -The following examples are all based on the models in the Prisma schema. - -Inside the `main` function, add the following query to read all `User` records from the database and print the result: - -```ts file=index.ts showLineNumbers -async function main() { - const allUsers = await prisma.user.findMany() - console.log(allUsers) -} -``` - -Now run the code with your current TypeScript setup. If you're using `tsx`, you can run it like this: - -```terminal copy -npx tsx index.ts -``` - -If you created a database using the schema from the database introspection step, the query should print an empty array because there are no `User` records in the database yet. - -```no-copy -[] -``` - -If you introspected an existing database with records, the query should return an array of JavaScript objects. - -## Write data into the database - -The `findMany` query you used in the previous section only _reads_ data from the database. In this section, you'll learn how to write a query to _write_ new records into the `Post` and `User` tables. - -Adjust the `main` function to send a `create` query to the database: - -```ts file=index.ts showLineNumbers -async function main() { - await prisma.user.create({ - data: { - name: 'Alice', - email: 'alice@prisma.io', - posts: { - create: { title: 'Hello World' }, - }, - profile: { - create: { bio: 'I like turtles' }, - }, - }, - }) - - const allUsers = await prisma.user.findMany({ - include: { - posts: true, - profile: true, - }, - }) - console.dir(allUsers, { depth: null }) -} -``` - -This code creates a new `User` record together with new `Post` and `Profile` records using a [nested write](/orm/prisma-client/queries/relation-queries#nested-writes) query. The `User` record is connected to the two other ones via the `Post.author` ↔ `User.posts` and `Profile.user` ↔ `User.profile` [relation fields](/orm/prisma-schema/data-model/relations#relation-fields) respectively. - -Notice that you're passing the [`include`](/orm/prisma-client/queries/select-fields#return-nested-objects-by-selecting-relation-fields) option to `findMany` which tells Prisma Client to include the `posts` and `profile` relations on the returned `User` objects. - -Run the code with your current TypeScript setup. If you're using `tsx`, you can run it like this: - -```terminal copy -npx tsx index.ts -``` - -Before moving on to the next section, you'll "publish" the `Post` record you just created using an `update` query. Adjust the `main` function as follows: - -```ts file=index.ts showLineNumbers -async function main() { - const post = await prisma.post.update({ - where: { id: 1 }, - data: { published: true }, - }) - console.log(post) -} -``` - -Run the code with your current TypeScript setup. If you're using `tsx`, you can run it like this: - -```terminal copy -npx tsx index.ts -``` diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/250-querying-the-database-typescript-sqlserver.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/250-querying-the-database-typescript-sqlserver.mdx deleted file mode 100644 index ef0b41aa99..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/250-querying-the-database-typescript-sqlserver.mdx +++ /dev/null @@ -1,138 +0,0 @@ ---- -title: 'Query your existing SQL Server database with TypeScript and Prisma ORM' -sidebar_label: 'Querying the database' -metaTitle: 'Query your existing SQL Server database with TypeScript and Prisma ORM' -metaDescription: 'Write data to and query the SQL Server database with your TypeScript and Prisma ORM project' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] -hide_table_of_contents: true -sidebar_class_name: hidden-sidebar -pagination_prev: getting-started/setup-prisma/add-to-existing-project/relational-databases/install-prisma-client-typescript-sqlserver -pagination_next: getting-started/setup-prisma/add-to-existing-project/relational-databases/evolve-your-schema-typescript-sqlserver -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/relational-databases/querying-the-database- ---- - - -## Write your first query with Prisma Client - -Now that you have generated Prisma Client, you can start writing queries to read and write data in your database. - -If you're building a REST API, you can use Prisma Client in your route handlers to read and write data in the database based on incoming HTTP requests. If you're building a GraphQL API, you can use Prisma Client in your resolvers to read and write data in the database based on incoming queries and mutations. - -For the purpose of this guide however, you'll just create a plain Node.js script to learn how to send queries to your database using Prisma Client. Once you have an understanding of how the API works, you can start integrating it into your actual application code (e.g. REST route handlers or GraphQL resolvers). - -Create a new file named `index.ts` and add the following code to it: - -```ts file=index.ts showLineNumbers -import { PrismaClient } from './generated/prisma' - -const prisma = new PrismaClient() - -async function main() { - // ... you will write your Prisma Client queries here -} - -main() - .then(async () => { - await prisma.$disconnect() - }) - .catch(async (e) => { - console.error(e) - await prisma.$disconnect() - process.exit(1) - }) -``` - -Here's a quick overview of the different parts of the code snippet: - -1. Import the `PrismaClient` constructor from the `@prisma/client` node module -1. Instantiate `PrismaClient` -1. Define an `async` function named `main` to send queries to the database -1. Call the `main` function -1. Close the database connections when the script terminates - -Depending on what your models look like, the Prisma Client API will look different as well. For example, if you have a `User` model, your `PrismaClient` instance exposes a property called `user` on which you can call [CRUD](/orm/prisma-client/queries/crud) methods like `findMany`, `create` or `update`. The property is named after the model, but the first letter is lowercased (so for the `Post` model it's called `post`, for `Profile` it's called `profile`). - -The following examples are all based on the models in the Prisma schema. - -Inside the `main` function, add the following query to read all `User` records from the database and print the result: - -```ts file=index.ts showLineNumbers -async function main() { - const allUsers = await prisma.user.findMany() - console.log(allUsers) -} -``` - -Now run the code with your current TypeScript setup. If you're using `tsx`, you can run it like this: - -```terminal copy -npx tsx index.ts -``` - -If you created a database using the schema from the database introspection step, the query should print an empty array because there are no `User` records in the database yet. - -```no-copy -[] -``` - -If you introspected an existing database with records, the query should return an array of JavaScript objects. - -## Write data into the database - -The `findMany` query you used in the previous section only _reads_ data from the database. In this section, you'll learn how to write a query to _write_ new records into the `Post` and `User` tables. - -Adjust the `main` function to send a `create` query to the database: - -```ts file=index.ts showLineNumbers -async function main() { - await prisma.user.create({ - data: { - name: 'Alice', - email: 'alice@prisma.io', - posts: { - create: { title: 'Hello World' }, - }, - profile: { - create: { bio: 'I like turtles' }, - }, - }, - }) - - const allUsers = await prisma.user.findMany({ - include: { - posts: true, - profile: true, - }, - }) - console.dir(allUsers, { depth: null }) -} -``` - -This code creates a new `User` record together with new `Post` and `Profile` records using a [nested write](/orm/prisma-client/queries/relation-queries#nested-writes) query. The `User` record is connected to the two other ones via the `Post.author` ↔ `User.posts` and `Profile.user` ↔ `User.profile` [relation fields](/orm/prisma-schema/data-model/relations#relation-fields) respectively. - -Notice that you're passing the [`include`](/orm/prisma-client/queries/select-fields#return-nested-objects-by-selecting-relation-fields) option to `findMany` which tells Prisma Client to include the `posts` and `profile` relations on the returned `User` objects. - -Run the code with your current TypeScript setup. If you're using `tsx`, you can run it like this: - -```terminal copy -npx tsx index.ts -``` - -Before moving on to the next section, you'll "publish" the `Post` record you just created using an `update` query. Adjust the `main` function as follows: - -```ts file=index.ts showLineNumbers -async function main() { - const post = await prisma.post.update({ - where: { id: 1 }, - data: { published: true }, - }) - console.log(post) -} -``` - -Run the code with your current TypeScript setup. If you're using `tsx`, you can run it like this: - -```terminal copy -npx tsx index.ts -``` diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/275-evolve-your-schema-node-cockroachdb.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/275-evolve-your-schema-node-cockroachdb.mdx deleted file mode 100644 index 88aaf399c1..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/275-evolve-your-schema-node-cockroachdb.mdx +++ /dev/null @@ -1,106 +0,0 @@ ---- -title: 'Evolve your schema for a CockroachDB database in a Javascript project' -sidebar_label: 'Evolve your schema' -metaTitle: 'Evolve your Prisma schema with Prisma Migrate : JavaScript-CockroachDB' -metaDescription: 'Evolve your Prisma schema with Prisma Migrate inside of your JavaScript and CockroachDB project' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'cockroachdb'] -hide_table_of_contents: true -sidebar_class_name: hidden-sidebar -pagination_prev: getting-started/setup-prisma/add-to-existing-project/relational-databases/querying-the-database-node-cockroachdb -pagination_next: getting-started/setup-prisma/add-to-existing-project/relational-databases/next-steps -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/relational-databases/evolve-your-schema- ---- - -## Add a `Tag` model to your schema - -In this section, you will evolve your Prisma schema and then generate and apply the migration to your database with [`prisma migrate dev`](/orm/reference/prisma-cli-reference#migrate-dev). - -For the purpose of this guide, we'll make the following changes to the Prisma schema: - -1. Create a new model called `Tag` with the following fields: - - `id`: an auto-incrementing integer that will be the primary key for the model - - `name`: a non-null `String` - - `posts`: an implicit many-to-many relation field that links to the `Post` model -2. Update the `Post` model with a `tags` field with an implicit many-to-many relation field that links to the `Tag` model - -Once you've made the changes to your schema, your schema should resemble the one below: - -```prisma file=prisma/schema.prisma highlight=9,27-31;edit showLineNumbers -model Post { - id Int @id @default(autoincrement()) - title String @db.VarChar(255) - createdAt DateTime @default(now()) @db.Timestamp(6) - content String? - published Boolean @default(false) - authorId Int - user User @relation(fields: [authorId], references: [id]) - //edit-next-line - tags Tag[] -} - -model Profile { - id Int @id @default(autoincrement()) - bio String? - userId Int @unique - user User @relation(fields: [userId], references: [id]) -} - -model User { - id Int @id @default(autoincrement()) - name String? @db.VarChar(255) - email String @unique @db.VarChar(255) - post Post[] - profile Profile? -} - -//edit-start -model Tag { - id Int @id @default(autoincrement()) - name String - posts Post[] -} -//edit-end -``` - -To apply your Prisma schema changes to your database, use the `prisma migrate dev` CLI command: - -```terminal copy -npx prisma migrate dev --name tags-model -``` - -This command will: - -1. Create a new SQL migration file for the migration -1. Apply the generated SQL migration to the database -1. Regenerate Prisma Client - -The following migration will be generated and saved in your `prisma/migrations` folder: - -```sql file=prisma/migrations/TIMESTAMP_tags_model.sql showLineNumbers - -- CreateTable -CREATE TABLE "Tag" ( - "id" SERIAL NOT NULL, - "name" VARCHAR(255) NOT NULL, - - CONSTRAINT "Tag_pkey" PRIMARY KEY ("id") -); - --- CreateTable -CREATE TABLE "_PostToTag" ( - "A" INTEGER NOT NULL, - "B" INTEGER NOT NULL -); - --- CreateIndex -CREATE UNIQUE INDEX "_PostToTag_AB_unique" ON "_PostToTag"("A", "B"); - --- CreateIndex -CREATE INDEX "_PostToTag_B_index" ON "_PostToTag"("B"); - --- AddForeignKey -ALTER TABLE "_PostToTag" ADD CONSTRAINT "_PostToTag_A_fkey" FOREIGN KEY ("A") REFERENCES "Post"("id") ON DELETE CASCADE ON UPDATE CASCADE; - --- AddForeignKey -ALTER TABLE "_PostToTag" ADD CONSTRAINT "_PostToTag_B_fkey" FOREIGN KEY ("B") REFERENCES "Tag"("id") ON DELETE CASCADE ON UPDATE CASCADE; -``` diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/275-evolve-your-schema-node-mysql.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/275-evolve-your-schema-node-mysql.mdx deleted file mode 100644 index 7b3ed655e2..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/275-evolve-your-schema-node-mysql.mdx +++ /dev/null @@ -1,108 +0,0 @@ ---- -title: 'Evolve your schema for a MySQL database in a Javascript project' -sidebar_label: 'Evolve your schema' -metaTitle: 'Evolve your Prisma schema with Prisma Migrate : JavaScript-MySQL' -metaDescription: 'Evolve your Prisma schema with Prisma Migrate inside of your JavaScript and MySQL project' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'cockroachdb'] -hide_table_of_contents: true -sidebar_class_name: hidden-sidebar -pagination_prev: getting-started/setup-prisma/add-to-existing-project/relational-databases/querying-the-database-node-mysql -pagination_next: getting-started/setup-prisma/add-to-existing-project/relational-databases/next-steps -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/relational-databases/evolve-your-schema- ---- - -## Add a `Tag` model to your schema - -In this section, you will evolve your Prisma schema and then generate and apply the migration to your database with [`prisma migrate dev`](/orm/reference/prisma-cli-reference#migrate-dev). - -For the purpose of this guide, we'll make the following changes to the Prisma schema: - -1. Create a new model called `Tag` with the following fields: - - `id`: an auto-incrementing integer that will be the primary key for the model - - `name`: a non-null `String` - - `posts`: an implicit many-to-many relation field that links to the `Post` model -2. Update the `Post` model with a `tags` field with an implicit many-to-many relation field that links to the `Tag` model - -Once you've made the changes to your schema, your schema should resemble the one below: - -```prisma file=prisma/schema.prisma highlight=9,27-31;edit showLineNumbers -model Post { - id Int @id @default(autoincrement()) - title String @db.VarChar(255) - createdAt DateTime @default(now()) @db.Timestamp(6) - content String? - published Boolean @default(false) - authorId Int - user User @relation(fields: [authorId], references: [id]) - //edit-next-line - tags Tag[] -} - -model Profile { - id Int @id @default(autoincrement()) - bio String? - userId Int @unique - user User @relation(fields: [userId], references: [id]) -} - -model User { - id Int @id @default(autoincrement()) - name String? @db.VarChar(255) - email String @unique @db.VarChar(255) - post Post[] - profile Profile? -} - -//edit-start -model Tag { - id Int @id @default(autoincrement()) - name String - posts Post[] -} -//edit-end -``` - -To apply your Prisma schema changes to your database, use the `prisma migrate dev` CLI command: - -```terminal copy -npx prisma migrate dev --name tags-model -``` - -This command will: - -1. Create a new SQL migration file for the migration -1. Apply the generated SQL migration to the database -1. Regenerate Prisma Client - -The following migration will be generated and saved in your `prisma/migrations` folder: - -```sql file=prisma/migrations/TIMESTAMP_tags_model.sql showLineNumbers --- CreateTable -CREATE TABLE Tag ( - id SERIAL NOT NULL, - name VARCHAR(255) NOT NULL, - - CONSTRAINT Tag_pkey PRIMARY KEY (id) -); - --- CreateTable -CREATE TABLE _PostToTag ( - A INTEGER NOT NULL, - B INTEGER NOT NULL -); - --- CreateIndex -CREATE UNIQUE INDEX _PostToTag_AB_unique ON _PostToTag(A, B); - --- CreateIndex -CREATE INDEX _PostToTag_B_index ON _PostToTag(B); - --- AddForeignKey -ALTER TABLE _PostToTag ADD CONSTRAINT _PostToTag_A_fkey FOREIGN KEY (A) REFERENCES Post(id) ON DELETE CASCADE ON UPDATE CASCADE; - --- AddForeignKey -ALTER TABLE _PostToTag ADD CONSTRAINT _PostToTag_B_fkey FOREIGN KEY (B) REFERENCES Tag(id) ON DELETE CASCADE ON UPDATE CASCADE; -``` - -Congratulations, you just evolved your database with Prisma Migrate 🚀 diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/275-evolve-your-schema-node-postgresql.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/275-evolve-your-schema-node-postgresql.mdx deleted file mode 100644 index c9ac290123..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/275-evolve-your-schema-node-postgresql.mdx +++ /dev/null @@ -1,107 +0,0 @@ ---- -title: 'Evolve your schema for a PostgreSQL database in a Javascript project' -sidebar_label: 'Evolve your schema' -metaTitle: 'Evolve your Prisma schema with Prisma Migrate : JavaScript-PostgreSQL' -metaDescription: 'Evolve your Prisma schema with Prisma Migrate inside of your JavaScript and PostgreSQL project' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'cockroachdb'] -hide_table_of_contents: true -sidebar_class_name: hidden-sidebar -pagination_prev: getting-started/setup-prisma/add-to-existing-project/relational-databases/querying-the-database-node-postgresql -pagination_next: getting-started/setup-prisma/add-to-existing-project/relational-databases/next-steps -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/relational-databases/evolve-your-schema- ---- - -## Add a `Tag` model to your schema - -In this section, you will evolve your Prisma schema and then generate and apply the migration to your database with [`prisma migrate dev`](/orm/reference/prisma-cli-reference#migrate-dev). - -For the purpose of this guide, we'll make the following changes to the Prisma schema: - -1. Create a new model called `Tag` with the following fields: - - `id`: an auto-incrementing integer that will be the primary key for the model - - `name`: a non-null `String` - - `posts`: an implicit many-to-many relation field that links to the `Post` model -2. Update the `Post` model with a `tags` field with an implicit many-to-many relation field that links to the `Tag` model - -Once you've made the changes to your schema, your schema should resemble the one below: - -```prisma file=prisma/schema.prisma highlight=9,27-31;edit showLineNumbers -model Post { - id Int @id @default(autoincrement()) - title String @db.VarChar(255) - createdAt DateTime @default(now()) @db.Timestamp(6) - content String? - published Boolean @default(false) - authorId Int - user User @relation(fields: [authorId], references: [id]) - //edit-next-line - tags Tag[] -} - -model Profile { - id Int @id @default(autoincrement()) - bio String? - userId Int @unique - user User @relation(fields: [userId], references: [id]) -} - -model User { - id Int @id @default(autoincrement()) - name String? @db.VarChar(255) - email String @unique @db.VarChar(255) - post Post[] - profile Profile? -} -//edit-start -model Tag { - id Int @id @default(autoincrement()) - name String - posts Post[] -} -//edit-end -``` - -To apply your Prisma schema changes to your database, use the `prisma migrate dev` CLI command: - -```terminal copy -npx prisma migrate dev --name tags-model -``` - -This command will: - -1. Create a new SQL migration file for the migration -1. Apply the generated SQL migration to the database -1. Regenerate Prisma Client - -The following migration will be generated and saved in your `prisma/migrations` folder: - -```sql file=prisma/migrations/TIMESTAMP_tags_model.sql showLineNumbers - -- CreateTable -CREATE TABLE "Tag" ( - "id" SERIAL NOT NULL, - "name" VARCHAR(255) NOT NULL, - - CONSTRAINT "Tag_pkey" PRIMARY KEY ("id") -); - --- CreateTable -CREATE TABLE "_PostToTag" ( - "A" INTEGER NOT NULL, - "B" INTEGER NOT NULL -); - --- CreateIndex -CREATE UNIQUE INDEX "_PostToTag_AB_unique" ON "_PostToTag"("A", "B"); - --- CreateIndex -CREATE INDEX "_PostToTag_B_index" ON "_PostToTag"("B"); - --- AddForeignKey -ALTER TABLE "_PostToTag" ADD CONSTRAINT "_PostToTag_A_fkey" FOREIGN KEY ("A") REFERENCES "Post"("id") ON DELETE CASCADE ON UPDATE CASCADE; - --- AddForeignKey -ALTER TABLE "_PostToTag" ADD CONSTRAINT "_PostToTag_B_fkey" FOREIGN KEY ("B") REFERENCES "Tag"("id") ON DELETE CASCADE ON UPDATE CASCADE; -``` - -Congratulations, you just evolved your database with Prisma Migrate 🚀 diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/275-evolve-your-schema-node-sqlserver.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/275-evolve-your-schema-node-sqlserver.mdx deleted file mode 100644 index 93c06b95e2..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/275-evolve-your-schema-node-sqlserver.mdx +++ /dev/null @@ -1,108 +0,0 @@ ---- -title: 'Evolve your schema for a SQL Server database in a Javascript project' -sidebar_label: 'Evolve your schema' -metaTitle: 'Evolve your Prisma schema with Prisma Migrate : JavaScript-sqlserver' -metaDescription: 'Evolve your Prisma schema with Prisma Migrate inside of your JavaScript and SQL Server project' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'cockroachdb'] -hide_table_of_contents: true -sidebar_class_name: hidden-sidebar -pagination_prev: getting-started/setup-prisma/add-to-existing-project/relational-databases/querying-the-database-node-sqlserver -pagination_next: getting-started/setup-prisma/add-to-existing-project/relational-databases/next-steps -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/relational-databases/evolve-your-schema- ---- - -## Add a `Tag` model to your schema - -In this section, you will evolve your Prisma schema and then generate and apply the migration to your database with [`prisma migrate dev`](/orm/reference/prisma-cli-reference#migrate-dev). - -For the purpose of this guide, we'll make the following changes to the Prisma schema: - -1. Create a new model called `Tag` with the following fields: - - `id`: an auto-incrementing integer that will be the primary key for the model - - `name`: a non-null `String` - - `posts`: an implicit many-to-many relation field that links to the `Post` model -2. Update the `Post` model with a `tags` field with an implicit many-to-many relation field that links to the `Tag` model - -Once you've made the changes to your schema, your schema should resemble the one below: - -```prisma file=prisma/schema.prisma highlight=9,27-31;edit showLineNumbers -model Post { - id Int @id @default(autoincrement()) - title String @db.VarChar(255) - createdAt DateTime @default(now()) @db.Timestamp(6) - content String? - published Boolean @default(false) - authorId Int - user User @relation(fields: [authorId], references: [id]) - //edit-next-line - tags Tag[] -} - -model Profile { - id Int @id @default(autoincrement()) - bio String? - userId Int @unique - user User @relation(fields: [userId], references: [id]) -} - -model User { - id Int @id @default(autoincrement()) - name String? @db.VarChar(255) - email String @unique @db.VarChar(255) - post Post[] - profile Profile? -} - -//edit-start -model Tag { - id Int @id @default(autoincrement()) - name String - posts Post[] -} -//edit-end -``` - -To apply your Prisma schema changes to your database, use the `prisma migrate dev` CLI command: - -```terminal copy -npx prisma migrate dev --name tags-model -``` - -This command will: - -1. Create a new SQL migration file for the migration -1. Apply the generated SQL migration to the database -1. Regenerate Prisma Client - -The following migration will be generated and saved in your `prisma/migrations` folder: - -```sql file=prisma/migrations/TIMESTAMP_tags_model.sql showLineNumbers - -- CreateTable -CREATE TABLE [dbo].[Tag] ( - [id] SERIAL NOT NULL, - [name] VARCHAR(255) NOT NULL, - - CONSTRAINT [Tag_pkey] PRIMARY KEY ([id]) -); - --- CreateTable -CREATE TABLE [dbo].[_PostToTag] ( - [A] INTEGER NOT NULL, - [B] INTEGER NOT NULL -); - --- CreateIndex -CREATE UNIQUE INDEX [_PostToTag_AB_unique] ON _PostToTag([A], [B]); - --- CreateIndex -CREATE INDEX [_PostToTag_B_index] ON [_PostToTag]([B]); - --- AddForeignKey -ALTER TABLE [dbo].[_PostToTag] ADD CONSTRAINT [_PostToTag_A_fkey] FOREIGN KEY ([A]) REFERENCES [dbo].[Post]([id]) ON DELETE CASCADE ON UPDATE CASCADE; - --- AddForeignKey -ALTER TABLE [dbo].[_PostToTag] ADD CONSTRAINT [_PostToTag_B_fkey] FOREIGN KEY ([B]) REFERENCES [dbo].[Tag]([id]) ON DELETE CASCADE ON UPDATE CASCADE; -``` - -Congratulations diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/275-evolve-your-schema-typescript-cockroachdb.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/275-evolve-your-schema-typescript-cockroachdb.mdx deleted file mode 100644 index 328f9a3c03..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/275-evolve-your-schema-typescript-cockroachdb.mdx +++ /dev/null @@ -1,109 +0,0 @@ ---- -title: 'Evolve your schema for a CockroachDB database in a Typescript project' -sidebar_label: 'Evolve your schema' -metaTitle: 'Evolve your Prisma schema with Prisma Migrate : TypeScript-cockroachdb' -metaDescription: 'Evolve your Prisma schema with Prisma Migrate inside of your TypeScript and CockroachDB project' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'cockroachdb'] -hide_table_of_contents: true -sidebar_class_name: hidden-sidebar -pagination_prev: getting-started/setup-prisma/add-to-existing-project/relational-databases/querying-the-database-typescript-cockroachdb -pagination_next: getting-started/setup-prisma/add-to-existing-project/relational-databases/next-steps -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/relational-databases/evolve-your-schema- ---- - -## Add a `Tag` model to your schema - -In this section, you will evolve your Prisma schema and then generate and apply the migration to your database with [`prisma migrate dev`](/orm/reference/prisma-cli-reference#migrate-dev). - -For the purpose of this guide, we'll make the following changes to the Prisma schema: - -1. Create a new model called `Tag` with the following fields: - - `id`: an auto-incrementing integer that will be the primary key for the model - - `name`: a non-null `String` - - `posts`: an implicit many-to-many relation field that links to the `Post` model -2. Update the `Post` model with a `tags` field with an implicit many-to-many relation field that links to the `Tag` model - -Once you've made the changes to your schema, your schema should resemble the one below: - -```prisma file=prisma/schema.prisma highlight=9,27-31;edit showLineNumbers -model Post { - id Int @id @default(autoincrement()) - title String @db.VarChar(255) - createdAt DateTime @default(now()) @db.Timestamp(6) - content String? - published Boolean @default(false) - authorId Int - user User @relation(fields: [authorId], references: [id]) - //edit-next-line - tags Tag[] -} - -model Profile { - id Int @id @default(autoincrement()) - bio String? - userId Int @unique - user User @relation(fields: [userId], references: [id]) -} - -model User { - id Int @id @default(autoincrement()) - name String? @db.VarChar(255) - email String @unique @db.VarChar(255) - post Post[] - profile Profile? -} - -//edit-start -model Tag { - id Int @id @default(autoincrement()) - name String - posts Post[] -} -//edit-end -``` - -To apply your Prisma schema changes to your database, use the `prisma migrate dev` CLI command: - -```terminal copy -npx prisma migrate dev --name tags-model -``` - -This command will: - -1. Create a new SQL migration file for the migration -1. Apply the generated SQL migration to the database -1. Regenerate Prisma Client - -The following migration will be generated and saved in your `prisma/migrations` folder: - -```sql file=prisma/migrations/TIMESTAMP_tags_model.sql showLineNumbers - -- CreateTable -CREATE TABLE "Tag" ( - "id" SERIAL NOT NULL, - "name" VARCHAR(255) NOT NULL, - - CONSTRAINT "Tag_pkey" PRIMARY KEY ("id") -); - --- CreateTable -CREATE TABLE "_PostToTag" ( - "A" INTEGER NOT NULL, - "B" INTEGER NOT NULL -); - --- CreateIndex -CREATE UNIQUE INDEX "_PostToTag_AB_unique" ON "_PostToTag"("A", "B"); - --- CreateIndex -CREATE INDEX "_PostToTag_B_index" ON "_PostToTag"("B"); - --- AddForeignKey -ALTER TABLE "_PostToTag" ADD CONSTRAINT "_PostToTag_A_fkey" FOREIGN KEY ("A") REFERENCES "Post"("id") ON DELETE CASCADE ON UPDATE CASCADE; - --- AddForeignKey -ALTER TABLE "_PostToTag" ADD CONSTRAINT "_PostToTag_B_fkey" FOREIGN KEY ("B") REFERENCES "Tag"("id") ON DELETE CASCADE ON UPDATE CASCADE; -``` - -Congratulations, you just evolved your database with Prisma Migrate 🚀 - diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/275-evolve-your-schema-typescript-mysql.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/275-evolve-your-schema-typescript-mysql.mdx deleted file mode 100644 index d810eddcb6..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/275-evolve-your-schema-typescript-mysql.mdx +++ /dev/null @@ -1,108 +0,0 @@ ---- -title: 'Evolve your schema for a MySQL database in a Typescript project' -sidebar_label: 'Evolve your schema' -metaTitle: 'Evolve your Prisma schema with Prisma Migrate : TypeScript-mysql' -metaDescription: 'Evolve your Prisma schema with Prisma Migrate inside of your TypeScript and MySQL project' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'cockroachdb'] -hide_table_of_contents: true -sidebar_class_name: hidden-sidebar -pagination_prev: getting-started/setup-prisma/add-to-existing-project/relational-databases/querying-the-database-typescript-mysql -pagination_next: getting-started/setup-prisma/add-to-existing-project/relational-databases/next-steps -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/relational-databases/evolve-your-schema- ---- - -## Add a `Tag` model to your schema - -In this section, you will evolve your Prisma schema and then generate and apply the migration to your database with [`prisma migrate dev`](/orm/reference/prisma-cli-reference#migrate-dev). - -For the purpose of this guide, we'll make the following changes to the Prisma schema: - -1. Create a new model called `Tag` with the following fields: - - `id`: an auto-incrementing integer that will be the primary key for the model - - `name`: a non-null `String` - - `posts`: an implicit many-to-many relation field that links to the `Post` model -2. Update the `Post` model with a `tags` field with an implicit many-to-many relation field that links to the `Tag` model - -Once you've made the changes to your schema, your schema should resemble the one below: - -```prisma file=prisma/schema.prisma highlight=9,27-31;edit showLineNumbers -model Post { - id Int @id @default(autoincrement()) - title String @db.VarChar(255) - createdAt DateTime @default(now()) @db.Timestamp(6) - content String? - published Boolean @default(false) - authorId Int - user User @relation(fields: [authorId], references: [id]) - //edit-next-line - tags Tag[] -} - -model Profile { - id Int @id @default(autoincrement()) - bio String? - userId Int @unique - user User @relation(fields: [userId], references: [id]) -} - -model User { - id Int @id @default(autoincrement()) - name String? @db.VarChar(255) - email String @unique @db.VarChar(255) - post Post[] - profile Profile? -} - -//edit-start -model Tag { - id Int @id @default(autoincrement()) - name String - posts Post[] -} -//edit-end -``` - -To apply your Prisma schema changes to your database, use the `prisma migrate dev` CLI command: - -```terminal copy -npx prisma migrate dev --name tags-model -``` - -This command will: - -1. Create a new SQL migration file for the migration -1. Apply the generated SQL migration to the database -1. Regenerate Prisma Client - -The following migration will be generated and saved in your `prisma/migrations` folder: - -```sql file=prisma/migrations/TIMESTAMP_tags_model.sql showLineNumbers --- CreateTable -CREATE TABLE Tag ( - id SERIAL NOT NULL, - name VARCHAR(255) NOT NULL, - - CONSTRAINT Tag_pkey PRIMARY KEY (id) -); - --- CreateTable -CREATE TABLE _PostToTag ( - A INTEGER NOT NULL, - B INTEGER NOT NULL -); - --- CreateIndex -CREATE UNIQUE INDEX _PostToTag_AB_unique ON _PostToTag(A, B); - --- CreateIndex -CREATE INDEX _PostToTag_B_index ON _PostToTag(B); - --- AddForeignKey -ALTER TABLE _PostToTag ADD CONSTRAINT _PostToTag_A_fkey FOREIGN KEY (A) REFERENCES Post(id) ON DELETE CASCADE ON UPDATE CASCADE; - --- AddForeignKey -ALTER TABLE _PostToTag ADD CONSTRAINT _PostToTag_B_fkey FOREIGN KEY (B) REFERENCES Tag(id) ON DELETE CASCADE ON UPDATE CASCADE; -``` - -Congratulations, you just evolved your database with Prisma Migrate 🚀 diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/275-evolve-your-schema-typescript-postgresql.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/275-evolve-your-schema-typescript-postgresql.mdx deleted file mode 100644 index 9159fff535..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/275-evolve-your-schema-typescript-postgresql.mdx +++ /dev/null @@ -1,109 +0,0 @@ ---- -title: 'Evolve your schema for a PostgreSQL database in a Typescript project' -sidebar_label: 'Evolve your schema' -metaTitle: 'Evolve your Prisma schema with Prisma Migrate : TypeScript-postgresql' -metaDescription: 'Evolve your Prisma schema with Prisma Migrate inside of your TypeScript and PostgreSQL project' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'cockroachdb'] -hide_table_of_contents: true -pagination_prev: getting-started/setup-prisma/add-to-existing-project/relational-databases/querying-the-database-typescript-postgresql -pagination_next: getting-started/setup-prisma/add-to-existing-project/relational-databases/next-steps -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/relational-databases/evolve-your-schema- ---- - -## Add a `Tag` model to your schema - -In this section, you will evolve your Prisma schema and then generate and apply the migration to your database with [`prisma migrate dev`](/orm/reference/prisma-cli-reference#migrate-dev). - -For the purpose of this guide, we'll make the following changes to the Prisma schema: - -1. Create a new model called `Tag` with the following fields: - - `id`: an auto-incrementing integer that will be the primary key for the model - - `name`: a non-null `String` - - `posts`: an implicit many-to-many relation field that links to the `Post` model -2. Update the `Post` model with a `tags` field with an implicit many-to-many relation field that links to the `Tag` model - -Once you've made the changes to your schema, your schema should resemble the one below: - -```prisma file=prisma/schema.prisma highlight=9,27-31;edit showLineNumbers -model Post { - id Int @id @default(autoincrement()) - title String @db.VarChar(255) - createdAt DateTime @default(now()) @db.Timestamp(6) - content String? - published Boolean @default(false) - authorId Int - user User @relation(fields: [authorId], references: [id]) - //edit-next-line - tags Tag[] -} - -model Profile { - id Int @id @default(autoincrement()) - bio String? - userId Int @unique - user User @relation(fields: [userId], references: [id]) -} - -model User { - id Int @id @default(autoincrement()) - name String? @db.VarChar(255) - email String @unique @db.VarChar(255) - post Post[] - profile Profile? -} - -//edit-start -model Tag { - id Int @id @default(autoincrement()) - name String - posts Post[] -} -//edit-end -``` - -To apply your Prisma schema changes to your database, use the `prisma migrate dev` CLI command: - -```terminal copy -npx prisma migrate dev --name tags-model -``` - -This command will: - -1. Create a new SQL migration file for the migration -1. Apply the generated SQL migration to the database -1. Regenerate Prisma Client - -The following migration will be generated and saved in your `prisma/migrations` folder: - -```sql file=prisma/migrations/TIMESTAMP_tags_model.sql showLineNumbers - -- CreateTable -CREATE TABLE "Tag" ( - "id" SERIAL NOT NULL, - "name" VARCHAR(255) NOT NULL, - - CONSTRAINT "Tag_pkey" PRIMARY KEY ("id") -); - --- CreateTable -CREATE TABLE "_PostToTag" ( - "A" INTEGER NOT NULL, - "B" INTEGER NOT NULL -); - --- CreateIndex -CREATE UNIQUE INDEX "_PostToTag_AB_unique" ON "_PostToTag"("A", "B"); - --- CreateIndex -CREATE INDEX "_PostToTag_B_index" ON "_PostToTag"("B"); - --- AddForeignKey -ALTER TABLE "_PostToTag" ADD CONSTRAINT "_PostToTag_A_fkey" FOREIGN KEY ("A") REFERENCES "Post"("id") ON DELETE CASCADE ON UPDATE CASCADE; - --- AddForeignKey -ALTER TABLE "_PostToTag" ADD CONSTRAINT "_PostToTag_B_fkey" FOREIGN KEY ("B") REFERENCES "Tag"("id") ON DELETE CASCADE ON UPDATE CASCADE; -``` - - - -Congratulations, you just evolved your database with Prisma Migrate 🚀 diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/275-evolve-your-schema-typescript-sqlserver.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/275-evolve-your-schema-typescript-sqlserver.mdx deleted file mode 100644 index 4b98a336f0..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/275-evolve-your-schema-typescript-sqlserver.mdx +++ /dev/null @@ -1,108 +0,0 @@ ---- -title: 'Evolve your schema for a SQL Server database in a Typescript project' -sidebar_label: 'Evolve your schema' -metaTitle: 'Evolve your Prisma schema with Prisma Migrate : TypeScript-sql-server' -metaDescription: 'Evolve your Prisma schema with Prisma Migrate inside of your TypeScript and SQL Server project' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'cockroachdb'] -hide_table_of_contents: true -sidebar_class_name: hidden-sidebar -pagination_prev: getting-started/setup-prisma/add-to-existing-project/relational-databases/querying-the-database-typescript-sqlserver -pagination_next: getting-started/setup-prisma/add-to-existing-project/relational-databases/next-steps -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/relational-databases/evolve-your-schema- ---- - -## Add a `Tag` model to your schema - -In this section, you will evolve your Prisma schema and then generate and apply the migration to your database with [`prisma migrate dev`](/orm/reference/prisma-cli-reference#migrate-dev). - -For the purpose of this guide, we'll make the following changes to the Prisma schema: - -1. Create a new model called `Tag` with the following fields: - - `id`: an auto-incrementing integer that will be the primary key for the model - - `name`: a non-null `String` - - `posts`: an implicit many-to-many relation field that links to the `Post` model -2. Update the `Post` model with a `tags` field with an implicit many-to-many relation field that links to the `Tag` model - -Once you've made the changes to your schema, your schema should resemble the one below: - -```prisma file=prisma/schema.prisma highlight=9,27-31;edit showLineNumbers -model Post { - id Int @id @default(autoincrement()) - title String @db.VarChar(255) - createdAt DateTime @default(now()) @db.Timestamp(6) - content String? - published Boolean @default(false) - authorId Int - user User @relation(fields: [authorId], references: [id]) - //edit-next-line - tags Tag[] -} - -model Profile { - id Int @id @default(autoincrement()) - bio String? - userId Int @unique - user User @relation(fields: [userId], references: [id]) -} - -model User { - id Int @id @default(autoincrement()) - name String? @db.VarChar(255) - email String @unique @db.VarChar(255) - post Post[] - profile Profile? -} - -//edit-start -model Tag { - id Int @id @default(autoincrement()) - name String - posts Post[] -} -//edit-end -``` - -To apply your Prisma schema changes to your database, use the `prisma migrate dev` CLI command: - -```terminal copy -npx prisma migrate dev --name tags-model -``` - -This command will: - -1. Create a new SQL migration file for the migration -1. Apply the generated SQL migration to the database -1. Regenerate Prisma Client - -The following migration will be generated and saved in your `prisma/migrations` folder: - -```sql file=prisma/migrations/TIMESTAMP_tags_model.sql showLineNumbers - -- CreateTable -CREATE TABLE [dbo].[Tag] ( - [id] SERIAL NOT NULL, - [name] VARCHAR(255) NOT NULL, - - CONSTRAINT [Tag_pkey] PRIMARY KEY ([id]) -); - --- CreateTable -CREATE TABLE [dbo].[_PostToTag] ( - [A] INTEGER NOT NULL, - [B] INTEGER NOT NULL -); - --- CreateIndex -CREATE UNIQUE INDEX [_PostToTag_AB_unique] ON _PostToTag([A], [B]); - --- CreateIndex -CREATE INDEX [_PostToTag_B_index] ON [_PostToTag]([B]); - --- AddForeignKey -ALTER TABLE [dbo].[_PostToTag] ADD CONSTRAINT [_PostToTag_A_fkey] FOREIGN KEY ([A]) REFERENCES [dbo].[Post]([id]) ON DELETE CASCADE ON UPDATE CASCADE; - --- AddForeignKey -ALTER TABLE [dbo].[_PostToTag] ADD CONSTRAINT [_PostToTag_B_fkey] FOREIGN KEY ([B]) REFERENCES [dbo].[Tag]([id]) ON DELETE CASCADE ON UPDATE CASCADE; -``` - -Congratulations, you just evolved your database with Prisma Migrate 🚀 diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/300-next-steps.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/300-next-steps.mdx deleted file mode 100644 index 9cbb67caa6..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/300-next-steps.mdx +++ /dev/null @@ -1,112 +0,0 @@ ---- -title: 'Next steps after adding Prisma ORM to your existing project' -sidebar_label: 'Next steps' -metaTitle: 'Next steps after adding Prisma ORM to your existing project' -metaDescription: 'Next steps to take now that you have successfully added Prisma ORM to your relational database project' -hide_table_of_contents: true ---- - -This section lists a number of potential next steps you can now take from here. Feel free to explore these or read the [Introduction](/orm/overview/introduction/what-is-prisma) page to get a high-level overview of Prisma ORM. - -### Continue exploring the Prisma Client API - -You can send a variety of queries with the Prisma Client API. Check out the [API reference](/orm/prisma-client) and use your existing database setup from this guide to try them out. - -:::tip - -You can use your editor's auto-completion feature to learn about the different API calls and the arguments it takes. Auto-completion is commonly invoked by hitting CTRL+SPACE on your keyboard. - -::: - -
-Expand for more Prisma Client API examples - -Here are a few suggestions for a number of more queries you can send with Prisma Client: - -**Filter all `Post` records that contain `"hello"`** - -```js -const filteredPosts = await prisma.post.findMany({ - where: { - OR: [ - { title: { contains: "hello" }, - { content: { contains: "hello" }, - ], - }, -}) -``` - -**Create a new `Post` record and connect it to an existing `User` record** - -```js -const post = await prisma.post.create({ - data: { - title: 'Join us for Prisma Day 2020', - author: { - connect: { email: 'alice@prisma.io' }, - }, - }, -}) -``` - -**Use the fluent relations API to retrieve the `Post` records of a `User` by traversing the relations** - -```js -const posts = await prisma.profile - .findUnique({ - where: { id: 1 }, - }) - .user() - .posts() -``` - -**Delete a `User` record** - -```js -const deletedUser = await prisma.user.delete({ - where: { email: 'sarah@prisma.io' }, -}) -``` - -
- -### Build an app with Prisma ORM - -The Prisma blog features comprehensive tutorials about Prisma ORM, check out our latest ones: - -- [Build a fullstack app with Next.js](https://www.youtube.com/watch?v=QXxy8Uv1LnQ&ab_channel=ByteGrad) -- [Build a fullstack app with Remix](https://www.prisma.io/blog/fullstack-remix-prisma-mongodb-1-7D0BfTXBmB6r) (5 parts, including videos) -- [Build a REST API with NestJS](https://www.prisma.io/blog/nestjs-prisma-rest-api-7D056s1BmOL0) - -### Explore the data in Prisma Studio - -Prisma Studio is a visual editor for the data in your database. Run `npx prisma studio` in your terminal. - -### Get query insights and analytics with Prisma Optimize - -[Prisma Optimize](/optimize) helps you generate insights and provides recommendations that can help you make your database queries faster. [Try it out now!](/optimize/getting-started) - -Optimize aims to help developers of all skill levels write efficient database queries, reducing database load and making applications more responsive. - -### Change the database schema (e.g. add more tables) - -To evolve the app, you need to follow the same flow of the tutorial: - -1. Manually adjust your database schema using SQL -1. Re-introspect your database -1. Optionally re-configure your Prisma Client API -1. Re-generate Prisma Client - -![Introspect workflow](/img/getting-started/prisma-evolve-app-workflow.png) - -### Try a Prisma ORM example - -The [`prisma-examples`](https://github.com/prisma/prisma-examples/) repository contains a number of ready-to-run examples: - -| Demo | Stack | Description | -| :------------------------------------------------------------------------------------------------------------------ | :----------- | --------------------------------------------------------------------------------------------------- | -| [`nextjs`](https://pris.ly/e/orm/nextjs) | Fullstack | Simple [Next.js](https://nextjs.org/) app | -| [`nextjs-graphql`](https://pris.ly/e/ts/graphql-nextjs) | Fullstack | Simple [Next.js](https://nextjs.org/) app (React) with a GraphQL API | -| [`graphql-nexus`](https://pris.ly/e/ts/graphql-nexus) | Backend only | GraphQL server based on [`@apollo/server`](https://www.apollographql.com/docs/apollo-server) | -| [`express`](https://pris.ly/e/ts/rest-express) | Backend only | Simple REST API with Express.JS | -| [`grpc`](https://pris.ly/e/ts/grpc) | Backend only | Simple gRPC API | diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/_install-prisma-client-partial.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/_install-prisma-client-partial.mdx deleted file mode 100644 index 2bf6ab6d15..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases/_install-prisma-client-partial.mdx +++ /dev/null @@ -1,25 +0,0 @@ -## Install and generate Prisma Client - -To get started with Prisma Client, first install the `@prisma/client` package: - -```terminal copy -npm install @prisma/client -``` - -Then, run `prisma generate` which reads your Prisma schema and generates the Prisma Client. - -```terminal copy -npx prisma generate -``` - -You can now import the `PrismaClient` constructor from the `@prisma/client` package to create an instance of Prisma Client to send queries to your database. You'll learn how to do that in the next section. - -:::note Good to know - -When you run `prisma generate`, you are actually creating code (TypeScript types, methods, queries, ...) that is tailored to _your_ Prisma schema file or files in the `prisma` directory. This means, that whenever you make changes to your Prisma schema file, you also need to update the Prisma Client. You can do this by running the `prisma generate` command. - -![Install and generate Prisma Client](/img/getting-started/prisma-client-install-and-generate.png) - -Whenever you update your Prisma schema, you will have to update your database schema using either `prisma migrate dev` or `prisma db push`. This will keep your database schema in sync with your Prisma schema. These commands will also run `prisma generate` under the hood to re-generate your Prisma Client. - -::: diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb-node-mongodb.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb-node-mongodb.mdx deleted file mode 100644 index 92366024f7..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb-node-mongodb.mdx +++ /dev/null @@ -1,58 +0,0 @@ ---- -title: 'Add Prisma ORM to an existing MongoDB project using JavaScript' -sidebar_label: 'MongoDB' -metaTitle: 'Add Prisma ORM to an existing MongoDB project using JavaScript (15 min)' -metaDescription: 'Learn how to add Prisma ORM to an existing Node.js project by connecting it to your MongoDB database and generating a Prisma Client for database access.' -toc: false -langSwitcher: ['typescript', 'node'] -hide_table_of_contents: true -dbSwitcher: ['mongodb'] -sidebar_class_name: hidden-sidebar -pagination_next: getting-started/setup-prisma/add-to-existing-project/mongodb/connect-your-database-node-mongodb -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/mongodb- ---- - -Learn how to add Prisma ORM to an existing Node.js or TypeScript project by connecting it to your database and generating a Prisma Client for database access. The following tutorial introduces you to [Prisma CLI](/orm/tools/prisma-cli), [Prisma Client](/orm/prisma-client), and [Prisma Introspection](/orm/prisma-schema/introspection). - - - -If you're migrating to Prisma ORM from Mongoose, see our [Migrate from Mongoose guide](/guides/migrate-from-mongoose). - - - -## Prerequisites - -In order to successfully complete this guide, you need: - -- [Node.js](https://nodejs.org/en/) installed on your machine (see [system requirements](/orm/reference/system-requirements) for officially supported versions) -- Access to a MongoDB 4.2+ server with a replica set deployment. We recommend using [MongoDB Atlas](https://www.mongodb.com/cloud/atlas). - - - - The MongoDB database connector uses transactions to support nested writes. Transactions **requires** a [replica set](https://www.mongodb.com/docs/manual/tutorial/deploy-replica-set/) deployment. The easiest way to deploy a replica set is with [Atlas](https://www.mongodb.com/docs/atlas/getting-started/). It's free to get started. - - - -Make sure you have your database [connection URL](/orm/reference/connection-urls) (that includes your authentication credentials) at hand! If you don't have a database server running and just want to explore Prisma ORM, check out the [Quickstart](/getting-started/quickstart-sqlite). - -> See [System requirements](/orm/reference/system-requirements) for exact version requirements. - -## Set up Prisma ORM - -As a first step, navigate into it your project directory that contains the `package.json` file. - -Next, add the Prisma CLI as a development dependency to your project: - -```terminal copy -npm install prisma --save-dev -``` - -:::note - -If your project contains multiple directories with `package.json` files (e.g., `frontend`, `backend`, etc.), note that Prisma ORM is specifically designed for use in the API/backend layer. To set up Prisma, navigate to the appropriate backend directory containing the relevant `package.json` file and configure Prisma there. - -::: - -import PrismaInitPartial from './_prisma-init-partial.mdx' - - diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb-typescript-mongodb.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb-typescript-mongodb.mdx deleted file mode 100644 index fec31143a6..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb-typescript-mongodb.mdx +++ /dev/null @@ -1,59 +0,0 @@ ---- -title: 'Add Prisma ORM to an existing MongoDB project using TypeScript ' -sidebar_label: 'MongoDB' -metaTitle: 'Add Prisma ORM to an existing MongoDB project using TypeScript (15 min)' -metaDescription: 'Learn how to add Prisma ORM to an existing TypeScript project by connecting it to your MongoDB database and generating a Prisma Client for database access.' -hide_table_of_contents: true -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['mongodb'] -sidebar_custom_props: { badge: '15 min' } -sidebar_class_name: hidden-sidebar -pagination_next: getting-started/setup-prisma/add-to-existing-project/mongodb/connect-your-database-typescript-mongodb -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/mongodb- ---- - -Learn how to add Prisma ORM to an existing Node.js or TypeScript project by connecting it to your database and generating a Prisma Client for database access. The following tutorial introduces you to [Prisma CLI](/orm/tools/prisma-cli), [Prisma Client](/orm/prisma-client), and [Prisma Introspection](/orm/prisma-schema/introspection). - - - -If you're migrating to Prisma ORM from Mongoose, see our [Migrate from Mongoose guide](/guides/migrate-from-mongoose). - - - -## Prerequisites - -In order to successfully complete this guide, you need: - -- [Node.js](https://nodejs.org/en/) installed on your machine (see [system requirements](/orm/reference/system-requirements) for officially supported versions) -- Access to a MongoDB 4.2+ server with a replica set deployment. We recommend using [MongoDB Atlas](https://www.mongodb.com/cloud/atlas). - - - - The MongoDB database connector uses transactions to support nested writes. Transactions **requires** a [replica set](https://www.mongodb.com/docs/manual/tutorial/deploy-replica-set/) deployment. The easiest way to deploy a replica set is with [Atlas](https://www.mongodb.com/docs/atlas/getting-started/). It's free to get started. - - - -Make sure you have your database [connection URL](/orm/reference/connection-urls) (that includes your authentication credentials) at hand! If you don't have a database server running and just want to explore Prisma ORM, check out the [Quickstart](/getting-started/quickstart-sqlite). - -> See [System requirements](/orm/reference/system-requirements) for exact version requirements. - -## Set up Prisma ORM - -As a first step, navigate into it your project directory that contains the `package.json` file. - -Next, add the Prisma CLI as a development dependency to your project: - -```terminal copy -npm install prisma --save-dev -``` - -:::note - -If your project contains multiple directories with `package.json` files (e.g., `frontend`, `backend`, etc.), note that Prisma ORM is specifically designed for use in the API/backend layer. To set up Prisma, navigate to the appropriate backend directory containing the relevant `package.json` file and configure Prisma there. - -::: - -import PrismaInitPartial from './_prisma-init-partial.mdx' - - - diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb/100-connect-your-database-node-mongodb.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb/100-connect-your-database-node-mongodb.mdx deleted file mode 100644 index 09e3fd39de..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb/100-connect-your-database-node-mongodb.mdx +++ /dev/null @@ -1,57 +0,0 @@ ---- -title: 'Connect MongoDB to your existing Node.js project' -sidebar_label: 'Connect your database (MongoDB)' -metaTitle: 'Connect your MongoDB database' -metaDescription: 'Connect your MongoDB database to your existing Node.js project' -langSwitcher: ['typescript', 'node'] -sidebar_class_name: hidden-sidebar -hide_table_of_contents: true -dbSwitcher: ['mongodb'] -toc: false -pagination_prev: getting-started/setup-prisma/add-to-existing-project/mongodb-node-mongodb -pagination_next: getting-started/setup-prisma/add-to-existing-project/mongodb/introspection-node-mongodb -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/mongodb/connect-your-database- ---- - -## Connecting your database - -To connect your database, you need to set the `url` field of the `datasource` block in your Prisma schema to your database [connection URL](/orm/reference/connection-urls): - -```prisma file=prisma/schema.prisma showLineNumbers -datasource db { - provider = "mongodb" - url = env("DATABASE_URL") -} -``` - -In this case, the `url` is [set via an environment variable](/orm/more/development-environment/environment-variables) which is defined in `.env`: - -```bash file=.env showLineNumbers -DATABASE_URL="mongodb+srv://test:test@cluster0.ns1yp.mongodb.net/myFirstDatabase" -``` - -You now need to adjust the connection URL to point to your own database. - -The [format of the connection URL](/orm/reference/connection-urls) for your database depends on the database you use. For MongoDB, it looks as follows (the parts spelled all-uppercased are _placeholders_ for your specific connection details): - -```no-lines -mongodb://USERNAME:PASSWORD@HOST:PORT/DATABASE -``` - -Here's a short explanation of each component: - -- `USERNAME`: The name of your database user -- `PASSWORD`: The password for your database user -- `HOST`: The host where a [`mongod`](https://www.mongodb.com/docs/manual/reference/program/mongod/#mongodb-binary-bin.mongod) (or [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos/#mongodb-binary-bin.mongos)) instance is running -- `PORT`: The port where your database server is running (typically `27017` for MongoDB) -- `DATABASE`: The name of the database. Note that if you're using MongoDB Atlas, you need to manually append the database name to the connection URL because the environment link from MongoDB Atlas doesn't contain it. - -## Troubleshooting - -### `Error in connector: SCRAM failure: Authentication failed.` - -If you see the `Error in connector: SCRAM failure: Authentication failed.` error message, you can specify the source database for the authentication by [adding](https://github.com/prisma/prisma/discussions/9994#discussioncomment-1562283) `?authSource=admin` to the end of the connection string. - -### `Raw query failed. Error code 8000 (AtlasError): empty database name not allowed.` - -If you see the `Raw query failed. Code: unknown. Message: Kind: Command failed: Error code 8000 (AtlasError): empty database name not allowed.` error message, be sure to append the database name to the database URL. You can find more info in this [GitHub issue](https://github.com/prisma/docs/issues/5562). \ No newline at end of file diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb/100-connect-your-database-typescript-mongodb.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb/100-connect-your-database-typescript-mongodb.mdx deleted file mode 100644 index f53849a73d..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb/100-connect-your-database-typescript-mongodb.mdx +++ /dev/null @@ -1,55 +0,0 @@ ---- -title: 'Connect your MongoDB database to your existing TypeScript project' -sidebar_label: 'Connect your database (MongoDB)' -metaTitle: 'Connect your MongoDB database using TypeScript' -metaDescription: 'Connect your MongoDB database to your existing TypeScript project' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['mongodb'] -hide_table_of_contents: true -pagination_prev: getting-started/setup-prisma/add-to-existing-project/mongodb-typescript-mongodb -pagination_next: getting-started/setup-prisma/add-to-existing-project/mongodb/introspection-typescript-mongodb -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/mongodb/connect-your-database- ---- - -## Connecting your database - -To connect your database, you need to set the `url` field of the `datasource` block in your Prisma schema to your database [connection URL](/orm/reference/connection-urls): - -```prisma file=prisma/schema.prisma showLineNumbers -datasource db { - provider = "mongodb" - url = env("DATABASE_URL") -} -``` - -In this case, the `url` is [set via an environment variable](/orm/more/development-environment/environment-variables) which is defined in `.env`: - -```bash file=.env showLineNumbers -DATABASE_URL="mongodb+srv://test:test@cluster0.ns1yp.mongodb.net/myFirstDatabase" -``` - -You now need to adjust the connection URL to point to your own database. - -The [format of the connection URL](/orm/reference/connection-urls) for your database depends on the database you use. For MongoDB, it looks as follows (the parts spelled all-uppercased are _placeholders_ for your specific connection details): - -```no-lines -mongodb://USERNAME:PASSWORD@HOST:PORT/DATABASE -``` - -Here's a short explanation of each component: - -- `USERNAME`: The name of your database user -- `PASSWORD`: The password for your database user -- `HOST`: The host where a [`mongod`](https://www.mongodb.com/docs/manual/reference/program/mongod/#mongodb-binary-bin.mongod) (or [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos/#mongodb-binary-bin.mongos)) instance is running -- `PORT`: The port where your database server is running (typically `27017` for MongoDB) -- `DATABASE`: The name of the database. Note that if you're using MongoDB Atlas, you need to manually append the database name to the connection URL because the environment link from MongoDB Atlas doesn't contain it. - -## Troubleshooting - -### `Error in connector: SCRAM failure: Authentication failed.` - -If you see the `Error in connector: SCRAM failure: Authentication failed.` error message, you can specify the source database for the authentication by [adding](https://github.com/prisma/prisma/discussions/9994#discussioncomment-1562283) `?authSource=admin` to the end of the connection string. - -### `Raw query failed. Error code 8000 (AtlasError): empty database name not allowed.` - -If you see the `Raw query failed. Code: unknown. Message: Kind: Command failed: Error code 8000 (AtlasError): empty database name not allowed.` error message, be sure to append the database name to the database URL. You can find more info in this [GitHub issue](https://github.com/prisma/docs/issues/5562). \ No newline at end of file diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb/125-introspection-node-mongodb.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb/125-introspection-node-mongodb.mdx deleted file mode 100644 index 7d4f30e8f9..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb/125-introspection-node-mongodb.mdx +++ /dev/null @@ -1,130 +0,0 @@ ---- -title: 'Introspection for MongoDB in a JavaScript project' -sidebar_label: 'Introspection' -metaTitle: 'Introspection: MongoDB and JavaScript' -metaDescription: 'Introspect your MongoDB database with Prisma ORM' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['mongodb'] -hide_table_of_contents: true -sidebar_class_name: hidden-sidebar -pagination_prev: getting-started/setup-prisma/add-to-existing-project/mongodb/connect-your-database-node-mongodb -pagination_next: getting-started/setup-prisma/add-to-existing-project/mongodb/install-prisma-client-node-mongodb -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/mongodb/introspection- ---- - - -Prisma ORM introspects a MongoDB schema by sampling the data stored in the given database and inferring the schema of that data. - -For the purposes of illustrating introspection, this guide will help you setup a MongoDB from scratch. But if you have a MongoDB database already, feel free to jump to [Initializing Prisma ORM](#initializing-prisma-orm) in your project. - -## Setting up your Database - -To see this in action, first create a `blog` database with 2 collections: `User` and `Post`. We recommend [MongoDB Compass](https://www.mongodb.com/products/tools/compass) for setting this up: - -![Create a blog database using Compass](/img/getting-started/1-create-database.jpg) - -First, add a user to our `User` collection: - -![Create a user within the User collection](/img/getting-started/2-create-user.jpg) - -Next, add some posts to our `Post` collection. It's important that the ObjectID in `userId` matches the user you created above. - -![Create some posts within the Post collection](/img/getting-started/3-create-posts.jpg) - -## Initializing Prisma ORM - -Now that you have a MongoDB database, the next step is to create a new project and initialize Prisma ORM: - -```terminal copy -mkdir blog -cd blog -npm init -y -npm install -D prisma -npx prisma init --datasource-provider mongodb --output ../generated/prisma -``` - -Initializing Prisma ORM will create a `prisma/schema.prisma` file like the following: - -```prisma file=prisma/schema.prisma showLineNumbers -datasource db { - provider = "mongodb" - url = env("DATABASE_URL") -} - -generator client { - provider = "prisma-client-js" -} -``` - -Next you'll need to adjust your `.env` file to point the `DATABASE_URL` to your MongoDB database - -## Introspecting MongoDB with Prisma ORM - -You're now ready to introspect. Run the following command to introspect your database: - -```terminal copy -npx prisma db pull -``` - -This command introspects our database and writes the inferred schema into your `prisma/schema.prisma` file: - -```prisma file=prisma/schema.prisma showLineNumbers -datasource db { - provider = "mongodb" - url = env("DATABASE_URL") -} - -generator client { - provider = "prisma-client-js" -} - -model Post { - id String @id @default(auto()) @map("_id") @db.ObjectId - title String - userId String @db.ObjectId -} - -model User { - id String @id @default(auto()) @map("_id") @db.ObjectId - email String -} -``` - -## Tweaking the Schema - -To be able to join data using Prisma Client, you can add the [`@relation`](/orm/reference/prisma-schema-reference#relation) attributes to our models: - -```prisma file=prisma/schema.prisma highlight=14;add|20;add showLineNumbers -datasource db { - provider = "mongodb" - url = env("DATABASE_URL") -} - -generator client { - provider = "prisma-client-js" -} - -model Post { - id String @id @default(auto()) @map("_id") @db.ObjectId - title String - userId String @db.ObjectId - //add-next-line - user User @relation(fields: [userId], references: [id]) -} - -model User { - id String @id @default(auto()) @map("_id") @db.ObjectId - email String - //add-next-line - posts Post[] -} -``` - -:::tip - -We're actively working on MongoDB introspection. Provide feedback for this feature in [this issue](https://github.com/prisma/prisma/issues/8241). - -::: - -And with that, you're ready to generate Prisma Client. - diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb/125-introspection-typescript-mongodb.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb/125-introspection-typescript-mongodb.mdx deleted file mode 100644 index d7f371fc9f..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb/125-introspection-typescript-mongodb.mdx +++ /dev/null @@ -1,129 +0,0 @@ ---- -title: 'Introspection for MongoDB in a TypeScript project' -sidebar_label: 'Introspection' -metaTitle: 'Introspection: MongoDB and TypeScript' -metaDescription: 'Introspection your MongoDB database with Prisma ORM' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['mongodb'] -hide_table_of_contents: true -pagination_prev: getting-started/setup-prisma/add-to-existing-project/mongodb/connect-your-database-typescript-mongodb -pagination_next: getting-started/setup-prisma/add-to-existing-project/mongodb/install-prisma-client-typescript-mongodb -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/mongodb/introspection- ---- - -# Introspection - -Prisma ORM introspects a MongoDB schema by sampling the data stored in the given database and inferring the schema of that data. - -For the purposes of illustrating introspection, this guide will help you setup a MongoDB from scratch. But if you have a MongoDB database already, feel free to jump to [Initializing Prisma ORM](#initializing-prisma-orm) in your project. - -## Setting up your Database - -To see this in action, first create a `blog` database with 2 collections: `User` and `Post`. We recommend [MongoDB Compass](https://www.mongodb.com/products/tools/compass) for setting this up: - -![Create a blog database using Compass](/img/getting-started/1-create-database.jpg) - -First, add a user to our `User` collection: - -![Create a user within the User collection](/img/getting-started/2-create-user.jpg) - -Next, add some posts to our `Post` collection. It's important that the ObjectID in `userId` matches the user you created above. - -![Create some posts within the Post collection](/img/getting-started/3-create-posts.jpg) - -## Initializing Prisma ORM - -Now that you have a MongoDB database, the next step is to create a new project and initialize Prisma ORM: - -```terminal copy -mkdir blog -cd blog -npm init -y -npm install -D prisma -npx prisma init --datasource-provider mongodb --output ../generated/prisma -``` - -Initializing Prisma ORM will create a `prisma/schema.prisma` file. Edit this file to use MongoDB: - -```prisma file=prisma/schema.prisma showLineNumbers -datasource db { - provider = "mongodb" - url = env("DATABASE_URL") -} - -generator client { - provider = "prisma-client-js" -} -``` - -Next you'll need to adjust your `.env` file to point the `DATABASE_URL` to your MongoDB database - -## Introspecting MongoDB with Prisma ORM - -You're now ready to introspect. Run the following command to introspect your database: - -```terminal copy -npx prisma db pull -``` - -This command introspects our database and writes the inferred schema into your `prisma/schema.prisma` file: - -```prisma file=prisma/schema.prisma showLineNumbers -datasource db { - provider = "mongodb" - url = env("DATABASE_URL") -} - -generator client { - provider = "prisma-client-js" -} - -model Post { - id String @id @default(auto()) @map("_id") @db.ObjectId - title String - userId String @db.ObjectId -} - -model User { - id String @id @default(auto()) @map("_id") @db.ObjectId - email String -} -``` - -## Tweaking the Schema - -To be able to join data using Prisma Client, you can add the [`@relation`](/orm/reference/prisma-schema-reference#relation) attributes to our models: - -```prisma file=prisma/schema.prisma highlight=14;add|20;add showLineNumbers -datasource db { - provider = "mongodb" - url = env("DATABASE_URL") -} - -generator client { - provider = "prisma-client-js" -} - -model Post { - id String @id @default(auto()) @map("_id") @db.ObjectId - title String - userId String @db.ObjectId - //add-next-line - user User @relation(fields: [userId], references: [id]) -} - -model User { - id String @id @default(auto()) @map("_id") @db.ObjectId - email String - //add-next-line - posts Post[] -} -``` - -:::tip - -We're actively working on MongoDB introspection. Provide feedback for this feature in [this issue](https://github.com/prisma/prisma/issues/8241). - -::: - -And with that, you're ready to generate Prisma Client. diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb/200-install-prisma-client-node-mongodb.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb/200-install-prisma-client-node-mongodb.mdx deleted file mode 100644 index 77bfa807a1..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb/200-install-prisma-client-node-mongodb.mdx +++ /dev/null @@ -1,28 +0,0 @@ ---- -title: 'Install Prisma Client in your existing JavaScript project (MongoDB)' -sidebar_label: 'Install Prisma Client' -metaTitle: 'Install Prisma Client in your existing project: JavaScript and MongoDB' -metaDescription: 'Install and generate Prisma Client in your existing project using a MongoDB database and Javascript.' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['mongodb'] -hide_table_of_contents: true -sidebar_class_name: hidden-sidebar -pagination_prev: getting-started/setup-prisma/add-to-existing-project/mongodb/introspection-node-mongodb -pagination_next: getting-started/setup-prisma/add-to-existing-project/mongodb/querying-the-database-node-mongodb -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/mongodb/install-prisma-client- ---- - -## Install and generate Prisma Client - -To get started with Prisma Client, you need to install the `@prisma/client` package: - -```terminal copy -npm install @prisma/client -``` - -The install command invokes `prisma generate` for you which reads your Prisma schema and generates a version of Prisma Client that is _tailored_ to your models. - -![Install and generate Prisma Client](/img/getting-started/prisma-client-install-and-generate.png) - -Whenever you make changes to your Prisma schema in the future, you manually need to invoke `prisma generate` in order to accommodate the changes in your Prisma Client API. - diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb/200-install-prisma-client-typescript-mongodb.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb/200-install-prisma-client-typescript-mongodb.mdx deleted file mode 100644 index a7b90e1c75..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb/200-install-prisma-client-typescript-mongodb.mdx +++ /dev/null @@ -1,26 +0,0 @@ ---- -title: 'Install Prisma Client in an existing TypeScript project (MongoDB)' -sidebar_label: 'Install Prisma Client' -metaTitle: 'Install Prisma Client in your existing project: TypeScript and MongoDB' -metaDescription: 'Install and generate Prisma Client in your existing project using a MongoDB database and TypeScript.' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['mongodb'] -hide_table_of_contents: true -pagination_prev: getting-started/setup-prisma/add-to-existing-project/mongodb/introspection-typescript-mongodb -pagination_next: getting-started/setup-prisma/add-to-existing-project/mongodb/querying-the-database-typescript-mongodb -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/mongodb/install-prisma-client- ---- - -## Install and generate Prisma Client - -To get started with Prisma Client, you need to install the `@prisma/client` package: - -```terminal copy -npm install @prisma/client -``` - -The install command invokes `prisma generate` for you which reads your Prisma schema and generates a version of Prisma Client that is _tailored_ to your models. - -![Install and generate Prisma Client](/img/getting-started/prisma-client-install-and-generate.png) - -Whenever you make changes to your Prisma schema in the future, you manually need to invoke `prisma generate` in order to accommodate the changes in your Prisma Client API. diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb/250-querying-the-database-node-mongodb.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb/250-querying-the-database-node-mongodb.mdx deleted file mode 100644 index e82d311963..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb/250-querying-the-database-node-mongodb.mdx +++ /dev/null @@ -1,220 +0,0 @@ ---- -title: 'Query your existing MongoDB database with JavaScript and Prisma ORM' -sidebar_label: 'Querying the database' -metaTitle: 'Querying the database in your existing project: MongoDB and JavaScript' -metaDescription: 'Write data to and query your MongoDB database in your existing project.' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['mongodb'] -hide_table_of_contents: true -sidebar_class_name: hidden-sidebar -pagination_prev: getting-started/setup-prisma/add-to-existing-project/mongodb/install-prisma-client-node-mongodb -pagination_next: getting-started/setup-prisma/add-to-existing-project/mongodb/next-steps -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/mongodb/querying-the-database- ---- - -## Write your first query with Prisma Client - -Now that you have generated Prisma Client, you can start writing queries to read and write data in your database. For the purpose of this guide, you'll use a plain Node.js script to explore some basic features of Prisma Client. - -If you're building a REST API, you can use Prisma Client in your route handlers to read and write data in the database based on incoming HTTP requests. If you're building a GraphQL API, you can use Prisma Client in your resolvers to read and write data in the database based on incoming queries and mutations. - -For the purpose of this guide however, you'll just create a plain Node.js script to learn how to send queries to your database using Prisma Client. Once you have an understanding of how the API works, you can start integrating it into your actual application code (e.g. REST route handlers or GraphQL resolvers). - -Create a new file named `index.js` and add the following code to it: - -```js file=index.js copy -const { PrismaClient } = require('@prisma/client') - -const prisma = new PrismaClient() - -async function main() { - // ... you will write your Prisma Client queries here -} - -main() - .then(async () => { - await prisma.$disconnect() - }) - .catch(async (e) => { - console.error(e) - await prisma.$disconnect() - process.exit(1) - }) -``` - -Here's a quick overview of the different parts of the code snippet: - -1. Import the `PrismaClient` constructor from the `@prisma/client` node module -1. Instantiate `PrismaClient` -1. Define an `async` function named `main` to send queries to the database -1. Connect to the database -1. Call the `main` function -1. Close the database connections when the script terminates - -Inside the `main` function, add the following query to read all `User` records from the database and print the result: - -```js file=index.js showLineNumbers -async function main() { -- // ... you will write your Prisma Client queries here -//add-start -+ const allUsers = await prisma.user.findMany() -+ console.log(allUsers) -//add-end -} -``` - -Now run the code with this command: - -```terminal copy -node index.js -``` - -If you introspected an existing database with records, the query should return an array of JavaScript objects. - -## Write data into the database - -The `findMany` query you used in the previous section only _reads_ data from the database (although it was still empty). In this section, you'll learn how to write a query to _write_ new records into the `Post`, `User` and `Comment` tables. - -Adjust the `main` function to send a `create` query to the database: - -```js file=index.js copy showLineNumbers -async function main() { - await prisma.user.create({ - data: { - name: 'Rich', - email: 'hello@prisma.com', - posts: { - create: { - title: 'My first post', - body: 'Lots of really interesting stuff', - slug: 'my-first-post', - }, - }, - }, - }) - - const allUsers = await prisma.user.findMany({ - include: { - posts: true, - }, - }) - console.dir(allUsers, { depth: null }) -} -``` - -This code creates a new `User` record together with a new `Post` using a [nested write](/orm/prisma-client/queries/relation-queries#nested-writes) query. The `User` record is connected to the other one via the `Post.author` ↔ `User.posts` [relation fields](/orm/prisma-schema/data-model/relations#relation-fields) respectively. - -Notice that you're passing the [`include`](/orm/prisma-client/queries/select-fields#return-nested-objects-by-selecting-relation-fields) option to `findMany` which tells Prisma Client to include the `posts` relations on the returned `User` objects. - -Run the code with this command: - -```terminal copy -node index.js -``` - -The output should look similar to this: - -```json no-lines -[ - { - id: '60cc9b0e001e3bfd00a6eddf', - email: 'hello@prisma.com', - name: 'Rich', - posts: [ - { - id: '60cc9bad005059d6007f45dd', - slug: 'my-first-post', - title: 'My first post', - body: 'Lots of really interesting stuff', - userId: '60cc9b0e001e3bfd00a6eddf', - }, - ], - }, -] -``` - -The query added new records to the `User` and the `Post` collections: - - - -The `id` field in the Prisma schema maps to `_id` in the underlying MongoDB database. - - - -**User** collection - -| **\_id** | **email** | **name** | -| :------------------------- | :------------------- | :------- | -| `60cc9b0e001e3bfd00a6eddf` | `"hello@prisma.com"` | `"Rich"` | - -**Post** collection - -| **\_id** | **createdAt** | **title** | **content** | **published** | **authorId** | -| :------------------------- | :------------------------- | :---------------- | :--------------------------------- | :------------ | :------------------------- | -| `60cc9bad005059d6007f45dd` | `2020-03-21T16:45:01.246Z` | `"My first post"` | `Lots of really interesting stuff` | `false` | `60cc9b0e001e3bfd00a6eddf` | - -> **Note**: The unique identifier in the `authorId` document field on `Post` reference the `_id` document field in the `User` collection, meaning the `_id` value `60cc9b0e001e3bfd00a6eddf` column therefore refers to the first (and only) `User` record in the database. - -Before moving on to the next section, you'll add a couple of comments to the `Post` record you just created using an `update` query. Adjust the `main` function as follows: - -```js file=index.js copy -async function main() { - await prisma.post.update({ - where: { - slug: 'my-first-post', - }, - data: { - comments: { - createMany: { - data: [ - { comment: 'Great post!' }, - { comment: "Can't wait to read more!" }, - ], - }, - }, - }, - }) - const posts = await prisma.post.findMany({ - include: { - comments: true, - }, - }) - - console.dir(posts, { depth: Infinity }) -} -``` - -Now run the code using the same command as before: - -```terminal copy -node index.js -``` - -You will see the following output: - -```json no-lines -[ - { - id: '60cc9bad005059d6007f45dd', - slug: 'my-first-post', - title: 'My first post', - body: 'Lots of really interesting stuff', - userId: '60cc9b0e001e3bfd00a6eddf', - comments: [ - { - id: '60cca420008a21d800578793', - postId: '60cca40300af8bf000f6ca99', - comment: 'Great post!', - }, - { - id: '60cca420008a21d800578794', - postId: '60cca40300af8bf000f6ca99', - comment: "Can't wait to try this!", - }, - ], - }, -] -``` - -Fantastic, you just wrote new data into your database for the first time using Prisma Client 🚀 - diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb/250-querying-the-database-typescript-mongodb.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb/250-querying-the-database-typescript-mongodb.mdx deleted file mode 100644 index 08f3d9ec9a..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb/250-querying-the-database-typescript-mongodb.mdx +++ /dev/null @@ -1,234 +0,0 @@ ---- -title: 'Query your existing MongoDB database with TypeScript and Prisma ORM' -sidebar_label: 'Querying the database' -metaTitle: 'Querying the database in your existing project: MongoDB and TypeScript' -metaDescription: 'Write data to and query your MongoDB database' -langSwitcher: ['typescript', 'node'] -dbSwitcher: ['mongodb'] -hide_table_of_contents: true -pagination_prev: getting-started/setup-prisma/add-to-existing-project/mongodb/install-prisma-client-typescript-mongodb -pagination_next: getting-started/setup-prisma/add-to-existing-project/mongodb/next-steps -slugSwitch: /getting-started/setup-prisma/add-to-existing-project/mongodb/querying-the-database- ---- - -## Write your first query with Prisma Client - -Now that you have generated Prisma Client, you can start writing queries to read and write data in your database. For the purpose of this guide, you'll use a plain Node.js script to explore some basic features of Prisma Client. - -If you're building a REST API, you can use Prisma Client in your route handlers to read and write data in the database based on incoming HTTP requests. If you're building a GraphQL API, you can use Prisma Client in your resolvers to read and write data in the database based on incoming queries and mutations. - -For the purpose of this guide however, you'll just create a plain Node.js script to learn how to send queries to your database using Prisma Client. Once you have an understanding of how the API works, you can start integrating it into your actual application code (e.g. REST route handlers or GraphQL resolvers). - -Create a new file named `index.ts` and add the following code to it: - -```js file=index.ts copy -import { PrismaClient } from './generated/prisma' - -const prisma = new PrismaClient() - -async function main() { - // ... you will write your Prisma Client queries here -} - -main() - .then(async () => { - await prisma.$disconnect() - }) - .catch(async (e) => { - console.error(e) - await prisma.$disconnect() - process.exit(1) - }) -``` - -Here's a quick overview of the different parts of the code snippet: - -1. Import the `PrismaClient` constructor from the `@prisma/client` node module -1. Instantiate `PrismaClient` -1. Define an `async` function named `main` to send queries to the database -1. Connect to the database -1. Call the `main` function -1. Close the database connections when the script terminates - -Inside the `main` function, add the following query to read all `User` records from the database and print the result: - -```ts file=index.ts showLineNumbers -async function main() { - // ... you will write your Prisma Client queries here -//add-start -+ const allUsers = await prisma.user.findMany() -+ console.log(allUsers) -//add-end -} -``` - -Now run the code with this command: - -```terminal copy -npx tsx index.ts -``` - -If you introspected an existing database with records, the query should return an array of JavaScript objects. - -## Write data into the database - -The `findMany` query you used in the previous section only _reads_ data from the database (although it was still empty). In this section, you'll learn how to write a query to _write_ new records into the `Post`, `User` and `Comment` tables. - -Adjust the `main` function to send a `create` query to the database: - -```ts file=index.ts copy showLineNumbers -async function main() { - await prisma.user.create({ - data: { - name: 'Rich', - email: 'hello@prisma.com', - posts: { - create: { - title: 'My first post', - body: 'Lots of really interesting stuff', - slug: 'my-first-post', - }, - }, - }, - }) - - const allUsers = await prisma.user.findMany({ - include: { - posts: true, - }, - }) - console.dir(allUsers, { depth: null }) -} -``` - -This code creates a new `User` record together with a new `Post` using a [nested write](/orm/prisma-client/queries/relation-queries#nested-writes) query. The `User` record is connected to the other one via the `Post.author` ↔ `User.posts` [relation fields](/orm/prisma-schema/data-model/relations#relation-fields) respectively. - -Notice that you're passing the [`include`](/orm/prisma-client/queries/select-fields#return-nested-objects-by-selecting-relation-fields) option to `findMany` which tells Prisma Client to include the `posts` relations on the returned `User` objects. - -Run the code with this command: - -```terminal copy -npx tsx index.ts -``` - -The output should look similar to this: - -```json no-lines -[ - { - id: '60cc9b0e001e3bfd00a6eddf', - email: 'hello@prisma.com', - name: 'Rich', - posts: [ - { - id: '60cc9bad005059d6007f45dd', - slug: 'my-first-post', - title: 'My first post', - body: 'Lots of really interesting stuff', - userId: '60cc9b0e001e3bfd00a6eddf', - }, - ], - }, -] -``` - -Also note that `allUsers` is _statically typed_ thanks to [Prisma Client's generated types](/orm/prisma-client/type-safety/operating-against-partial-structures-of-model-types). You can observe the type by hovering over the `allUsers` variable in your editor. It should be typed as follows: - -```ts no-lines showLineNumbers -const allUsers: (User & { - posts: Post[] -})[] - -export type Post = { - id: number - title: string - body: string | null - published: boolean - authorId: number | null -} -``` - -The query added new records to the `User` and the `Post` collections: - - - -The `id` field in the Prisma schema maps to `_id` in the underlying MongoDB database. - - - -**User** collection - -| **\_id** | **email** | **name** | -| :------------------------- | :------------------- | :------- | -| `60cc9b0e001e3bfd00a6eddf` | `"hello@prisma.com"` | `"Rich"` | - -**Post** collection - -| **\_id** | **createdAt** | **title** | **content** | **published** | **authorId** | -| :------------------------- | :------------------------- | :---------------- | :--------------------------------- | :------------ | :------------------------- | -| `60cc9bad005059d6007f45dd` | `2020-03-21T16:45:01.246Z` | `"My first post"` | `Lots of really interesting stuff` | `false` | `60cc9b0e001e3bfd00a6eddf` | - -> **Note**: The unique identifier in the `authorId` document field on `Post` reference the `_id` document field in the `User` collection, meaning the `_id` value `60cc9b0e001e3bfd00a6eddf` column therefore refers to the first (and only) `User` record in the database. - -Before moving on to the next section, you'll add a couple of comments to the `Post` record you just created using an `update` query. Adjust the `main` function as follows: - -```ts file=index.ts copy showLineNumbers -async function main() { - await prisma.post.update({ - where: { - slug: 'my-first-post', - }, - data: { - comments: { - createMany: { - data: [ - { comment: 'Great post!' }, - { comment: "Can't wait to read more!" }, - ], - }, - }, - }, - }) - const posts = await prisma.post.findMany({ - include: { - comments: true, - }, - }) - - console.dir(posts, { depth: Infinity }) -} -``` - -Now run the code using the same command as before: - -```terminal copy -npx tsx index.ts -``` - -You will see the following output: - -```json no-lines -[ - { - id: '60cc9bad005059d6007f45dd', - slug: 'my-first-post', - title: 'My first post', - body: 'Lots of really interesting stuff', - userId: '60cc9b0e001e3bfd00a6eddf', - comments: [ - { - id: '60cca420008a21d800578793', - postId: '60cca40300af8bf000f6ca99', - comment: 'Great post!', - }, - { - id: '60cca420008a21d800578794', - postId: '60cca40300af8bf000f6ca99', - comment: "Can't wait to try this!", - }, - ], - }, -] -``` - -Fantastic, you just wrote new data into your database for the first time using Prisma Client 🚀 diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb/300-next-steps.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb/300-next-steps.mdx deleted file mode 100644 index a088fcdf0f..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb/300-next-steps.mdx +++ /dev/null @@ -1,94 +0,0 @@ ---- -title: 'Next steps after adding Prisma ORM to an existing project using MongoDB' -sidebar_label: 'Next steps' -metaTitle: 'Next steps after adding Prisma ORM to an existing project using MongoDB' -metaDescription: 'Next steps to take now that you have successfully added Prisma ORM to your existing Node.js or TypeScript project.' -hide_table_of_contents: true ---- - -This section lists a number of potential next steps you can now take from here. Feel free to explore these or read the [Introduction](/orm/overview/introduction/what-is-prisma) page to get a high-level overview of Prisma ORM. - -### Continue exploring the Prisma Client API - -You can send a variety of queries with the Prisma Client API. Check out the [API reference](/orm/prisma-client) and use your existing database setup from this guide to try them out. - -:::tip - -You can use your editor's auto-completion feature to learn about the different API calls and the arguments it takes. Auto-completion is commonly invoked by hitting CTRL+SPACE on your keyboard. - -::: - -
-Expand for more Prisma Client API examples - -Here are a few suggestions for a number of more queries you can send with Prisma Client: - -**Filter all `Post` records that contain `"hello"`** - -```js -const filteredPosts = await prisma.post.findMany({ - where: { - OR: [{ title: { contains: 'hello' } }, { body: { contains: 'hello' } }], - }, -}) -``` - -**Create a new `Post` record and connect it to an existing `User` record** - -```js -const post = await prisma.post.create({ - data: { - title: 'Join us for Prisma Day 2020', - slug: 'prisma-day-2020', - body: 'A conference on modern application development and databases.', - user: { - connect: { email: 'hello@prisma.com' }, - }, - }, -}) -``` - -**Use the fluent relations API to retrieve the `Post` records of a `User` by traversing the relations** - -```js -const user = await prisma.comment - .findUnique({ - where: { id: '60ff4e9500acc65700ebf470' }, - }) - .post() - .user() -``` - -**Delete a `User` record** - -```js -const deletedUser = await prisma.user.delete({ - where: { email: 'sarah@prisma.io' }, -}) -``` - -
- -### Build an app with Prisma ORM - -The Prisma blog features comprehensive tutorials about Prisma ORM, check out our latest ones: - -- [Build a fullstack app with Next.js](https://www.youtube.com/watch?v=QXxy8Uv1LnQ&ab_channel=ByteGrad) -- [Build a fullstack app with Remix](https://www.prisma.io/blog/fullstack-remix-prisma-mongodb-1-7D0BfTXBmB6r) (5 parts, including videos) -- [Build a REST API with NestJS](https://www.prisma.io/blog/nestjs-prisma-rest-api-7D056s1BmOL0) - -### Explore the data in Prisma Studio - -Prisma Studio is a visual editor for the data in your database. Run `npx prisma studio` in your terminal. - -### Try a Prisma ORM example - -The [`prisma-examples`](https://github.com/prisma/prisma-examples/) repository contains a number of ready-to-run examples: - -| Demo | Stack | Description | -| :------------------------------------------------------------------------------------------------------------------ | :----------- | --------------------------------------------------------------------------------------------------- | -| [`nextjs`](https://pris.ly/e/orm/nextjs) | Fullstack | Simple [Next.js](https://nextjs.org/) app | -| [`nextjs-graphql`](https://pris.ly/e/ts/graphql-nextjs) | Fullstack | Simple [Next.js](https://nextjs.org/) app (React) with a GraphQL API | -| [`graphql-nexus`](https://pris.ly/e/ts/graphql-nexus) | Backend only | GraphQL server based on [`@apollo/server`](https://www.apollographql.com/docs/apollo-server) | -| [`express`](https://pris.ly/e/ts/rest-express) | Backend only | Simple REST API with Express.JS | -| [`grpc`](https://pris.ly/e/ts/grpc) | Backend only | Simple gRPC API | diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/_prisma-init-partial.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/_prisma-init-partial.mdx deleted file mode 100644 index 4fdfa6d8f3..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/_prisma-init-partial.mdx +++ /dev/null @@ -1,33 +0,0 @@ -import CodeBlock from '@theme/CodeBlock'; - -You can now invoke the Prisma CLI by prefixing it with `npx`: - -```terminal -npx prisma -``` - -:::info - -See [installation instructions](/orm/tools/prisma-cli#installation) to learn how to install Prisma ORM using a different package manager. - -::: - -Next, set up your Prisma ORM project by creating your [Prisma Schema](/orm/prisma-schema) file with the following command: - -{`npx prisma init --datasource-provider ${props.datasource.toLowerCase()} --output ../generated/prisma`} - -This command does a few things: - -- Creates a new directory called `prisma` that contains a file called `schema.prisma`, which contains the Prisma Schema with your database connection variable and schema models. -- Sets the `datasource` to {props.datasource} and the output to a custom location, respectively. -- Creates the [`.env` file](/orm/more/development-environment/environment-variables) in the root directory of the project, which is used for defining environment variables (such as your database connection) - -Note that the default schema created by `prisma init` uses PostgreSQL as the `provider`. If you didn't specify a provider with the `datasource-provider` option, you need to edit the `datasource` block to use the {props.datasource.toLowerCase()} provider instead: - - -{`datasource db { - //edit-next-line - provider = "${props.datasource.toLowerCase()}" - url = env("DATABASE_URL") -}`} - \ No newline at end of file diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/index.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/index.mdx deleted file mode 100644 index 142fedb80d..0000000000 --- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/index.mdx +++ /dev/null @@ -1,16 +0,0 @@ ---- -title: 'Add to existing project' -metaTitle: 'Add Prisma ORM to an existing project' -metaDescription: 'Learn how to add Prisma ORM to an existing Node.js or TypeScript project by connecting it to your database of choice and generating a Prisma Client for database access.' -hide_table_of_contents: true ---- - - - -Include Prisma ORM in an existing project with the following documentation, which explains some core concepts as it guides you through integrating Prisma ORM into your workflow. - - - -## In this section - - diff --git a/content/100-getting-started/02-setup-prisma/index.mdx b/content/100-getting-started/02-setup-prisma/index.mdx deleted file mode 100644 index 3532293fe7..0000000000 --- a/content/100-getting-started/02-setup-prisma/index.mdx +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: 'Set up Prisma ORM' -metaTitle: 'Set up Prisma ORM' -metaDescription: 'Get started with Prisma ORM and your favorite database. Learn about data modeling, migrations and querying.' -hide_table_of_contents: true -staticLink: true ---- - -Start from scratch or add Prisma ORM to an existing project. The following tutorials introduce you to the [Prisma CLI](/orm/tools/prisma-cli), [Prisma Client](/orm/prisma-client), and [Prisma Migrate](/orm/prisma-migrate). - -## In this section - - diff --git a/content/100-getting-started/03-prisma-postgres/100-from-the-cli.mdx b/content/100-getting-started/03-prisma-postgres/100-from-the-cli.mdx index 49fad38bf8..9d3e6275ff 100644 --- a/content/100-getting-started/03-prisma-postgres/100-from-the-cli.mdx +++ b/content/100-getting-started/03-prisma-postgres/100-from-the-cli.mdx @@ -113,16 +113,87 @@ Next, initialize TypeScript with a `tsconfig.json` file in the project: npx tsc --init ``` -### 2.2. Set up Prisma ORM +### 2.2. Configure ESM support + +Update `tsconfig.json` for ESM compatibility: + +```json file=tsconfig.json +{ + "compilerOptions": { + "module": "ESNext", + "moduleResolution": "node", + "target": "ES2023", + "strict": true, + "esModuleInterop": true, + "ignoreDeprecations": "6.0" + } +} +``` + +Update `package.json` to enable ESM: + +```json file=package.json +{ + // add-start + "type": "module", + // add-end +} +``` + +### 2.3. Set up Prisma ORM Install the required dependencies to use Prisma Postgres: ```terminal npm install prisma --save-dev -npm install @prisma/extension-accelerate +npm install @prisma/client @prisma/adapter-pg dotenv +``` + +Here's what each package does: + +- **`prisma`** - The Prisma CLI for running commands like `prisma migrate` and `prisma generate` +- **`@prisma/client`** - The Prisma Client library for querying your database +- **`@prisma/adapter-pg`** - The [`node-postgres` driver adapter](/orm/overview/databases/postgresql#using-the-node-postgres-driver) that connects Prisma Client to your database +- **`dotenv`** - Loads environment variables from your `.env` file + +### 2.4. Create prisma.config.ts + +Create a `prisma.config.ts` file in the root directory for Prisma configuration: + +```typescript file=prisma.config.ts +import { defineConfig, env } from 'prisma/config' + +export default defineConfig({ + schema: 'prisma/schema.prisma', + migrations: { + path: 'prisma/migrations', + }, + datasource: { + url: env('DATABASE_URL'), + }, +}) ``` -### 2.3. Create a TypeScript script +Add `dotenv` to `prisma.config.ts` so that Prisma can load environment variables from your `.env` file: + +```typescript file=prisma.config.ts +// add-start +import 'dotenv/config' +// add-end +import { defineConfig, env } from 'prisma/config' + +export default defineConfig({ + schema: 'prisma/schema.prisma', + migrations: { + path: 'prisma/migrations', + }, + datasource: { + url: env('DATABASE_URL'), + }, +}) +``` + +### 2.5. Create a script to query the database Create an `index.ts` file in the root directory, this will be used to query your application with Prisma ORM: @@ -132,9 +203,18 @@ touch index.ts ## 3. Migrate the database schema -Update your `prisma/schema.prisma` file to include a simple `User` model: +Update your `prisma/schema.prisma` file to include the `User` and `Post` models: ```prisma file=prisma/schema.prisma +generator client { + provider = "prisma-client" + output = "../generated/prisma" +} + +datasource db { + provider = "postgresql" +} + model User { id Int @id @default(autoincrement()) email String @unique @@ -158,15 +238,39 @@ After adding the models, migrate your database using [Prisma Migrate](/orm/prism npx prisma migrate dev --name init ``` +This command creates the database tables based on your schema. + +Now run the following command to generate the Prisma Client: + +```terminal +npx prisma generate +``` + ## 4. Send queries with Prisma ORM +### 4.1. Instantiate Prisma Client + +Create a `lib/prisma.ts` file to instantiate Prisma Client with the driver adapter: + +```typescript file=lib/prisma.ts +import "dotenv/config"; +import { PrismaPg } from '@prisma/adapter-pg' +import { PrismaClient } from '../generated/prisma/client' + +const connectionString = `${process.env.DATABASE_URL}` + +const adapter = new PrismaPg({ connectionString }) +const prisma = new PrismaClient({ adapter }) + +export { prisma } +``` + +### 4.2. Write your first query + Paste the following boilerplate into `index.ts`: ```ts file=index.ts -import { PrismaClient } from './generated/prisma' -import { withAccelerate } from '@prisma/extension-accelerate' - -const prisma = new PrismaClient().$extends(withAccelerate()) +import { prisma } from './lib/prisma' async function main() { // ... you will write your Prisma ORM queries here @@ -185,15 +289,12 @@ main() This code contains a `main` function that's invoked at the end of the script. It also instantiates `PrismaClient` which you'll use to send queries to your database. -### 4.1. Create a new `User` record +### 4.3. Create a new `User` record Let's start with a small query to create a new `User` record in the database and log the resulting object to the console. Add the following code to your `index.ts` file: ```ts file=index.ts -import { PrismaClient } from './generated/prisma' -import { withAccelerate } from '@prisma/extension-accelerate' - -const prisma = new PrismaClient().$extends(withAccelerate()) +import { prisma } from './lib/prisma' async function main() { // add-start @@ -241,17 +342,14 @@ npx tsx index.ts Great job, you just created your first database record with Prisma Postgres! 🎉 -### 4.2. Retrieve all `User` records +### 4.4. Retrieve all `User` records Prisma ORM offers various queries to read data from your database. In this section, you'll use the `findMany` query that returns _all_ the records in the database for a given model. Delete the previous Prisma ORM query and add the new `findMany` query instead: ```ts file=index.ts -import { PrismaClient } from './generated/prisma' -import { withAccelerate } from '@prisma/extension-accelerate' - -const prisma = new PrismaClient().$extends(withAccelerate()) +import { prisma } from './lib/prisma' async function main() { // add-start @@ -295,17 +393,14 @@ npx tsx index.ts Notice how the single `User` object is now enclosed with square brackets in the console. That's because the `findMany` returned an array with a single object inside. -### 4.3. Explore relation queries +### 4.5. Explore relation queries One of the main features of Prisma ORM is the ease of working with [relations](/orm/prisma-schema/data-model/relations). In this section, you'll learn how to create a `User` and a `Post` record in a nested write query. Afterwards, you'll see how you can retrieve the relation from the database using the `include` option. First, adjust your script to include the nested query: ```ts file=index.ts -import { PrismaClient } from './generated/prisma' -import { withAccelerate } from '@prisma/extension-accelerate' - -const prisma = new PrismaClient().$extends(withAccelerate()) +import { prisma } from './lib/prisma' async function main() { // add-start @@ -367,10 +462,7 @@ npx tsx index.ts In order to also retrieve the `Post` records that belong to a `User`, you can use the `include` option via the `posts` relation field: ```ts file=index.ts -import { PrismaClient } from './generated/prisma' -import { withAccelerate } from '@prisma/extension-accelerate' - -const prisma = new PrismaClient().$extends(withAccelerate()) +import { prisma } from './lib/prisma' async function main() { // add-start @@ -444,14 +536,14 @@ This time, you're seeing two `User` objects being printed. Both of them have a ` ## Next steps -You just got your feet wet with a basic Prisma Postgres setup. If you want to explore more complex queries, such as adding caching functionality, check out the official [Quickstart](/getting-started/quickstart-prismaPostgres). +You just got your feet wet with a basic Prisma Postgres setup. If you want to explore more complex queries, such as adding caching functionality, check out the official [Quickstart](/getting-started/prisma-orm/quickstart/prisma-postgres). ### View and edit data in Prisma Studio Prisma ORM comes with a built-in GUI to view and edit the data in your database. You can open it using the following command: ```terminal -npx prisma studio +npx prisma studio --config ./prisma.config.ts ``` With Prisma Postgres, you can also directly use Prisma Studio inside the [Console](https://console.prisma.io) by selecting the **Studio** tab in your project. diff --git a/content/100-getting-started/03-prisma-postgres/100-quickstart/100-kysely.mdx b/content/100-getting-started/03-prisma-postgres/100-quickstart/100-kysely.mdx new file mode 100644 index 0000000000..1b2b1ff247 --- /dev/null +++ b/content/100-getting-started/03-prisma-postgres/100-quickstart/100-kysely.mdx @@ -0,0 +1,151 @@ +--- +title: 'Use Prisma Postgres with Kysely' +sidebar_label: 'Kysely' +metaTitle: 'Quickstart: Kysely with Prisma Postgres (10 min)' +metaDescription: 'Get started with Kysely and Prisma Postgres by creating a type-safe SQL query builder for your database.' +sidebar_custom_props: { badge: '10 min' } +--- + +[Kysely](https://kysely.dev) is a type-safe TypeScript SQL query builder that provides excellent TypeScript support and a fluent API for building SQL queries. In this guide, you'll learn how to connect Kysely to [Prisma Postgres](/postgres) and start querying your database with full type safety. + +## Prerequisites + +- **Node.js** - Version 14 or higher +- **TypeScript** - Version 4.6 or higher (5.4+ recommended for better type inference) +- A [Prisma Data Platform](https://console.prisma.io) account +- (Optional) **Kysely setup** - If you already have Kysely configured in your project, skip to [step 2](#2-get-your-direct-connection-string) + +For detailed Kysely installation and configuration, see the [Kysely Getting started guide](https://kysely.dev/docs/getting-started). + +## 1. Create a Prisma Postgres database + +Follow these steps to create your Prisma Postgres database: + +1. Log in to [Prisma Data Platform](https://console.prisma.io) and open the Console. +2. In a workspace of your choice, click the **New project** button. +3. Type a name for your project in the **Name** field, e.g. `kysely-quickstart`. +4. In the **Prisma Postgres** section, click the **Get started** button. +5. In the **Region** dropdown, select the region that's closest to your current location, e.g. US East (N. Virginia). +6. Click the **Create project** button. + +At this point, you'll be redirected to the Database page where you will need to wait for a few seconds while the status of your database changes from **PROVISIONING** to **CONNECTED**. + +Once the green **CONNECTED** label appears, your database is ready to use! + +## 2. Get your direct connection string + +To connect to Prisma Postgres via direct TCP, you need to: + +1. Open your project in the Prisma Console. +2. Navigate to your active Prisma Postgres instance. +3. Click the **API Keys** tab in the project's sidenav. +4. Click the **Create API key** button. +5. In the popup, provide a **Name** for the API key and click **Create**. +6. Copy the connection string starting with `postgres://`, this is your direct connection string. + +## 3. Create a new project + +Create a new directory for your project and initialize it: + +```terminal +mkdir kysely-quickstart +cd kysely-quickstart +npm init -y +``` + +## 4. Configure Kysely with Prisma Postgres + +Create a database connection file that uses your Prisma Postgres connection string: + + +```typescript file=database.ts +import { Pool } from 'pg' +import { Kysely, PostgresDialect } from 'kysely' + +const dialect = new PostgresDialect({ + pool: new Pool({ + connectionString: process.env.DATABASE_URL, + max: 10, + }) +}) + +// Define your database interface +interface Database { + users: { + id: number + email: string + name: string | null + } + posts: { + id: number + title: string + content: string | null + published: boolean + author_id: number + } +} + +export const db = new Kysely({ + dialect, +}) +``` + +Create a `.env` file and add your Prisma Postgres connection string: + +```env file=.env +DATABASE_URL="postgres://USER:PASSWORD@db.prisma.io:5432/?sslmode=require" +``` + +## 5. Use Kysely with Prisma Postgres + +Now you can use Kysely to query your Prisma Postgres database: + +```typescript file=script.ts +import { db } from './database' + +async function main() { + // Insert a user + const user = await db + .insertInto('users') + .values({ + email: 'alice@prisma.io', + name: 'Alice', + }) + .returningAll() + .executeTakeFirstOrThrow() + + console.log('Created user:', user) + + // Query all users + const users = await db + .selectFrom('users') + .selectAll() + .execute() + + console.log('All users:', users) +} + +main() + .then(async () => { + await db.destroy() + }) + .catch(async (error) => { + console.error('Error:', error) + await db.destroy() + process.exit(1) + }) +``` + +## Next steps + +Now that you have Kysely connected to Prisma Postgres, you can: + +- **Learn more about Kysely** - Check out the [Kysely documentation](https://kysely.dev/docs/intro) for advanced query patterns +- **Explore migrations** - Learn about [Kysely migrations](https://kysely.dev/docs/migrations) for managing schema changes +- **Add more complex queries** - Explore [joins](https://kysely.dev/docs/category/join), [subqueries](https://kysely.dev/docs/examples/join/subquery-join), and [transactions](https://kysely.dev/docs/category/transactions) + +## More info + +- [Kysely documentation](https://kysely.dev) +- [Prisma Postgres documentation](/postgres) +- [PostgreSQL driver documentation](https://node-postgres.com) diff --git a/content/100-getting-started/03-prisma-postgres/100-quickstart/200-drizzle-orm.mdx b/content/100-getting-started/03-prisma-postgres/100-quickstart/200-drizzle-orm.mdx new file mode 100644 index 0000000000..c729d66565 --- /dev/null +++ b/content/100-getting-started/03-prisma-postgres/100-quickstart/200-drizzle-orm.mdx @@ -0,0 +1,193 @@ +--- +title: 'Use Prisma Postgres with Drizzle ORM' +sidebar_label: 'Drizzle ORM' +metaTitle: 'Quickstart: Drizzle ORM with Prisma Postgres (10 min)' +metaDescription: 'Get started with Drizzle ORM and Prisma Postgres by creating a lightweight, performant TypeScript ORM for your database.' +sidebar_custom_props: { badge: '10 min' } +--- + +[Drizzle ORM](https://orm.drizzle.team) is a lightweight and performant TypeScript ORM with developer experience in mind. It provides a SQL-like syntax with full TypeScript support and excellent performance. In this guide, you'll learn how to connect Drizzle ORM to [Prisma Postgres](/postgres) and start building type-safe database queries. + +## Prerequisites + +- **Node.js** - Version 16 or higher +- **TypeScript** - Version 5.0 or higher +- A [Prisma Data Platform](https://console.prisma.io) account +- (Optional) **Drizzle ORM setup** - If you already have Drizzle configured in your project, skip to [step 2](#2-get-your-direct-connection-string) + +For detailed Drizzle ORM installation and configuration, see the [Drizzle ORM Getting started guide](https://orm.drizzle.team/docs/get-started-postgresql). + +## 1. Create a Prisma Postgres database + +Follow these steps to create your Prisma Postgres database: + +1. Log in to [Prisma Data Platform](https://console.prisma.io) and open the Console. +2. In a workspace of your choice, click the **New project** button. +3. Type a name for your project in the **Name** field, e.g. `drizzle-quickstart`. +4. In the **Prisma Postgres** section, click the **Get started** button. +5. In the **Region** dropdown, select the region that's closest to your current location, e.g. US East (N. Virginia). +6. Click the **Create project** button. + +At this point, you'll be redirected to the Database page where you will need to wait for a few seconds while the status of your database changes from **PROVISIONING** to **CONNECTED**. + +Once the green **CONNECTED** label appears, your database is ready to use! + +## 2. Get your direct connection string + +To connect to Prisma Postgres via direct TCP, you need to: + +1. Open your project in the Prisma Console. +2. Navigate to your active Prisma Postgres instance. +3. Click the **API Keys** tab in the project's sidenav. +4. Click the **Create API key** button. +5. In the popup, provide a **Name** for the API key and click **Create**. +6. Copy the connection string starting with `postgres://`, this is your direct connection string. + +## 3. Create a new project + +Create a new directory for your project and initialize it: + +```terminal +mkdir drizzle-quickstart +cd drizzle-quickstart +npm init -y +``` + +## 4. Configure Drizzle ORM with Prisma Postgres + +Define your database schema using Drizzle's schema definition: + + +```typescript file=schema.ts +import { pgTable, serial, text, varchar, boolean, timestamp, integer } from 'drizzle-orm/pg-core' +import { relations } from 'drizzle-orm' + +export const users = pgTable('users', { + id: serial('id').primaryKey(), + email: varchar('email', { length: 255 }).notNull().unique(), + name: text('name'), + createdAt: timestamp('created_at').defaultNow().notNull(), +}) + +export const posts = pgTable('posts', { + id: serial('id').primaryKey(), + title: varchar('title', { length: 255 }).notNull(), + content: text('content'), + published: boolean('published').default(false).notNull(), + authorId: integer('author_id') + .notNull() + .references(() => users.id, { onDelete: 'cascade' }), + createdAt: timestamp('created_at').defaultNow().notNull(), +}) + +// Define relations +export const usersRelations = relations(users, ({ many }) => ({ + posts: many(posts), +})) + +export const postsRelations = relations(posts, ({ one }) => ({ + author: one(users, { + fields: [posts.authorId], + references: [users.id], + }), +})) +``` + +Configure Drizzle Kit with your Prisma Postgres connection string: + +```typescript file=drizzle.config.ts +import { defineConfig } from 'drizzle-kit' + +export default defineConfig({ + schema: './schema.ts', + out: './drizzle', + dialect: 'postgresql', + dbCredentials: { + url: process.env.DATABASE_URL!, + }, +}) +``` + +Create a `.env` file and add your Prisma Postgres connection string: + +```env file=.env +DATABASE_URL="postgres://USER:PASSWORD@db.prisma.io:5432/?sslmode=require" +``` + +Create a database connection file: + +```typescript file=db.ts +import { drizzle } from 'drizzle-orm/node-postgres' +import { Pool } from 'pg' +import * as schema from './schema' + +const pool = new Pool({ + connectionString: process.env.DATABASE_URL, +}) + +export const db = drizzle({ client: pool, schema }) +``` + +## 5. Use Drizzle ORM with Prisma Postgres + +Generate and push your schema to the database: + +```terminal +npx drizzle-kit push +``` + +Now you can use Drizzle ORM to query your Prisma Postgres database: + +```typescript file=script.ts +import { db } from './db' +import { users, posts } from './schema' +import { eq } from 'drizzle-orm' + +async function main() { + // Insert a user + const [user] = await db + .insert(users) + .values({ + name: 'Alice', + email: 'alice@prisma.io', + }) + .returning() + + console.log('Created user:', user) + + // Query users with their posts + const usersWithPosts = await db.query.users.findMany({ + with: { + posts: true, + }, + }) + + console.log('Users with posts:', JSON.stringify(usersWithPosts, null, 2)) +} + +main() + .then(() => { + console.log('Done!') + process.exit(0) + }) + .catch((error) => { + console.error('Error:', error) + process.exit(1) + }) +``` + +## Next steps + +Now that you have Drizzle ORM connected to Prisma Postgres, you can: + +- **Learn more about Drizzle** - Check out the [Drizzle ORM documentation](https://orm.drizzle.team/docs/overview) for advanced features +- **Explore queries** - Learn about [select queries](https://orm.drizzle.team/docs/select), [joins](https://orm.drizzle.team/docs/joins), and [transactions](https://orm.drizzle.team/docs/transactions) +- **Manage migrations** - Explore [Drizzle Kit migrations](https://orm.drizzle.team/docs/migrations) for schema management +- **Use relational queries** - Take advantage of [Drizzle's relational query API](https://orm.drizzle.team/docs/rqb) for cleaner code + +## More info + +- [Drizzle ORM documentation](https://orm.drizzle.team) +- [Drizzle ORM GitHub repository](https://github.com/drizzle-team/drizzle-orm) +- [Prisma Postgres documentation](/postgres) +- [Drizzle Kit documentation](https://orm.drizzle.team/kit-docs/overview) diff --git a/content/100-getting-started/03-prisma-postgres/100-quickstart/300-typeorm.mdx b/content/100-getting-started/03-prisma-postgres/100-quickstart/300-typeorm.mdx new file mode 100644 index 0000000000..ff923f02cc --- /dev/null +++ b/content/100-getting-started/03-prisma-postgres/100-quickstart/300-typeorm.mdx @@ -0,0 +1,185 @@ +--- +title: 'Use Prisma Postgres with TypeORM' +sidebar_label: 'TypeORM' +metaTitle: 'Quickstart: TypeORM with Prisma Postgres (10 min)' +metaDescription: 'Get started with TypeORM and Prisma Postgres by connecting your TypeScript ORM to a managed PostgreSQL database.' +sidebar_custom_props: { badge: '10 min' } +--- + +[TypeORM](https://typeorm.io) is a feature-rich ORM that supports both Active Record and Data Mapper patterns, providing flexibility in how you structure your database code. In this guide, you'll learn how to connect TypeORM to [Prisma Postgres](/postgres) and start building type-safe database applications. + +## Prerequisites + +- **Node.js** - Version 16 or higher +- **TypeScript** - Version 4.5 or higher +- A [Prisma Data Platform](https://console.prisma.io) account +- (Optional) **TypeORM setup** - If you already have TypeORM configured in your project, skip to [step 2](#2-get-your-direct-connection-string) + +For detailed TypeORM installation and configuration, see the [TypeORM Getting started guide](https://typeorm.io/docs/getting-started/). + +## 1. Create a Prisma Postgres database + +Follow these steps to create your Prisma Postgres database: + +1. Log in to [Prisma Data Platform](https://console.prisma.io) and open the Console. +2. In a workspace of your choice, click the **New project** button. +3. Type a name for your project in the **Name** field, e.g. `typeorm-quickstart`. +4. In the **Prisma Postgres** section, click the **Get started** button. +5. In the **Region** dropdown, select the region that's closest to your current location, e.g. US East (N. Virginia). +6. Click the **Create project** button. + +At this point, you'll be redirected to the Database page where you will need to wait for a few seconds while the status of your database changes from **PROVISIONING** to **CONNECTED**. + +Once the green **CONNECTED** label appears, your database is ready to use! + +## 2. Get your direct connection string + +To connect to Prisma Postgres via direct TCP, you need to: + +1. Open your project in the Prisma Console. +2. Navigate to your active Prisma Postgres instance. +3. Click the **API Keys** tab in the project's sidenav. +4. Click the **Create API key** button. +5. In the popup, provide a **Name** for the API key and click **Create**. +6. Copy the connection string starting with `postgres://`, this is your direct connection string. + +## 3. Configure TypeORM with Prisma Postgres + +Update your TypeORM DataSource configuration to use your Prisma Postgres connection string. In your `data-source.ts` (or equivalent configuration file): + +```typescript file=data-source.ts +import "reflect-metadata" +import { DataSource } from "typeorm" +import { User } from "./entity/User" +import { Post } from "./entity/Post" + +export const AppDataSource = new DataSource({ + type: "postgres", + url: process.env.DATABASE_URL, // Your Prisma Postgres connection string + synchronize: true, // Set to false in production + logging: false, + entities: [User, Post], + migrations: [], + subscribers: [], +}) +``` + +Create a `.env` file and add your Prisma Postgres connection string: + +```env file=.env +DATABASE_URL="postgres://USER:PASSWORD@db.prisma.io:5432/?sslmode=require" +``` + +:::tip + +For production applications, set `synchronize: false` and use [TypeORM migrations](https://typeorm.io/docs/migrations/setup) to manage schema changes safely. + +::: + +## 4. Define your entities + +Create your TypeORM entities as usual. Here's an example with User and Post entities: + +```typescript file=entity/User.ts +import { Entity, PrimaryGeneratedColumn, Column, OneToMany } from "typeorm" +import { Post } from "./Post" + +@Entity() +export class User { + @PrimaryGeneratedColumn() + id: number + + @Column({ unique: true }) + email: string + + @Column({ nullable: true }) + name: string + + @OneToMany(() => Post, (post) => post.author) + posts: Post[] +} +``` + +```typescript file=entity/Post.ts +import { Entity, PrimaryGeneratedColumn, Column, ManyToOne } from "typeorm" +import { User } from "./User" + +@Entity() +export class Post { + @PrimaryGeneratedColumn() + id: number + + @Column() + title: string + + @Column({ type: "text", nullable: true }) + content: string + + @Column({ default: false }) + published: boolean + + @ManyToOne(() => User, (user) => user.posts) + author: User +} +``` + +For more information on defining entities, see the [TypeORM Entities documentation](https://typeorm.io/docs/entity/entities). + +## 5. Initialize and use TypeORM + +Initialize your DataSource and start querying: + +```typescript file=index.ts +import "reflect-metadata" +import { AppDataSource } from "./data-source" +import { User } from "./entity/User" +import { Post } from "./entity/Post" + +AppDataSource.initialize() + .then(async () => { + console.log("Connected to Prisma Postgres!") + + // Create a user with a post + const user = new User() + user.email = "alice@prisma.io" + user.name = "Alice" + await AppDataSource.manager.save(user) + + const post = new Post() + post.title = "Hello World" + post.content = "This is my first post!" + post.published = true + post.author = user + await AppDataSource.manager.save(post) + + console.log("Created user and post!") + + // Query users with their posts + const users = await AppDataSource.getRepository(User).find({ + relations: { + posts: true, + }, + }) + + console.log("Users with posts:", JSON.stringify(users, null, 2)) + }) + .catch((error) => console.log("Error:", error)) +``` + +Run your application: + +```terminal +npx tsx index.ts +``` + +## Next steps + +Now that you have TypeORM connected to Prisma Postgres, you can: + +- **Learn more about TypeORM** - Check out the [TypeORM documentation](https://typeorm.io/docs/) for comprehensive guides + +## More info + +- [TypeORM documentation](https://typeorm.io) +- [Prisma Postgres documentation](/postgres) +- [TypeORM PostgreSQL driver documentation](https://typeorm.io/docs/drivers/postgres/) diff --git a/content/100-getting-started/03-prisma-postgres/100-quickstart/50-prisma-orm.mdx b/content/100-getting-started/03-prisma-postgres/100-quickstart/50-prisma-orm.mdx new file mode 100644 index 0000000000..d774affd78 --- /dev/null +++ b/content/100-getting-started/03-prisma-postgres/100-quickstart/50-prisma-orm.mdx @@ -0,0 +1,301 @@ +--- +title: 'Use Prisma Postgres with Prisma ORM' +sidebar_label: 'Prisma ORM' +metaTitle: 'Quickstart: Prisma ORM with Prisma Postgres (5 min)' +metaDescription: 'Create a new TypeScript project from scratch by connecting Prisma ORM to Prisma Postgres and generating a Prisma Client for database access.' +sidebar_custom_props: { badge: '5 min' } +--- + +import Prerequisites from '../../_components/_prerequisites.mdx' +import CreateProject from '../../_components/_create-project.mdx' +import ExploreData from '../../_components/_explore-data.mdx' +import NextSteps from '../../_components/_next-steps.mdx' + +[Prisma Postgres](/postgres) is a fully managed PostgreSQL database that scales to zero and integrates smoothly with both Prisma ORM and Prisma Studio. In this guide, you will learn how to set up a new TypeScript project from scratch, connect it to Prisma Postgres using Prisma ORM, and generate a Prisma Client for easy, type-safe access to your database. + +## Prerequisites + + + +## 1. Create a Prisma Postgres database + +Follow these steps to create your Prisma Postgres database: + +1. Log in to [Prisma Data Platform](https://console.prisma.io) and open the Console. +2. In a workspace of your choice, click the **New project** button. +3. Type a name for your project in the **Name** field, e.g. `hello-ppg`. +4. In the **Prisma Postgres** section, click the **Get started** button. +5. In the **Region** dropdown, select the region that's closest to your current location, e.g. US East (N. Virginia). +6. Click the **Create project** button. + +At this point, you'll be redirected to the Database page where you will need to wait for a few seconds while the status of your database changes from **PROVISIONING** to **CONNECTED**. + +Once the green **CONNECTED** label appears, your database is ready to use! + +## 2. Get your direct connection string + +To connect to Prisma Postgres via direct TCP, you need to: + +1. Open your project in the Prisma Console. +2. Navigate to your active Prisma Postgres instance. +3. Click the **API Keys** tab in the project's sidenav. +4. Click the **Create API key** button. +5. In the popup, provide a **Name** for the API key and click **Create**. +6. Copy the connection string starting with `postgres://`, this is your direct connection string. + +## 3. Create a new project + + + +## 4. Install required dependencies + +Install the packages needed for this quickstart: + +```terminal +npm install prisma @types/node --save-dev +npm install @prisma/client @prisma/adapter-pg dotenv +``` + +Here's what each package does: + +- **`prisma`** - The Prisma CLI for running commands like `prisma init`, `prisma migrate`, and `prisma generate` +- **`@prisma/client`** - The Prisma Client library for querying your database +- **`@prisma/adapter-pg`** - The [`node-postgres` driver adapter](/orm/overview/databases/postgresql#using-the-node-postgres-driver) that connects Prisma Client to your database +- **`dotenv`** - Loads environment variables from your `.env` file + +## 5. Configure ESM support + +Update `tsconfig.json` for ESM compatibility: + +```json file=tsconfig.json +{ + "compilerOptions": { + "module": "ESNext", + "moduleResolution": "node", + "target": "ES2023", + "strict": true, + "esModuleInterop": true, + "ignoreDeprecations": "6.0" + } +} +``` + +Update `package.json` to enable ESM: + +```json file=package.json +{ + // add-start + "type": "module", + // add-end +} +``` + +## 6. Initialize Prisma ORM + +You can now invoke the Prisma CLI by prefixing it with `npx`: + +```terminal +npx prisma +``` + +Next, set up your Prisma ORM project by creating your [Prisma Schema](/orm/prisma-schema) file with the following command: + +```terminal +npx prisma init --output ../generated/prisma +``` + +This command does a few things: + +- Creates a `prisma/` directory with a `schema.prisma` file containing your database connection and schema models +- Creates a `.env` file in the root directory for environment variables +- Generates the Prisma Client in the `generated/prisma/` directory +- Creates a `prisma.config.ts` file for Prisma configuration + +Add your Prisma Postgres direct connection string to the `.env` file: + +```env file=.env +DATABASE_URL="postgres://your-connection-string" +``` + +The generated `prisma.config.ts` file looks like this: + +```typescript file=prisma.config.ts +import { defineConfig, env } from 'prisma/config' + +export default defineConfig({ + schema: 'prisma/schema.prisma', + migrations: { + path: 'prisma/migrations', + }, + datasource: { + url: env('DATABASE_URL'), + }, +}) +``` + +Add `dotenv` to `prisma.config.ts` so that Prisma can load environment variables from your `.env` file: + +```typescript file=prisma.config.ts +// add-start +import 'dotenv/config' +// add-end +import { defineConfig, env } from 'prisma/config' + +export default defineConfig({ + schema: 'prisma/schema.prisma', + migrations: { + path: 'prisma/migrations', + }, + datasource: { + url: env('DATABASE_URL'), + }, +}) +``` + +The generated schema uses [the ESM-first `prisma-client` generator](/orm/prisma-schema/overview/generators#prisma-client) with a custom output path: + +```prisma file=prisma/schema.prisma +generator client { + provider = "prisma-client" + output = "../generated/prisma" +} + +datasource db { + provider = "postgresql" +} +``` + +## 7. Define your data model + +Open `prisma/schema.prisma` and add the following models: + +```prisma file=prisma/schema.prisma +generator client { + provider = "prisma-client" + output = "../generated/prisma" +} + +datasource db { + provider = "postgresql" +} + +//add-start +model User { + id Int @id @default(autoincrement()) + email String @unique + name String? + posts Post[] +} + +model Post { + id Int @id @default(autoincrement()) + title String + content String? + published Boolean @default(false) + author User @relation(fields: [authorId], references: [id]) + authorId Int +} +//add-end +``` + +## 8. Create and apply your first migration + +Create your first migration to set up the database tables: + +```terminal +npx prisma migrate dev --name init +``` + +This command creates the database tables based on your schema. + +Now run the following command to generate the Prisma Client: + +```terminal +npx prisma generate +``` + +## 9. Instantiate Prisma Client + +Now that you have all the dependencies installed, you can instantiate Prisma Client. You need to pass an instance of Prisma ORM's driver adapter to the `PrismaClient` constructor: + +```typescript file=lib/prisma.ts +import "dotenv/config"; +import { PrismaPg } from '@prisma/adapter-pg' +import { PrismaClient } from '../generated/prisma/client' + +const connectionString = `${process.env.DATABASE_URL}` + +const adapter = new PrismaPg({ connectionString }) +const prisma = new PrismaClient({ adapter }) + +export { prisma } +``` + +## 10. Write your first query + +Create a `script.ts` file to test your setup: + +```typescript file=script.ts +import { prisma } from './lib/prisma' + +async function main() { + // Create a new user with a post + const user = await prisma.user.create({ + data: { + name: 'Alice', + email: 'alice@prisma.io', + posts: { + create: { + title: 'Hello World', + content: 'This is my first post!', + published: true, + }, + }, + }, + include: { + posts: true, + }, + }) + console.log('Created user:', user) + + // Fetch all users with their posts + const allUsers = await prisma.user.findMany({ + include: { + posts: true, + }, + }) + console.log('All users:', JSON.stringify(allUsers, null, 2)) +} + +main() + .then(async () => { + await prisma.$disconnect() + }) + .catch(async (e) => { + console.error(e) + await prisma.$disconnect() + process.exit(1) + }) +``` + +Run the script: + +```terminal +npx tsx script.ts +``` + +You should see the created user and all users printed to the console! + +## 11. Explore your data with Prisma Studio + + + +## Next steps + + + +## More info + +- [Prisma Postgres documentation](/postgres) +- [Prisma Config reference](/orm/reference/prisma-config-reference) +- [Database connection management](/orm/prisma-client/setup-and-configuration/databases-connections) diff --git a/content/100-getting-started/03-prisma-postgres/110-import-from-existing-database-postgresql.mdx b/content/100-getting-started/03-prisma-postgres/110-import-from-existing-database-postgresql.mdx index 310401625f..1464590f14 100644 --- a/content/100-getting-started/03-prisma-postgres/110-import-from-existing-database-postgresql.mdx +++ b/content/100-getting-started/03-prisma-postgres/110-import-from-existing-database-postgresql.mdx @@ -1,13 +1,11 @@ --- -title: 'Import data from an existing database' -sidebar_label: 'Import from existing database' +title: 'Import data from an existing PostgreSQL database' +sidebar_label: 'PostgreSQL' metaTitle: 'Import from existing Postgres database into Prisma Postgres' -metaDescription: 'Learn how to import data from an existing database into Prisma Postgres.' +metaDescription: 'Learn how to import data from an existing PostgreSQL database into Prisma Postgres.' tocDepth: 3 toc: true search: true -dbSwitcher: [ "mysql", "postgresql"] -slugSwitch: /getting-started/prisma-postgres/import-from-existing-database- --- This guide provides step-by-step instructions for importing data from an existing PostgreSQL database into Prisma Postgres. @@ -18,7 +16,7 @@ You can accomplish this migration in three steps: 1. Export your existing data via `pg_dump`. 1. Import the previously exported data into Prisma Postgres via `pg_restore`. -In the third step, you will be using a [direct connection](/postgres/database/direct-connections) to securely connect to your Prisma Postgres database during to run `pg_restore`. +In the third step, you will be using a [direct connection](/postgres/database/direct-connections) to securely connect to your Prisma Postgres database to run `pg_restore`. ## Prerequisites @@ -27,6 +25,12 @@ In the third step, you will be using a [direct connection](/postgres/database/di - Node.js 18+ installed - PostgreSQL CLI Tools (`pg_dump`, `pg_restore`) for creating and restoring backups +:::info[Make sure your PostgreSQL tools match the Prisma Postgres version] + +Prisma Postgres runs PostgreSQL 17. Your `pg_dump` and `pg_restore` tools need to be version 17 to ensure compatibility. You can check your version by running `pg_dump --version` or `pg_restore --version`. + +::: + ## 1. Create a new Prisma Postgres database Follow these steps to create a new Prisma Postgres database: @@ -38,7 +42,15 @@ Follow these steps to create a new Prisma Postgres database: 1. In the **Region** dropdown, select the region that's closest to your current location, e.g. **US East (N. Virginia)**. 1. Click the **Create project** button. -With your Prisma Postgres instance being created, you can move to the next step. +Once your database is provisioned, obtain your direct connection string: + +1. Navigate to your active Prisma Postgres instance. +1. Click the **API Keys** tab in the project's sidenav. +1. Click the **Create API key** button. +1. In the popup, provide a **Name** for the API key and click **Create**. +1. Copy the connection string starting with `postgres://`, this is your direct connection string. + +Save the connection string, you'll need it in step 3. ## 2. Export data from your existing database @@ -100,57 +112,43 @@ Running this command will create a backup file named `db_dump.bak` which you wil ## 3. Import data into Prisma Postgres -In this section, you'll use a [TCP Tunnel](/postgres/database/direct-connections#tcp-tunnel) in order to connect to your Prisma Postgres instance and import data via `pg_restore`. +In this section, you'll use your [direct connection string](/postgres/database/direct-connections) to connect to your Prisma Postgres instance and import data via `pg_restore`. -### 3.1. Connecting to the Prisma Postgres Database with `@prisma/ppg-tunnel` +Your direct connection string from step 1 should look like this: -Open a new terminal and set the environment variable for your Prisma Postgres database connection URL. - -```bash -export DATABASE_URL="prisma+postgres://accelerate.prisma-data.net/?api_key=eyJhbGciOiJIUzI..." -``` - -Run the tunnel: -```bash -npx @prisma/ppg-tunnel --host 127.0.0.1 --port 5432 +```no-copy +postgres://USER:PASSWORD@db.prisma.io:5432/?sslmode=require ``` -You should see output similar to: +Use the backup file from **Step 2** to restore data into your Prisma Postgres database with `pg_restore` by running this command (replace `__USER__`, `__PASSWORD__` with the values from your direct connection string): -```cmd -Prisma Postgres auth proxy listening on 127.0.0.1:52604 🚀 - -Your connection is authenticated using your Prisma Postgres API key. -... - -============================== -hostname: 127.0.0.1 -port: 52604 -username: -password: -============================== +```bash +pg_restore \ + -h db.prisma.io \ + -p 5432 \ + -U __USER__ \ + -d postgres \ + -v \ + ./db_dump.bak \ +&& echo "-complete-" ``` +When prompted, enter the `__PASSWORD__` from your direct connection string. -:::note -Keep this tunnel process running to maintain the connection! -::: - -### 3.2. Restoring the Backup with `pg_restore` +:::tip -Use the backup file from **Step 2** to restore data into Prisma Postgres database with `pg_restore` by running this command: +You can also use the full connection string format: ```bash -PGSSLMODE=disable \ pg_restore \ - -h 127.0.0.1 \ - -p 5432 \ + -d "postgres://USER:PASSWORD@db.prisma.io:5432/postgres?sslmode=require" \ -v \ - -d postgres \ ./db_dump.bak \ && echo "-complete-" ``` +::: + Once the command completes execution, you will have successfully imported the data from your existing PostgreSQL database into Prisma Postgres 🎉 To validate that the import worked, you can use [Prisma Studio](/postgres/integrations/viewing-data#viewing-and-editing-data-in-prisma-studio). Either open it in the [Platform Console](https://console.prisma.io) by clicking the **Studio** tab in the left-hand sidenav in your project or run this command to launch Prisma Studio locally: @@ -163,63 +161,35 @@ npx prisma studio ### Scenario A: You are already using Prisma ORM -If you already using Prisma ORM, the only things you need to do are: - -- add the Prisma Accelerate extension to your project -- update the database connection URL and re-generate Prisma Client - -#### 4.A.1. Add the Prisma Accelerate extension - -Th Prisma Accelerate extension is [required](/postgres/introduction/overview#using-the-client-extension-for-prisma-accelerate-required) when using Prisma Postgres. If you are not currently using Prisma Accelerate with Prisma ORM, go through the following steps to make Prisma ORM work with Prisma Postgres. - -First, install the `@prisma/extension-accelerate` package in your project: - -```terminal -npm install @prisma/extension-accelerate -``` - -Then, add the extension to your Prisma Client instance: +If you're already using Prisma ORM, you need to update your database connection URL to point to your new Prisma Postgres instance. -```ts -import { withAccelerate } from '@prisma/extension-accelerate' +Update the `DATABASE_URL` in your `.env` file to match your Prisma Postgres direct connection string from step 1: -const prisma = new PrismaClient().$extends(withAccelerate()) +```bash file=.env +DATABASE_URL="postgres://USER:PASSWORD@db.prisma.io:5432/?sslmode=require" ``` -#### 4.A.2. Update the database connection URL +Then, re-generate Prisma Client so that the updated environment variable takes effect: -The database connection URL is configured via the `url` of the `datasource` block in your `schema.prisma` file. Most commonly, it is set via an environment variable called `DATABASE_URL`: - -```prisma file=schema.prisma -datasource db { - provider = "postgresql" - url = env("DATABASE_URL") -} +```terminal +npx prisma generate ``` -The next steps assumes that you're a `.env` file to set the `DATABASE_URL` environment variable (if that's not the case, you can set the environment variable in your preferred way). - -Open `.env` and update the value for the `DATABASE_URL` environment variable to match your Prisma Postgres connection URL, looking similar to this: - -```bash -DATABASE_URL="prisma+postgres://accelerate.prisma-data.net/?api_key=__API_KEY__" -``` +Once this is done, you can run your application and it should work as before. -As a last step, you need to re-generate Prisma Client for so that the updated environment variables takes effect and your queries go to Prisma Postgres going forward: +:::tip -``` -npx prisma generate --no-engine -``` +For a complete guide on setting up Prisma ORM with Prisma Postgres from scratch, including driver adapter configuration and best practices, see the [Prisma ORM with Prisma Postgres quickstart](/getting-started/prisma-orm/quickstart/prisma-postgres). -Once this is done, you can run your application and it should work as before. +::: ### Scenario B: You are not yet using Prisma ORM If you are not yet using Prisma ORM, you'll need to go through the following steps to use Prisma Postgres from your application: -1. Install the Prisma CLI in your project +1. Install the Prisma CLI and other required dependencies in your project 1. Introspect the database to generate a Prisma schema 1. Generate Prisma Client 1. Update the queries in your application to use Prisma ORM -You can find the detailed step-by-step instructions for this process in this guide: [Add Prisma ORM to an existing project](/getting-started/setup-prisma/add-to-existing-project/relational-databases-typescript-postgresql). \ No newline at end of file +You can find the detailed step-by-step instructions for this process in this guide: [Add Prisma ORM to an existing project](/getting-started/prisma-orm/add-to-existing-project/prisma-postgres). \ No newline at end of file diff --git a/content/100-getting-started/03-prisma-postgres/115-import-from-existing-database-mysql.mdx b/content/100-getting-started/03-prisma-postgres/115-import-from-existing-database-mysql.mdx index 795c4c8634..0d009ba206 100644 --- a/content/100-getting-started/03-prisma-postgres/115-import-from-existing-database-mysql.mdx +++ b/content/100-getting-started/03-prisma-postgres/115-import-from-existing-database-mysql.mdx @@ -1,13 +1,11 @@ --- title: 'Import data from an existing MySQL database' -sidebar_label: 'Import from existing database' +sidebar_label: 'MySQL' metaTitle: 'Import from existing MySQL database into Prisma Postgres' metaDescription: 'Learn how to import data from an existing MySQL database into Prisma Postgres.' tocDepth: 3 toc: true search: true -dbSwitcher: ["mysql", "postgresql"] -slugSwitch: /getting-started/prisma-postgres/import-from-existing-database- --- This guide provides step-by-step instructions for importing data from an existing MySQL database into Prisma Postgres. @@ -26,6 +24,12 @@ You can accomplish this migration in four steps: - Node.js 18+ installed. - [pgloader](https://pgloader.io/) installed. +:::info[Make sure your PostgreSQL tools match the Prisma Postgres version] + +Prisma Postgres runs PostgreSQL 17. Your `pgloader` and any other PostgreSQL tools you use need to be compatible with PostgreSQL 17. + +::: + We recommend attempting this migration in a separate git development branch. ## 1. Create a new Prisma Postgres database @@ -49,16 +53,18 @@ Once your database was provisioned, find your direct Prisma Postgres connection Save the connection string, you'll need it in the next step. -## 2. Connect directly to a Prisma Postgres instance +## 2. Prepare your direct connection string -In this step, you'll use a [direct connection](/postgres/database/direct-connections) to connect to your Prisma Postgres instance. +In this step, you'll use the [direct connection string](/postgres/database/direct-connections) you obtained in step 1 to connect to your Prisma Postgres instance. -You'll need the Prisma Postgres connection URL from [step 1](/getting-started/prisma-postgres/import-from-existing-database-mysql#1-create-a-new-prisma-postgres-database): +Your direct connection string should look like this: ```no-copy -prisma+postgres://accelerate.prisma-data.net/?api_key=ey... +postgres://USER:PASSWORD@db.prisma.io:5432/?sslmode=require ``` +You'll use this connection string in the next step when configuring pgloader. + ## 3. Migrate your MySQL data to Prisma Postgres using pgloader @@ -148,10 +154,10 @@ After migrating your data, you need to set up your Prisma project to work with P Initialize Prisma in your project by running `npx prisma init` in your project directory. This creates a `prisma` folder with a `schema.prisma` file and `.env` file (if not already present). -In the generated `.env` file, update `DATABASE_URL` to match your Prisma Postgres connection string that you received in [step 1](/getting-started/prisma-postgres/import-from-existing-database-mysql#1-create-a-new-prisma-postgres-database): +In the generated `.env` file, update `DATABASE_URL` to match your Prisma Postgres direct connection string that you received in [step 1](/getting-started/prisma-postgres/import-from-existing-database-mysql#1-create-a-new-prisma-postgres-database): ```terminal file=.env no-copy -DATABASE_URL="prisma+postgres://accelerate.prisma-data.net/?api_key=__API_KEY__" +DATABASE_URL="postgres://USER:PASSWORD@db.prisma.io:5432/?sslmode=require" ``` [Introspect](/orm/prisma-schema/introspection) your newly migrated database by running: @@ -167,7 +173,7 @@ Congratulations! You've successfully migrated your MySQL database to Prisma Post :::note -For a comprehensive guide on getting started with Prisma and Prisma Postgres, see [start from scratch with Prisma and Prisma Postgres](/getting-started/setup-prisma/start-from-scratch/relational-databases-typescript-prismaPostgres). +For a comprehensive guide on getting started with Prisma and Prisma Postgres, see [start from scratch with Prisma and Prisma Postgres](/getting-started/prisma-orm/quickstart/prisma-postgres). ::: @@ -187,10 +193,10 @@ datasource db { } ``` -In the generated `.env` file, update `DATABASE_URL` to match your new Prisma Postgres connection string that you received in [step 1](/getting-started/prisma-postgres/import-from-existing-database-mysql#1-create-a-new-prisma-postgres-database): +In the generated `.env` file, update `DATABASE_URL` to match your Prisma Postgres direct connection string that you received in [step 1](/getting-started/prisma-postgres/import-from-existing-database-mysql#1-create-a-new-prisma-postgres-database): ```terminal file=.env no-copy -DATABASE_URL="prisma+postgres://accelerate.prisma-data.net/?api_key=__API_KEY__" +DATABASE_URL="postgres://USER:PASSWORD@db.prisma.io:5432/?sslmode=require" ``` Introspect your newly migrated Prisma Postgres database and generate Prisma Client: diff --git a/content/100-getting-started/03-prisma-postgres/120-upgrade-from-early-access.mdx b/content/100-getting-started/03-prisma-postgres/120-upgrade-from-early-access.mdx deleted file mode 100644 index a7ef91194e..0000000000 --- a/content/100-getting-started/03-prisma-postgres/120-upgrade-from-early-access.mdx +++ /dev/null @@ -1,257 +0,0 @@ ---- -title: 'Upgrade from Early Access' -metaTitle: 'Upgrade Prisma Postgres from Early Access' -metaDescription: 'Upgrade your Prisma Postgres database from Early Access database to General Availability database.' -staticLink: true -tocDepth: 3 -toc: true ---- - -This guide shows you how to migrate your Prisma Postgres Early Access (EA) database to the now official Prisma Postgres General Availability (GA) database. Prisma Postgres Early Access was introduced to allow early adopters to test Prisma’s new managed PostgreSQL service. As we move to GA, it's crucial to safely migrate data from your EA database to the new GA database. - -Prisma will _not_ automatically migrate your data to ensure its integrity. Instead, this process must be done manually. You can accomplish this in three main steps: - -1. Back up your EA database via `pg_dump`. -2. Create a new GA database. -3. Import your backup into the GA database via `pg_restore`. - -We will be using the [`@prisma/ppg-tunnel`](https://www.npmjs.com/package/@prisma/ppg-tunnel) package to securely connect to both databases. This tool sets up a secure proxy tunnel, eliminating the need for manual credential handling. - -You can learn more about **Prisma Postgres** on [this page](/postgres). - -## Prerequisites - -Before you begin, make sure you have: - -- **Node.js** installed (version 16 or higher). -- **PostgreSQL CLI Tools** (`pg_dump`, `pg_restore`) for creating and restoring backups. -- A **Database connection string** for your Prisma Postgres database. - -To create and restore backups, ensure you have the PostgreSQL command-line tools installed. Run the following commands based on your operating system: - - - - - -```terminal -brew install postgresql@16 -which pg_dump -which pg_restore -``` - - - - - -```terminal -# Download from the official PostgreSQL website: -# https://www.postgresql.org/download/windows/ -# During installation, select "Command Line Tools". -# Then verify with: - -where pg_dump -where pg_restore -``` - - - - -```terminal -sudo apt-get update -sudo apt-get install postgresql-client-16 -which pg_dump -which pg_restore -``` - - - - - -:::tip -If you installed PostgreSQL but still see a “command not found” error for pg_dump or pg_restore, ensure your installation directory is in your system’s PATH environment variable. -::: - -:::note -Please make sure that you are installing Postgresql version 16. Other versions may cause errors during the backup and restore process. -::: - -## Option A: Interactive approach - -This approach is recommended if you prefer a guided, one-command solution. In this mode, the `@prisma/ppg-tunnel` CLI: - -1. Prompts you for your Early Access (EA) database API key (or `DATABASE_URL`). -2. Uses `pg_dump` behind the scenes to back up your EA database to a file in the current directory. -3. Prompts you for your new GA database URL or API Key. -4. Uses `pg_restore` to import the backup file into your GA database. - -Interactive mode does not accept any CLI arguments or read API keys from the environment. You must provide them interactively. - -### Steps - -1. Open a terminal and run: -```bash -npx @prisma/ppg-tunnel migrate-from-ea -``` - -2. When prompted, paste your Early Access database key or connection string. The CLI will create a `.bak` file in the current directory. - -3. When prompted again, paste your GA database key or connection string. The CLI will automatically restore the .bak file into the new GA database. - -4. Once complete, connect with your favorite Database IDE to verify your data in the GA database. - -## Option B: Manual backup-and-restore approach - -If you prefer or need finer control over the migration process (or to pass environment variables directly), follow these manual steps. -The migration involves three main parts: - -1. Back up your EA database via `pg_dump`. -2. Create a new GA database. -3. Import your backup into the GA database via `pg_restore`. - -We will still be using the `@prisma/ppg-tunnel` package to securely connect to both databases. - -## 1. Back up the EA database - -### 1.1. Connecting to the EA database directly with `@prisma/ppg-tunnel` - -In your terminal, run `npx @prisma/ppg-tunnel` to establish a secure tunnel to your Early Access database. - -If you already have a `.env` file in your current directory with `DATABASE_URL` set, the tunnel CLI will automatically pick it up—no need to manually export it. However, if you haven't set up a `.env` file, you'll need to set the `DATABASE_URL` environment variable explicitly. - -To set environment variable (with your actual EA database URL): -```bash -export DATABASE_URL="prisma+postgres://accelerate.prisma-data.net/?api_key=eyJhbGciOiJIUzI..." -``` -:::note -If you explicitly set `DATABASE_URL` in your terminal, that value will take precedence over the one in your `.env` file. -::: - -Run the tunnel: -```bash -npx @prisma/ppg-tunnel --host 127.0.0.1 --port 5432 -``` - -You should see output similar to: - -```cmd -Prisma Postgres auth proxy listening on 127.0.0.1:5432 🚀 - -Your connection is authenticated using your Prisma Postgres API key. -... - -============================== -hostname: 127.0.0.1 -port: 5432 -username: -password: -============================== -``` - -:::note -Please note that the port you will see in your output will be a randomly assigned port which may be different from the one mentioned here. -Also, Keep this terminal window open so the tunnel remains active! If you close it, the tunnel disconnects. -::: - -Copy the port number from the terminal output, you’ll need it in the next step for the `pg_dump` command. - -### 1.2. Creating the Backup with `pg_dump` - -With the tunnel running, you can now dump the EA database by running the following command: -```bash -PGSSLMODE=disable \ -pg_dump \ - -h 127.0.0.1 \ - -p 5432 \ - -Fc \ - -v \ - -d postgres \ - -f ./mydatabase.bak \ -&& echo "-complete-" -``` - -`PGSSLMODE=disable` indicates SSL is not required locally because the tunnel already encrypts the connection. - -``` -`-h` is the host (127.0.0.1) -`-p` is the port, which should match the one from the tunnel output. -`-Fc` uses the custom format for backups, recommended for pg_restore. -`-d` postgres is the default database name used in Prisma Postgres. -`-f` ./mydatabase.bak specifies the backup file name and location. -`-v` runs pg_dump in verbose mode. -``` - -This should create your backup file named `mydatabase.bak` in the current directory. We will use this backup file for importing in next steps. - -## 2. Create a new GA database - -Next, create your GA (General Availability) database: -1. Visit [console.prisma.io](https://console.prisma.io) and sign in (or create an account). -2. Create a Prisma Postgres database in the region of your choice. -3. Copy the Database URL for later use. - -Prisma Postgres GA uses PostgreSQL 17, so you’ll be restoring your EA backup into this new environment. - -## 3. Import the backup into the GA database - -### 3.1. Connecting to the GA Database with `@prisma/ppg-tunnel` - -Open a new terminal (or stop the previous tunnel) and connect to your GA database: - -Set environment variables for the new GA database: -```bash -export DATABASE_URL="prisma+postgres://accelerate.prisma-data.net/?api_key=eyJhbGciOiJIUzI..." -``` - -Run the tunnel: -```bash -npx @prisma/ppg-tunnel --host 127.0.0.1 --port 5432 -``` - -You should see output similar to: - -```cmd -Prisma Postgres auth proxy listening on 127.0.0.1:52604 🚀 - -Your connection is authenticated using your Prisma Postgres API key. -... - -============================== -hostname: 127.0.0.1 -port: 52604 -username: -password: -============================== -``` - - -:::note -Again, keep this tunnel process running to maintain the connection! -::: - -### 3.2. Restoring the Backup with `pg_restore` - -Use the backup file from **Step 1** to restore data into your GA database with `pg_restore` by running this command: - -```bash -PGSSLMODE=disable \ -pg_restore \ - -h 127.0.0.1 \ - -p 5432 \ - -v \ - -d postgres \ - ./mydatabase.bak \ -&& echo "-complete-" -``` - -Also, in this case the database name is `postgres`. You can replace it with your desired database name. It does not matter what you name your database as you will be able to use Prisma Postgres as usual. -The backup file name (mydatabase.bak in our example) should match the one you created in Step 1. - -This command restores the backup into the GA database. If successful, you should see `-complete-` in the terminal. - -## Next steps - -Connect with your favorite Database IDE or Prisma Client to confirm all tables, rows, and schemas match your old EA environment. - -Congratulations! You have successfully migrated your Prisma Postgres Early Access database to Prisma Postgres GA. If you encounter any issues, please reach out to our [support team](https://www.prisma.io/support). - - diff --git a/content/100-getting-started/_components/_create-prisma-client.mdx b/content/100-getting-started/_components/_create-prisma-client.mdx new file mode 100644 index 0000000000..9ac8c11aa5 --- /dev/null +++ b/content/100-getting-started/_components/_create-prisma-client.mdx @@ -0,0 +1,181 @@ +import CodeBlock from '@theme/CodeBlock'; + +Create a `lib/` directory and a `prisma.ts` file inside it to set up your Prisma Client instance: + +{props.database === 'prisma-postgres' && ( +<> + +{`import { PrismaClient } from '../generated/prisma' +import { withAccelerate } from '@prisma/extension-accelerate' + +const globalForPrisma = globalThis as unknown as { + prisma: PrismaClient | undefined +} + +export const prisma = globalForPrisma.prisma ?? + new PrismaClient().$extends(withAccelerate()) + +if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prisma`} + + +)} + +{props.database === 'postgresql' && ( +<> + +{`import { PrismaClient } from '../generated/prisma' +import { PrismaPg } from '@prisma/adapter-pg' + +const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL }) + +const globalForPrisma = globalThis as unknown as { + prisma: PrismaClient | undefined +} + +export const prisma = globalForPrisma.prisma ?? new PrismaClient({ adapter }) + +if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prisma`} + + +)} + +{props.database === 'mysql' && ( +<> + +{`import { PrismaClient } from '../generated/prisma' +import { PrismaMariaDb } from '@prisma/adapter-mariadb' + +const adapter = new PrismaMariaDb({ + host: process.env.DB_HOST || 'localhost', + port: parseInt(process.env.DB_PORT || '3306'), + connectionLimit: 5 +}) + +const globalForPrisma = globalThis as unknown as { + prisma: PrismaClient | undefined +} + +export const prisma = globalForPrisma.prisma ?? new PrismaClient({ adapter }) + +if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prisma`} + + +)} + +{props.database === 'sqlite' && ( +<> + +{`import { PrismaClient } from '../generated/prisma' +import { PrismaBetterSQLite3 } from '@prisma/adapter-better-sqlite3' + +const adapter = new PrismaBetterSQLite3({ url: process.env.DATABASE_URL }) + +const globalForPrisma = globalThis as unknown as { + prisma: PrismaClient | undefined +} + +export const prisma = globalForPrisma.prisma ?? new PrismaClient({ adapter }) + +if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prisma`} + + +)} + +{props.database === 'sqlserver' && ( +<> + +{`import { PrismaClient } from '../generated/prisma' +import { PrismaMSSQL } from '@prisma/adapter-mssql' + +const sqlConfig = { + user: process.env.DB_USER, + password: process.env.DB_PASSWORD, + database: process.env.DB_NAME, + server: process.env.DB_HOST, + pool: { + max: 10, + min: 0, + idleTimeoutMillis: 30000 + }, + options: { + encrypt: true, + trustServerCertificate: false + } +} + +const adapter = new PrismaMSSQL(sqlConfig) + +const globalForPrisma = globalThis as unknown as { + prisma: PrismaClient | undefined +} + +export const prisma = globalForPrisma.prisma ?? new PrismaClient({ adapter }) + +if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prisma`} + + +)} + +{props.database === 'planetscale' && ( +<> + +{`import { PrismaClient } from '../generated/prisma' +import { PrismaPlanetScale } from '@prisma/adapter-planetscale' +import { fetch as undiciFetch } from 'undici' + +const adapter = new PrismaPlanetScale({ + url: process.env.DATABASE_URL, + fetch: undiciFetch +}) + +const globalForPrisma = globalThis as unknown as { + prisma: PrismaClient | undefined +} + +export const prisma = globalForPrisma.prisma ?? new PrismaClient({ adapter }) + +if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prisma`} + + +)} + +{props.database === 'cockroachdb' && ( +<> + +{`import { PrismaClient } from '../generated/prisma' +import { PrismaPg } from '@prisma/adapter-pg' + +const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL }) + +const globalForPrisma = globalThis as unknown as { + prisma: PrismaClient | undefined +} + +export const prisma = globalForPrisma.prisma ?? new PrismaClient({ adapter }) + +if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prisma`} + + +)} + +{props.database === 'mongodb' && ( +<> + +{`import { PrismaClient } from '../generated/prisma' + +const globalForPrisma = globalThis as unknown as { + prisma: PrismaClient | undefined +} + +export const prisma = globalForPrisma.prisma ?? new PrismaClient() + +if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prisma`} + + +)} + +:::note + +The global pattern prevents multiple instances of Prisma Client in development due to hot reloading. + +::: diff --git a/content/100-getting-started/_components/_create-project.mdx b/content/100-getting-started/_components/_create-project.mdx new file mode 100644 index 0000000000..d25affdf0d --- /dev/null +++ b/content/100-getting-started/_components/_create-project.mdx @@ -0,0 +1,14 @@ +Create a project directory and navigate into it: + +```terminal +mkdir hello-prisma +cd hello-prisma +``` + +Initialize a TypeScript project: + +```terminal +npm init -y +npm install typescript tsx @types/node --save-dev +npx tsc --init +``` diff --git a/content/100-getting-started/_components/_explore-data.mdx b/content/100-getting-started/_components/_explore-data.mdx new file mode 100644 index 0000000000..8e1ecd0362 --- /dev/null +++ b/content/100-getting-started/_components/_explore-data.mdx @@ -0,0 +1,7 @@ +Prisma Studio is a visual editor for your database. Launch it with: + +```terminal +npx prisma studio --config ./prisma.config.ts +``` + +This opens a web interface where you can view and edit your data. diff --git a/content/100-getting-started/_components/_install-prisma-client.mdx b/content/100-getting-started/_components/_install-prisma-client.mdx new file mode 100644 index 0000000000..3947901919 --- /dev/null +++ b/content/100-getting-started/_components/_install-prisma-client.mdx @@ -0,0 +1,83 @@ +import CodeBlock from '@theme/CodeBlock'; + +## {props.stepNumber ? `${props.stepNumber}. ` : ''}Install and generate Prisma Client + +To get started with Prisma Client, first install the required packages: + +{props.database === 'prisma-postgres' && ( +<> + +{`npm install @prisma/client @prisma/extension-accelerate`} + + +)} + +{props.database === 'postgresql' && ( +<> + +{`npm install @prisma/client @prisma/adapter-pg`} + + +)} + +{props.database === 'mysql' && ( +<> + +{`npm install @prisma/client @prisma/adapter-mariadb`} + + +)} + +{props.database === 'sqlite' && ( +<> + +{`npm install @prisma/client @prisma/adapter-better-sqlite3`} + + +)} + +{props.database === 'sqlserver' && ( +<> + +{`npm install @prisma/client @prisma/adapter-mssql`} + + +)} + +{props.database === 'planetscale' && ( +<> + +{`npm install @prisma/client @prisma/adapter-planetscale`} + + +)} + +{props.database === 'cockroachdb' && ( +<> + +{`npm install @prisma/client @prisma/adapter-pg`} + + +)} + +{props.database === 'mongodb' && ( +<> + +{`npm install @prisma/client`} + + +)} + +Then, run `prisma generate` which reads your Prisma schema and generates the Prisma Client: + +```terminal +npx prisma generate +``` + +:::note Good to know + +When you run `prisma generate`, you are creating code (TypeScript types, methods, queries) tailored to your Prisma schema. Whenever you make changes to your Prisma schema, you need to update the Prisma Client by running `prisma generate`. + +Whenever you update your Prisma schema, you will also need to update your database schema using either `prisma migrate dev` or `prisma db push`. These commands will also run `prisma generate` automatically. + +::: diff --git a/content/100-getting-started/_components/_next-steps.mdx b/content/100-getting-started/_components/_next-steps.mdx new file mode 100644 index 0000000000..e28f626f50 --- /dev/null +++ b/content/100-getting-started/_components/_next-steps.mdx @@ -0,0 +1,7 @@ +You've successfully set up Prisma ORM. Here's what you can explore next: + +- **Learn more about Prisma Client**: Explore the [Prisma Client API](/orm/prisma-client) for advanced querying, filtering, and relations +- **Database migrations**: Learn about [Prisma Migrate](/orm/prisma-migrate) for evolving your database schema +- **Performance optimization**: Discover [query optimization techniques](/orm/prisma-client/queries/query-optimization-performance) +- **Build a full application**: Check out our [framework guides](/guides) to integrate Prisma ORM with Next.js, Express, and more +- **Join the community**: Connect with other developers on [Discord](https://pris.ly/discord) diff --git a/content/100-getting-started/_components/_prerequisites.mdx b/content/100-getting-started/_components/_prerequisites.mdx new file mode 100644 index 0000000000..eacf532107 --- /dev/null +++ b/content/100-getting-started/_components/_prerequisites.mdx @@ -0,0 +1,11 @@ +You need: + +- [Node.js](https://nodejs.org/en/) v20.19+, v22.12+, or v24.0+ installed on your machine +- Basic knowledge of JavaScript or TypeScript + +{props.database && ( +
    +
  • A {props.database} database accessible
  • + {props.connectionDetails &&
  • {props.connectionDetails}
  • } +
+)} diff --git a/content/100-getting-started/_components/_prisma-init.mdx b/content/100-getting-started/_components/_prisma-init.mdx new file mode 100644 index 0000000000..64c5c0a227 --- /dev/null +++ b/content/100-getting-started/_components/_prisma-init.mdx @@ -0,0 +1,67 @@ +import CodeBlock from '@theme/CodeBlock'; + +## {props.stepNumber ? `${props.stepNumber}. ` : ''}Initialize Prisma + +You can now invoke the Prisma CLI by prefixing it with `npx`: + +```terminal +npx prisma +``` + +Next, set up your Prisma ORM project by creating your [Prisma Schema](/orm/prisma-schema) file with the following command: + +{props.database === 'prisma-postgres' ? ( +<> + +{`npx prisma init --db --output ../generated/prisma`} + + +:::info + +You'll need to answer a few questions while setting up your Prisma Postgres database. Select the region closest to your location and a memorable name for your database. + +::: + +This command creates: + +- A `prisma/` directory with a `schema.prisma` file containing your database connection and schema models +- A new Prisma Postgres database (when using `--db` flag) +- A `.env` file in the root directory for environment variables +- A `generated/prisma/` directory for the generated Prisma Client + +The generated schema uses the modern `prisma-client` generator with a custom output path: + + +{`generator client { + provider = "prisma-client" + output = "../generated/prisma" +} + +datasource db { + provider = "postgresql" +}`} + + +) : ( +<> + +{`npx prisma init --datasource-provider ${props.datasource?.toLowerCase() || props.database} --output ../generated/prisma`} + + +This command does a few things: + +- Creates a new directory called `prisma` that contains a file called `schema.prisma`, which contains the Prisma Schema with your database connection variable and schema models. +- Sets the `datasource` to {props.datasource || props.database} and the output to a custom location, respectively. +- Creates the [`.env` file](/orm/more/development-environment/environment-variables) in the root directory of the project, which is used for defining environment variables (such as your database connection) + +Note that the default schema created by `prisma init` uses PostgreSQL as the `provider`. If you didn't specify a provider with the `datasource-provider` option, you need to edit the `datasource` block to use the {(props.datasource || props.database)?.toLowerCase()} provider instead: + + +{`datasource db { + //edit-next-line + provider = "${(props.datasource || props.database)?.toLowerCase()}" + url = env("DATABASE_URL") +}`} + + +)} diff --git a/content/100-getting-started/index.mdx b/content/100-getting-started/index.mdx index b03a3857a7..2cea2e85d4 100644 --- a/content/100-getting-started/index.mdx +++ b/content/100-getting-started/index.mdx @@ -3,10 +3,8 @@ title: 'Get Started' metaTitle: 'Get started with Prisma' metaDescription: 'Build data-driven applications with ease using Prisma ORM, add connection pooling or global caching with Prisma Accelerate.' hide_title: true -tocDepth: 1 sidebar_position: 0 sidebar_class_name: firstTitle -pagination_next: 'getting-started/quickstart-sqlite' --- import { @@ -18,198 +16,166 @@ import { Grid, LinkCard, List, + Plus, + Plug, SignalStream, PrismaPostgres, SquareLogo, + QuickstartLinkCard } from '@site/src/components/GettingStarted'; +Getting started - - -Get started - -Welcome 👋 - -Explore our products that make it easy to build and scale data-driven applications: - -[**Prisma ORM**](/orm/overview/introduction/what-is-prisma) is a next-generation Node.js and TypeScript ORM that unlocks a new level of developer experience when working with databases thanks to its intuitive data model, automated migrations, type-safety & auto-completion. - -[**Prisma Postgres**](/postgres) is a managed PostgreSQL service that gives you an _always-on_ database with _pay-as-you-go_ pricing. + -[**Prisma Optimize**](/optimize/) helps you analyze queries, generate insights, and provides recommendations to make your database queries faster. - -[**Prisma Accelerate**](/accelerate) is a global database cache with scalable connection pooling to make your queries fast. + - +[**Prisma ORM**](/orm/overview/introduction/what-is-prisma) is an open-source ORM that provides fast, type-safe access to Postgres, MySQL, SQLite, and more databases, and runs smoothly across Node.js, Bun, and Deno. +```terminal +npx prisma init --db +``` + + -## Prisma ORM + -Add Prisma ORM to your application in a few minutes to start modeling your data, run schema migrations and query your database. +[**Prisma Postgres**](/postgres) is a fully managed PostgreSQL database that scales to zero, integrates with Prisma ORM and Prisma Studio, and includes a generous free tier. -### The easiest way to get started with Prisma +```terminal +npx create-db +``` + + + -_Explore all Prisma products at once._ +
- + -### Explore quickly with a SQLite database +The fastest way to set up **Prisma ORM** with a ready-to-use **Prisma Postgres** database. -_These options don't require you to have your own database running._ + - - - - +
+
-### Choose an option to get started with your own database +### Already have your own database? -_Select one of these options if you want to connect Prisma ORM to your own database._ +The fastest way to set Prisma ORM up with a ready-to-use database. - - -

- Set up Prisma ORM from scratch with your favorite database and - learn basic workflows like data modeling, querying, and migrations. -

- + - + - -
- -

- Get started with Prisma ORM and your existing database by - introspecting your database schema and learn how to query your database. -

- + + +
+
+ +### Using Prisma Postgres with other tools? + +You can also use Prisma Postgres with different tools or ORMs. Pick one of the options below to see how to connect. + + + {/* */} + + +
+
+ +### Add Prisma to your favorite framework? + +Working with **Next.js**, **Remix**, or another framework? You can easily add Prisma to your setup in just a few steps and start using it right away. + + - -
-
- -## Prisma Accelerate - -Make your database queries faster by scaling your database connections and caching database results at the edge with Prisma Accelerate. - - - - - -
- - -## Prisma Optimize - -Make your database queries faster by using the insights and recommendations generated by Prisma Optimize. - - - - - + + + + + diff --git a/content/200-orm/025-getting-started/10-quickstart.mdx b/content/200-orm/025-getting-started/10-quickstart.mdx new file mode 100644 index 0000000000..ef7fcb6d6a --- /dev/null +++ b/content/200-orm/025-getting-started/10-quickstart.mdx @@ -0,0 +1,11 @@ +--- +title: 'Quickstart with Prisma ORM' +sidebar_label: 'Quickstart' +metaTitle: 'Quickstart with Prisma ORM' +metaDescription: "This section provides a quick step-by-step guide to get started with Prisma ORM." +hide_table_of_contents: true +--- + +import { Redirect } from '@docusaurus/router'; + + \ No newline at end of file diff --git a/content/200-orm/025-getting-started/20-add-to-existing-project.mdx b/content/200-orm/025-getting-started/20-add-to-existing-project.mdx new file mode 100644 index 0000000000..7e89ef8e26 --- /dev/null +++ b/content/200-orm/025-getting-started/20-add-to-existing-project.mdx @@ -0,0 +1,11 @@ +--- +title: 'Add Prisma ORM to an existing project' +sidebar_label: 'Add to existing project' +metaTitle: 'Add Prisma ORM to an existing project' +metaDescription: "This section provides a step-by-step guide to add Prisma ORM to an existing project." +hide_table_of_contents: true +--- + +import { Redirect } from '@docusaurus/router'; + + \ No newline at end of file diff --git a/content/200-orm/025-getting-started/_category_.json b/content/200-orm/025-getting-started/_category_.json new file mode 100644 index 0000000000..8f75e9e8ae --- /dev/null +++ b/content/200-orm/025-getting-started/_category_.json @@ -0,0 +1,5 @@ +{ + "label": "Getting started", + "collapsible": false, + "collapsed": false +} diff --git a/content/200-orm/025-getting-started/index.mdx b/content/200-orm/025-getting-started/index.mdx new file mode 100644 index 0000000000..87b4690c63 --- /dev/null +++ b/content/200-orm/025-getting-started/index.mdx @@ -0,0 +1,13 @@ +--- +title: 'Getting started with Prisma ORM' +sidebar_label: 'Getting started' +metaTitle: 'Getting started with Prisma ORM' +metaDescription: "This section provides a quick step-by-step guide to get started with Prisma ORM." +hide_table_of_contents: true +--- + +## In this section + +You can either start with a fresh Prisma ORM project with a database of your choice or add Prisma ORM to an existing project. + + diff --git a/content/200-orm/050-overview/500-databases/600-mongodb.mdx b/content/200-orm/050-overview/500-databases/600-mongodb.mdx index b927e6d98d..0e519206ff 100644 --- a/content/200-orm/050-overview/500-databases/600-mongodb.mdx +++ b/content/200-orm/050-overview/500-databases/600-mongodb.mdx @@ -14,7 +14,7 @@ This guide discusses the concepts behind using Prisma ORM and MongoDB, explains -To connect Prisma ORM with MongoDB, refer to our [Getting Started documentation](/getting-started/setup-prisma/start-from-scratch/mongodb-typescript-mongodb). +To connect Prisma ORM with MongoDB, refer to our [Getting Started documentation](/getting-started/prisma-orm/quickstart/mongodb). @@ -360,8 +360,8 @@ console.log(findNullOrMissing) The fastest way to start using MongoDB with Prisma ORM is to refer to our Getting Started documentation: -- [Start from scratch](/getting-started/setup-prisma/start-from-scratch/mongodb-typescript-mongodb) -- [Add to existing project](/getting-started/setup-prisma/add-to-existing-project/mongodb-typescript-mongodb) +- [Start from scratch](/getting-started/prisma-orm/quickstart/mongodb) +- [Add to existing project](/getting-started/prisma-orm/add-to-existing-project/mongodb) These tutorials will take you through the process of connecting to MongoDB, pushing schema changes, and using Prisma Client. diff --git a/content/200-orm/050-overview/500-databases/840-cockroachdb.mdx b/content/200-orm/050-overview/500-databases/840-cockroachdb.mdx index 3d3bdf18b9..ca6984dd09 100644 --- a/content/200-orm/050-overview/500-databases/840-cockroachdb.mdx +++ b/content/200-orm/050-overview/500-databases/840-cockroachdb.mdx @@ -213,8 +213,8 @@ model Device { The fastest way to start using CockroachDB with Prisma ORM is to refer to our Getting Started documentation: -- [Start from scratch](/getting-started/setup-prisma/start-from-scratch/relational-databases-typescript-cockroachdb) -- [Add to existing project](/getting-started/setup-prisma/add-to-existing-project/relational-databases-typescript-cockroachdb) +- [Start from scratch](/getting-started/prisma-orm/quickstart/cockroachdb) +- [Add to existing project](/getting-started/prisma-orm/add-to-existing-project/cockroachdb) These tutorials will take you through the process of connecting to CockroachDB, migrating your schema, and using Prisma Client. diff --git a/content/200-orm/050-overview/500-databases/850-planetscale.mdx b/content/200-orm/050-overview/500-databases/850-planetscale.mdx index f000a80a33..d325915dc1 100644 --- a/content/200-orm/050-overview/500-databases/850-planetscale.mdx +++ b/content/200-orm/050-overview/500-databases/850-planetscale.mdx @@ -49,7 +49,7 @@ PlanetScale's branching model and design for scalability means that there are al ## How to use branches and deploy requests -When connecting to PlanetScale with Prisma ORM, you will need to use the correct connection string for your branch. The connection URL for a given database branch can be found from your PlanetScale account by going to the overview page for the branch and selecting the 'Connect' dropdown. In the 'Passwords' section, generate a new password and select 'Prisma' from the dropdown to get the Prisma format for the connection URL. See Prisma ORM's [Getting Started guide](/getting-started/setup-prisma/start-from-scratch/relational-databases/connect-your-database-typescript-planetscale) for more details of how to connect to a PlanetScale database. +When connecting to PlanetScale with Prisma ORM, you will need to use the correct connection string for your branch. The connection URL for a given database branch can be found from your PlanetScale account by going to the overview page for the branch and selecting the 'Connect' dropdown. In the 'Passwords' section, generate a new password and select 'Prisma' from the dropdown to get the Prisma format for the connection URL. See Prisma ORM's [Getting started guide](/getting-started/prisma-orm/quickstart/planetscale) for more details of how to connect to a PlanetScale database. Every PlanetScale database is created with a branch called `main`, which is initially a development branch that you can use to test schema changes on. Once you are happy with the changes you make there, you can [promote it](https://planetscale.com/docs/concepts/branching#promote-a-branch-to-production) to become a production branch. Note that you can only push new changes to a development branch, so further changes will need to be created on a separate development branch and then later deployed to production using a [deploy request](https://planetscale.com/docs/concepts/branching#promote-a-branch-to-production). @@ -257,7 +257,7 @@ model User { } ``` -For a more detailed example, see the [Getting Started guide for PlanetScale](/getting-started/setup-prisma/add-to-existing-project/relational-databases/introspection-typescript-planetscale). +For a more detailed example, see the [Getting started guide for PlanetScale](/getting-started/prisma-orm/add-to-existing-project/planetscale). ## How to define shard keys in your Prisma schema (Preview) @@ -353,8 +353,8 @@ You can then use Prisma Client as you normally would with full type-safety. Pris The fastest way to start using PlanetScale with Prisma ORM is to refer to our Getting Started documentation: -- [Start from scratch](/getting-started/setup-prisma/start-from-scratch/relational-databases-typescript-planetscale) -- [Add to existing project](/getting-started/setup-prisma/add-to-existing-project/relational-databases-typescript-planetscale) +- [Start from scratch](/getting-started/prisma-orm/quickstart/planetscale) +- [Add to existing project](/getting-started/prisma-orm/add-to-existing-project/planetscale) These tutorials will take you through the process of connecting to PlanetScale, pushing schema changes, and using Prisma Client. diff --git a/content/200-orm/100-prisma-schema/50-introspection.mdx b/content/200-orm/100-prisma-schema/50-introspection.mdx index 8d64093664..5d5394d3f8 100644 --- a/content/200-orm/100-prisma-schema/50-introspection.mdx +++ b/content/200-orm/100-prisma-schema/50-introspection.mdx @@ -7,7 +7,7 @@ metaDescription: 'Learn how you can introspect your database to generate a data You can introspect your database using the Prisma CLI in order to generate the [data model](/orm/prisma-schema/data-model) in your [Prisma schema](/orm/prisma-schema). The data model is needed to [generate Prisma Client](/orm/prisma-client/setup-and-configuration/custom-model-and-field-names). -Introspection is often used to generate an _initial_ version of the data model when [adding Prisma ORM to an existing project](/getting-started/setup-prisma/add-to-existing-project/relational-databases-typescript-postgresql). +Introspection is often used to generate an _initial_ version of the data model when [adding Prisma ORM to an existing project](/getting-started/prisma-orm/add-to-existing-project/postgresql). However, it can also be [used _repeatedly_ in an application](#introspection-with-an-existing-schema). This is most commonly the case when you're _not_ using [Prisma Migrate](/orm/prisma-migrate) but perform schema migrations using plain SQL or another migration tool. In that case, you also need to re-introspect your database and subsequently re-generate Prisma Client to reflect the schema changes in your [Prisma Client API](/orm/prisma-client). diff --git a/content/200-orm/200-prisma-client/000-setup-and-configuration/005-introduction.mdx b/content/200-orm/200-prisma-client/000-setup-and-configuration/005-introduction.mdx index 7c8f5d58f0..99beeecfb0 100644 --- a/content/200-orm/200-prisma-client/000-setup-and-configuration/005-introduction.mdx +++ b/content/200-orm/200-prisma-client/000-setup-and-configuration/005-introduction.mdx @@ -11,9 +11,9 @@ import { -Prisma Client is an auto-generated and type-safe query builder that's _tailored_ to your data. The easiest way to get started with Prisma Client is by following the **[Quickstart](/getting-started/quickstart-sqlite)**. +Prisma Client is an auto-generated and type-safe query builder that's _tailored_ to your data. The easiest way to get started with Prisma Client is by following the **[Quickstart](/getting-started/prisma-orm/quickstart/sqlite)**. - + Quickstart (5 min) @@ -22,16 +22,15 @@ The setup instructions [below](#set-up) provide a high-level overview of the ste Set up a new project from scratch
-
Add Prisma to an existing project diff --git a/content/200-orm/200-prisma-client/500-deployment/101-traditional/200-deploy-to-heroku.mdx b/content/200-orm/200-prisma-client/500-deployment/101-traditional/200-deploy-to-heroku.mdx index d45ffd8200..96c86441f6 100644 --- a/content/200-orm/200-prisma-client/500-deployment/101-traditional/200-deploy-to-heroku.mdx +++ b/content/200-orm/200-prisma-client/500-deployment/101-traditional/200-deploy-to-heroku.mdx @@ -53,7 +53,7 @@ For brevity, the guide does not cover how migrations are created with `prisma mi You will use Heroku's [release phase](https://devcenter.heroku.com/articles/release-phase) to run the `prisma migrate deploy` command so that the migrations are applied before the application starts. -To learn more about how migrations are created with Prisma Migrate, check out the [start from scratch guide](/getting-started/setup-prisma/start-from-scratch/relational-databases-typescript-postgresql) +To learn more about how migrations are created with Prisma Migrate, check out the [start from scratch guide](/getting-started/prisma-orm/quickstart/postgresql) ## 1. Download the example and install dependencies diff --git a/content/200-orm/200-prisma-client/500-deployment/101-traditional/250-deploy-to-koyeb.mdx b/content/200-orm/200-prisma-client/500-deployment/101-traditional/250-deploy-to-koyeb.mdx index e6f3e9ac75..ae17d01eb4 100644 --- a/content/200-orm/200-prisma-client/500-deployment/101-traditional/250-deploy-to-koyeb.mdx +++ b/content/200-orm/200-prisma-client/500-deployment/101-traditional/250-deploy-to-koyeb.mdx @@ -48,7 +48,7 @@ For brevity, the guide does not cover how migrations are created with `prisma mi You will use Koyeb's [build step](https://www.koyeb.com/docs/build-and-deploy/build-from-git#the-buildpack-build-process) to run the `prisma migrate deploy` command so that the migrations are applied before the application starts. -To learn more about how migrations are created with Prisma Migrate, check out the [start from scratch guide](/getting-started/setup-prisma/start-from-scratch/relational-databases-typescript-postgresql) +To learn more about how migrations are created with Prisma Migrate, check out the [start from scratch guide](/getting-started/prisma-orm/quickstart/postgresql) ## 1. Download the example and install dependencies diff --git a/content/200-orm/300-prisma-migrate/300-workflows/20-prototyping-your-schema.mdx b/content/200-orm/300-prisma-migrate/300-workflows/20-prototyping-your-schema.mdx index 374f39309a..e019dc32a6 100644 --- a/content/200-orm/300-prisma-migrate/300-workflows/20-prototyping-your-schema.mdx +++ b/content/200-orm/300-prisma-migrate/300-workflows/20-prototyping-your-schema.mdx @@ -19,7 +19,7 @@ The Prisma CLI has a dedicated command for prototyping schemas: [`db push`](/orm > **Notes**: > > - `db push` does not interact with or rely on migrations. The migrations table `_prisma_migrations` will not be created or updated, and no migration files will be generated. -> - When working with PlanetScale, we recommend that you use `db push` instead of `migrate`. For details refer to our Getting Started documentation, either [Start from scratch](/getting-started/setup-prisma/start-from-scratch/relational-databases-typescript-planetscale) or [Add to existing project](/getting-started/setup-prisma/add-to-existing-project/relational-databases-typescript-planetscale) depending on your situation. +> - When working with PlanetScale, we recommend that you use `db push` instead of `migrate`. For details refer to our Getting started documentation, either [Start from scratch guide](/getting-started/prisma-orm/quickstart/planetscale) or [Add to existing project guide](/getting-started/prisma-orm/add-to-existing-project/planetscale) depending on your situation. ## Choosing `db push` or Prisma Migrate diff --git a/content/200-orm/500-reference/380-connection-urls.mdx b/content/200-orm/500-reference/380-connection-urls.mdx index 68fd631f08..a8bf1b54a9 100644 --- a/content/200-orm/500-reference/380-connection-urls.mdx +++ b/content/200-orm/500-reference/380-connection-urls.mdx @@ -15,7 +15,7 @@ The connection URL is provided via the `url` field of a `datasource` block in yo - **Port**: The port on which your database server is running - **Database name**: The name of the database you want to use -Make sure you have this information at hand when getting started with Prisma ORM. If you don't have a database server running yet, you can either use a local SQLite database file (see the [Quickstart](/getting-started/quickstart-sqlite)) or [setup a free PostgreSQL database with Prisma Postgres](/postgres). +Make sure you have this information at hand when getting started with Prisma ORM. If you don't have a database server running yet, you can either use a local SQLite database file (see the [Quickstart](/getting-started/prisma-orm/quickstart/sqlite)) or [setup a free PostgreSQL database with Prisma Postgres](/postgres). ## Format diff --git a/content/200-orm/800-more/100-under-the-hood/index.mdx b/content/200-orm/800-more/100-under-the-hood/index.mdx index 8bf96648f7..c90ba799c4 100644 --- a/content/200-orm/800-more/100-under-the-hood/index.mdx +++ b/content/200-orm/800-more/100-under-the-hood/index.mdx @@ -11,7 +11,7 @@ This page gives an overview of the Prisma ORM internals and how it works "under Note that **this page does not contain any practical information that is relevant for _using_ Prisma ORM**. It rather aims at providing a _mental model_ for what the Prisma ORM toolkit _actually_ is and how the different tools that are available to developers are structured. -If you're new to using Prisma ORM, be sure to check out the [Quickstart](/getting-started/quickstart-sqlite) and [Introduction](/orm/overview/introduction/what-is-prisma) pages first. +If you're new to using Prisma ORM, be sure to check out the [Quickstart](/getting-started/prisma-orm/quickstart/sqlite) and [Introduction](/orm/overview/introduction/what-is-prisma) pages first.
diff --git a/content/200-orm/800-more/300-upgrade-guides/200-upgrading-versions/600-upgrading-to-prisma-5/index.mdx b/content/200-orm/800-more/300-upgrade-guides/200-upgrading-versions/600-upgrading-to-prisma-5/index.mdx index 637b4c4e4b..10454a4417 100644 --- a/content/200-orm/800-more/300-upgrade-guides/200-upgrading-versions/600-upgrading-to-prisma-5/index.mdx +++ b/content/200-orm/800-more/300-upgrade-guides/200-upgrading-versions/600-upgrading-to-prisma-5/index.mdx @@ -138,14 +138,14 @@ While `OR`, `in`, and `notIn` operators are affected, `AND` and `NOT` are not af With Prisma ORM version 5.0.0, we require the `cockroachdb` provider to be used when connecting to CockroachDB databases. Previously, we had accepted `postgresql` as well, but we are removing that option. -If you were using [native database types](/orm/reference/prisma-schema-reference#postgresql) and also the `postgresql` provider, you will need to [baseline your database](/getting-started/setup-prisma/add-to-existing-project/relational-databases/baseline-your-database-typescript-cockroachdb) from PostgreSQL to CockroachDB: +If you were using [native database types](/orm/reference/prisma-schema-reference#postgresql) and also the `postgresql` provider, you will need to [baseline your database](/getting-started/prisma-orm/add-to-existing-project/cockroachdb#5-baseline-your-database) from PostgreSQL to CockroachDB: 1. Backup your existing `schema.prisma` file (e.g. use version control) 2. Update your `datasource` provider from `postgresql` to `cockroachdb` 3. Use `npx prisma db pull --force` in order to overwrite your existing Prisma schema (including native types) to those that are on your CockroachDB instance. 4. Review changes between your Prisma schema backup and the new Prisma schema generated by `db pull`. You can either use the new schema as is, or update it to include your preferred spacing, comments, etc. -5. Delete your existing migrations. We will be [performing a baseline](/getting-started/setup-prisma/add-to-existing-project/relational-databases/baseline-your-database-typescript-cockroachdb) in order to make your local setup agree with your existing CockroachDB instance. -6. Perform the [baselining steps](/getting-started/setup-prisma/add-to-existing-project/relational-databases/baseline-your-database-typescript-cockroachdb). After these steps, you'll have migrated successfully from the `postgresql` provider to the `cockroachdb` provider! +5. Delete your existing migrations. We will be [performing a baseline](/getting-started/prisma-orm/add-to-existing-project/cockroachdb#5-baseline-your-database) in order to make your local setup agree with your existing CockroachDB instance. +6. Perform the [baselining steps](/getting-started/prisma-orm/add-to-existing-project/cockroachdb#5-baseline-your-database). After these steps, you'll have migrated successfully from the `postgresql` provider to the `cockroachdb` provider! ### Removal of `runtime/index.js` from generated client diff --git a/content/250-postgres/100-introduction/220-npx-create-db.mdx b/content/250-postgres/100-introduction/220-npx-create-db.mdx index 7b5c93b971..c0fa7a3289 100644 --- a/content/250-postgres/100-introduction/220-npx-create-db.mdx +++ b/content/250-postgres/100-introduction/220-npx-create-db.mdx @@ -123,7 +123,7 @@ Once you have the output, take the **Prisma ORM-optimized connection string** (` DATABASE_URL="prisma+postgres://accelerate.prisma-data.net/?api_key=..." ``` -You can now follow the [Prisma Postgres quickstart guide](/getting-started/quickstart-prismaPostgres#3-set-database-connection-url) to connect your Prisma project to this database. +You can now follow the [Prisma Postgres quickstart guide](/getting-started/prisma-orm/quickstart/prisma-postgres) to connect your Prisma project to this database. If you're using other tools or libraries, use the **standard PostgreSQL connection string** (`postgresql://...`) with any PostgreSQL-compatible client, such as `psql`, `pgAdmin`, `node-postgres`, or an ORM of your choice. Detailed instructions are available in the guide for [connecting via direct PostgreSQL connection string](/postgres/database/direct-connections). diff --git a/content/250-postgres/300-database/650-direct-connections.mdx b/content/250-postgres/300-database/650-direct-connections.mdx index d020e30f5b..b63e7f4687 100644 --- a/content/250-postgres/300-database/650-direct-connections.mdx +++ b/content/250-postgres/300-database/650-direct-connections.mdx @@ -74,7 +74,13 @@ While direct connections are in Early Access, the following timeouts apply: User permissions are limited to read, write and schema changes. It is not possible to create separate databases, manage users and roles, or perform other administrative actions. -## TCP tunnel +## TCP tunnel (deprecated) + +:::warning + +The TCP tunnel feature has been **deprecated** in favor of [direct connections](#how-to-connect-to-prisma-postgres-via-direct-tcp). Please use direct connections for all new integrations and migrate existing implementations. + +::: Prisma Postgres can be accessed securely via a TCP tunnel using the [`@prisma/ppg-tunnel`](https://www.npmjs.com/package/@prisma/ppg-tunnel) package, an authentication proxy designed for local database workflows. This package establishes a secure connection to Prisma Postgres through a local TCP server, enabling secure access while automatically handling traffic routing and authentication. diff --git a/content/250-postgres/350-integrations/400-mcp-server.mdx b/content/250-postgres/350-integrations/400-mcp-server.mdx index e1c263571f..42caa36c6f 100644 --- a/content/250-postgres/350-integrations/400-mcp-server.mdx +++ b/content/250-postgres/350-integrations/400-mcp-server.mdx @@ -56,11 +56,6 @@ The remote Prisma MCP server follows the standard JSON-based configuration for M } ``` - -:::tip -If you want to try it the remote MCP server and explore it's capabilities, we recommend [Cloudflare's AI Playground](https://playground.ai.cloudflare.com/) for that. Add the `https://mcp.prisma.io/mcp` URL into the text field with the **Enter MCP server URL** placeholder, click **Connect**, and then authenticate with the [Prisma Console](https://console.prisma.io) in the popup window. Once connected, you can send prompts to the Playground and see what MCP tools the LLM chooses based on your prompts. -::: - ### Sample prompts - "Show me a list of all the databases in my account." diff --git a/content/250-postgres/400-query-optimization/100-setup.mdx b/content/250-postgres/400-query-optimization/100-setup.mdx index c4737247b1..a7a19dd194 100644 --- a/content/250-postgres/400-query-optimization/100-setup.mdx +++ b/content/250-postgres/400-query-optimization/100-setup.mdx @@ -12,7 +12,7 @@ Before you begin with Prisma Optimize for Prisma Postgres, ensure you have the f - A [Prisma Data Platform account](https://console.prisma.io/optimize?utm_source=docs&utm_medium=optimize-page). - A project using [Prisma Client](/orm/prisma-client) version `5.0.0` or higher (we recommend using the latest version). -- A [Prisma Postgres database](/postgres/introduction/getting-started). +- A [Prisma Postgres database](/postgres/getting-started). :::note diff --git a/content/250-postgres/50-getting-started/100-quickstart.mdx b/content/250-postgres/50-getting-started/100-quickstart.mdx new file mode 100644 index 0000000000..5fea9ceeeb --- /dev/null +++ b/content/250-postgres/50-getting-started/100-quickstart.mdx @@ -0,0 +1,11 @@ +--- +title: 'Quickstart with Prisma ORM' +sidebar_label: 'Quickstart' +metaTitle: 'Quickstart: Prisma ORM with Prisma Postgres (5 min)' +metaDescription: 'Create a new TypeScript project from scratch by connecting Prisma ORM to Prisma Postgres and generating a Prisma Client for database access.' +hide_table_of_contents: true +--- + +import { Redirect } from '@docusaurus/router'; + + \ No newline at end of file diff --git a/content/250-postgres/50-getting-started/200-import-from-existing-database.mdx b/content/250-postgres/50-getting-started/200-import-from-existing-database.mdx new file mode 100644 index 0000000000..e72aa23fdf --- /dev/null +++ b/content/250-postgres/50-getting-started/200-import-from-existing-database.mdx @@ -0,0 +1,11 @@ +--- +title: 'Import data from an existing PostgreSQL database' +sidebar_label: 'Import from existing database' +metaTitle: 'Import from existing Postgres database into Prisma Postgres' +metaDescription: 'Learn how to import data from an existing PostgreSQL database into Prisma Postgres.' +hide_table_of_contents: true +--- + +import { Redirect } from '@docusaurus/router'; + + \ No newline at end of file diff --git a/content/250-postgres/50-getting-started/_category_.json b/content/250-postgres/50-getting-started/_category_.json new file mode 100644 index 0000000000..8f75e9e8ae --- /dev/null +++ b/content/250-postgres/50-getting-started/_category_.json @@ -0,0 +1,5 @@ +{ + "label": "Getting started", + "collapsible": false, + "collapsed": false +} diff --git a/content/250-postgres/100-introduction/200-getting-started.mdx b/content/250-postgres/50-getting-started/index.mdx similarity index 86% rename from content/250-postgres/100-introduction/200-getting-started.mdx rename to content/250-postgres/50-getting-started/index.mdx index ac3fc926fd..9a63cf6c87 100644 --- a/content/250-postgres/100-introduction/200-getting-started.mdx +++ b/content/250-postgres/50-getting-started/index.mdx @@ -8,7 +8,6 @@ toc: true ## Quickstart - To **bootstrap a new Prisma ORM project with a Prisma Postgres database**, run the following command in your terminal: ```terminal @@ -31,7 +30,7 @@ You can learn more about `npx create-db` in [the dedicated documentation](/postg The easiest ways to get started with Prisma Postgres is by following these guides: -- [**Start from scratch**](/getting-started/quickstart-prismaPostgres) +- [**Start from scratch**](/getting-started/prisma-postgres/quickstart/prisma-orm) - [**Import data from an existing database**](/getting-started/prisma-postgres/import-from-existing-database-postgresql) If you are looking to explore Prisma Postgres in a fullstack project, check out these resources: @@ -39,16 +38,6 @@ If you are looking to explore Prisma Postgres in a fullstack project, check out - [**Build a fullstack app with Next.js 15**](/guides/nextjs) - [**Next.js 15 example app**](https://github.com/prisma/nextjs-prisma-postgres-demo) (including authentication) -:::note - -When you are using Prisma Postgres, you don't need to include the query engine in the generated Prisma Client code. Make sure to always generate it using the `--no-engine` flag: - -```terminal -prisma generate --no-engine -``` - -::: - ## Connect via any database library / tool You can access Prisma Postgres with any ORM or database tool of your choice via [direct TCP connections](/postgres/database/direct-connections). @@ -67,4 +56,10 @@ Once you have the connection string, you can follow the setup docs for PostgreSQ - [TypeORM](https://typeorm.io/#installation) - [Sequelize](https://sequelize.org/docs/v6/getting-started/) - [MikroORM](https://mikro-orm.io/docs/quick-start) -- [node-postgres](https://node-postgres.com/) \ No newline at end of file +- [node-postgres](https://node-postgres.com/) + +## In this section + +You can either start with a fresh Prisma Postgres project or import data from an existing database to Prisma Postgres. + + diff --git a/content/800-guides/140-use-prisma-in-pnpm-workspaces.mdx b/content/800-guides/140-use-prisma-in-pnpm-workspaces.mdx index 388b68f1c8..634859b3b1 100644 --- a/content/800-guides/140-use-prisma-in-pnpm-workspaces.mdx +++ b/content/800-guides/140-use-prisma-in-pnpm-workspaces.mdx @@ -104,7 +104,7 @@ pnpm add @prisma/extension-accelerate :::info -This guide uses [Prisma Postgres](/postgres/introduction/getting-started). If you plan to use a different database, you can omit the [@prisma/extension-accelerate package](https://www.npmjs.com/package/@prisma/extension-accelerate/). +This guide uses [Prisma Postgres](/postgres/getting-started). If you plan to use a different database, you can omit the [@prisma/extension-accelerate package](https://www.npmjs.com/package/@prisma/extension-accelerate/). ::: @@ -126,7 +126,7 @@ Enter a name for your project and choose a database region. :::info -We're going to be using [Prisma Postgres](/postgres/introduction/getting-started) in this guide. If you're not using a Prisma Postgres database, you won't need to add the `--db` flag. +We're going to be using [Prisma Postgres](/postgres/getting-started) in this guide. If you're not using a Prisma Postgres database, you won't need to add the `--db` flag. ::: @@ -181,7 +181,7 @@ Next, add helper scripts to your `package.json` to simplify Prisma commands: :::info -If you're not using [Prisma Postgres](/postgres/introduction/getting-started) for your database, exclude the `--no-engine` flag from the `db:generate` script. +If you're not using [Prisma Postgres](/postgres/getting-started) for your database, exclude the `--no-engine` flag from the `db:generate` script. ::: @@ -221,7 +221,7 @@ if (process.env.NODE_ENV !== "production") { :::info -If you're not using [Prisma Postgres](/postgres/introduction/getting-started) for your database, exclude the `import { withAccelerate }` line and `.$extends(withAccelerate())` from the line following it. +If you're not using [Prisma Postgres](/postgres/getting-started) for your database, exclude the `import { withAccelerate }` line and `.$extends(withAccelerate())` from the line following it. ::: diff --git a/content/800-guides/230-betterauth-nextjs.mdx b/content/800-guides/230-betterauth-nextjs.mdx index 5a048fb22c..4907a37fa0 100644 --- a/content/800-guides/230-betterauth-nextjs.mdx +++ b/content/800-guides/230-betterauth-nextjs.mdx @@ -1,8 +1,8 @@ --- -title: 'How to use Prisma ORM with Better-Auth and Next.js' -metaTitle: 'How to use Prisma ORM and Prisma Postgres with Better-Auth and Next.js' -description: 'Learn how to use Prisma ORM in a Next.js app with Better-Auth' -sidebar_label: 'Better-Auth (with Next.js)' +title: 'How to use Prisma ORM with Better Auth and Next.js' +metaTitle: 'How to use Prisma ORM and Prisma Postgres with Better Auth and Next.js' +description: 'Learn how to use Prisma ORM in a Next.js app with Better Auth' +sidebar_label: 'Better Auth (with Next.js)' image: '/img/guides/prisma-betterauth-nextjs-cover.png' completion_time: '25 min' community_section: true @@ -10,9 +10,9 @@ community_section: true ## Introduction -[Better-Auth](https://better-auth.com/) is a modern, open-source authentication solution for web applications. It's built with TypeScript, React, and Prisma to provide a simple and extensible auth experience. +[Better Auth](https://better-auth.com/) is a modern, open-source authentication solution for web applications. It's built with TypeScript and provides a simple and extensible auth experience with support for multiple database adapters, including Prisma. -In this guide, you'll wire Better-Auth into a brand-new [Next.js](https://nextjs.org/) app and persist users in a [Prisma Postgres](https://prisma.io/postgres) database. You can find a complete example of this guide on [GitHub](https://github.com/prisma/prisma-examples/tree/latest/orm/betterauth-nextjs). +In this guide, you'll wire Better Auth into a brand-new [Next.js](https://nextjs.org/) app and persist users in a [Prisma Postgres](https://prisma.io/postgres) database. You can find a complete example of this guide on [GitHub](https://github.com/prisma/prisma-examples/tree/latest/orm/betterauth-nextjs). ## Prerequisites @@ -78,15 +78,15 @@ Once installed, initialize Prisma in your project: npx prisma init --db --output ../src/generated/prisma ``` :::info -You'll need to answer a few questions while setting up your Prisma Postgres database. Select the region closest to your location and a memorable name for your database like "My Better-Auth Project" +You'll need to answer a few questions while setting up your Prisma Postgres database. Select the region closest to your location and a memorable name for your database like "My Better Auth Project" ::: This will create: -- A `prisma` directory with a `schema.prisma` file. -- A Prisma Postgres database. -- A `.env` file containing the `DATABASE_URL` at the project root. -- An `output` directory for the generated Prisma Client as `better-auth/generated/prisma`. +- A `prisma` directory with a `schema.prisma` file +- A Prisma Postgres database +- A `.env` file containing the `DATABASE_URL` at the project root +- An `output` directory for the generated Prisma Client as `better-auth/generated/prisma` ### 2.2. Configure the Prisma client generator @@ -98,7 +98,7 @@ npx prisma generate ### 2.3. Set up a global Prisma client -Create a `/lib` directory and a `prisma.ts` file inside it. This file will be used to create and export your Prisma Client instance. +In the `src` directory, create a `lib` folder and a `prisma.ts` file inside it. This file will be used to create and export your Prisma Client instance. ```terminal mkdir -p src/lib @@ -149,19 +149,19 @@ We recommend using a connection pooler (like [Prisma Accelerate](https://www.pri If you choose not to use one, **avoid** instantiating `PrismaClient` globally in long-lived environments. Instead, create and dispose of the client per request to prevent exhausting your database connections. ::: -## 3. Set up Better-Auth +## 3. Set up Better Auth -Now it's time to integrate Better-Auth for authentication. +Now it's time to integrate Better Auth for authentication. -### 3.1. Install and configure Better-Auth +### 3.1. Install and configure Better Auth -First, install the Better-Auth core package: +First, install the Better Auth core package: ```terminal npm install better-auth ``` -Next, generate a secure secret that Better-Auth will use to sign authentication tokens. This ensures your tokens cannot be messed with. +Next, generate a secure secret that Better Auth will use to sign authentication tokens. This ensures your tokens cannot be messed with. ```terminal npx @better-auth/cli@latest secret @@ -170,7 +170,7 @@ npx @better-auth/cli@latest secret Copy the generated secret and add it, along with your application's URL, to your `.env` file: ```dotenv file=.env showLineNumbers -# Better-Auth +# Better Auth //add-start BETTER_AUTH_SECRET=your-generated-secret BETTER_AUTH_URL=http://localhost:3000 @@ -180,13 +180,13 @@ BETTER_AUTH_URL=http://localhost:3000 DATABASE_URL="your-database-url" ``` -Now, create a configuration file for Better-Auth at `src/lib/auth.ts`: +Now, create a configuration file for Better Auth. In the `src/lib` directory, create an `auth.ts` file: ```terminal touch src/lib/auth.ts ``` -In this file, you'll configure Better-Auth to use the Prisma adapter, which allows it to persist user and session data in your database. You will also enable email and password authentication. +In this file, you'll configure Better Auth to use the Prisma adapter, which allows it to persist user and session data in your database. You will also enable email and password authentication. ```ts file=src/lib/auth.ts import { betterAuth } from 'better-auth' @@ -200,7 +200,7 @@ export const auth = betterAuth({ }) ``` -Better-Auth also supports other sign-in methods like social logins (Google, GitHub, etc.), which you can explore in their [documentation](https://www.better-auth.com/docs/authentication/email-password). +Better Auth also supports other sign-in methods like social logins (Google, GitHub, etc.), which you can explore in their [documentation](https://www.better-auth.com/docs/authentication/email-password). ```ts file=src/lib/auth.ts import { betterAuth } from 'better-auth' @@ -240,9 +240,9 @@ export const auth = betterAuth({ ``` ::: -### 3.2. Add Better-Auth models to your schema +### 3.2. Add Better Auth models to your schema -Better-Auth provides a CLI command to automatically add the necessary authentication models (`User`, `Session`, `Account`, and `Verification`) to your `schema.prisma` file. +Better Auth provides a CLI command to automatically add the necessary authentication models (`User`, `Session`, `Account`, and `Verification`) to your `schema.prisma` file. Run the following command: @@ -329,16 +329,16 @@ npx prisma migrate dev --name add-auth-models ## 4. Set up the API routes -Better-Auth needs an API endpoint to handle authentication requests like sign-in, sign-up, and sign-out. You'll create a catch-all API route in Next.js to handle all requests sent to `/api/auth/[...all]`. +Better Auth needs an API endpoint to handle authentication requests like sign-in, sign-up, and sign-out. You'll create a catch-all API route in Next.js to handle all requests sent to `/api/auth/[...all]`. -First, create the necessary directory and file: +In the `src/app/api` directory, create an `auth/[...all]` folder structure and a `route.ts` file inside it: ```terminal mkdir -p "src/app/api/auth/[...all]" touch "src/app/api/auth/[...all]/route.ts" ``` -Add the following code to the newly created `route.ts` file. This code uses a helper from Better-Auth to create Next.js-compatible `GET` and `POST` request handlers. +Add the following code to the newly created `route.ts` file. This code uses a helper from Better Auth to create Next.js-compatible `GET` and `POST` request handlers. ```ts import { auth } from "@/lib/auth"; @@ -347,7 +347,7 @@ import { toNextJsHandler } from "better-auth/next-js"; export const { POST, GET } = toNextJsHandler(auth); ``` -Next, you'll need a client-side utility to interact with these endpoints from your React components. Create a new file `src/lib/auth-client.ts`: +Next, you'll need a client-side utility to interact with these endpoints from your React components. In the `src/lib` directory, create an `auth-client.ts` file: ```terminal touch src/lib/auth-client.ts @@ -363,7 +363,11 @@ export const { signIn, signUp, signOut, useSession } = createAuthClient() ## 5. Set up your pages -Now, let's build the user interface for authentication. Create the pages for signing up, signing in, and a protected dashboard: +Now, let's build the user interface for authentication. In the `src/app` directory, create the following folder structure: + +- `sign-up/page.tsx` +- `sign-in/page.tsx` +- `dashboard/page.tsx` ```terminal mkdir -p src/app/{sign-up,sign-in,dashboard} @@ -410,7 +414,7 @@ export default function SignUpPage() { } ``` -Now, import the `signUp` function from your Better-Auth client and add the `handleSubmit` function. This function is triggered on form submission and calls the `signUp.email` method provided by Better-Auth, passing the user's name, email, and password. +Now, import the `signUp` function from your Better Auth client and add the `handleSubmit` function. This function is triggered on form submission and calls the `signUp.email` method provided by Better Auth, passing the user's name, email, and password. ```tsx file=src/app/sign-up/page.tsx "use client"; @@ -611,7 +615,7 @@ export default function SignInPage() { } ``` -Add the `handleSubmit` function, this time importing and using the `signIn.email` method from Better-Auth. +Add the `handleSubmit` function, this time importing and using the `signIn.email` method from Better Auth. ```tsx file=src/app/sign-in/page.tsx "use client"; @@ -778,7 +782,7 @@ export default function DashboardPage() { } ``` -Import the `useSession` hook from your Better-Auth client. This hook is the key to managing authentication state on the client side. It provides the session data and a pending status. +Import the `useSession` hook from your Better Auth client. This hook is the key to managing authentication state on the client side. It provides the session data and a pending status. ```tsx file=src/app/dashboard/page.tsx "use client"; @@ -816,7 +820,7 @@ export default function DashboardPage() { const router = useRouter(); const { data: session, isPending } = useSession(); - //add-start: redirect if not signed in + //add-start useEffect(() => { if (!isPending && !session?.user) { router.push("/sign-in"); @@ -851,7 +855,7 @@ export default function DashboardPage() { } }, [isPending, session, router]); - //add-start: loading and redirect states + //add-start if (isPending) return

Loading...

; if (!session?.user) @@ -890,7 +894,7 @@ export default function DashboardPage() { if (!session?.user) return

Redirecting...

; - //add-start: destructure user from session + //add-start const { user } = session; //add-end @@ -899,7 +903,7 @@ export default function DashboardPage() {

Dashboard

Welcome, {user.name || "User"}!

Email: {user.email}

- {/* add-start: sign out button */} + {/* add-start */} + +

Already have an account? Sign in here.

+ //add-end + + + +``` + +Now add a script to handle form submission. Import the `authClient` and add an event listener to the form that prevents the default submission behavior, extracts the form data, and calls the Better Auth sign-up method. + +```html file=src/pages/sign-up/index.astro +--- +export const prerender = false; +--- + + + + + + Sign Up + + +
+

Sign Up

+
+ + + + +
+

Already have an account? Sign in here.

+
+ //add-start + + //add-end + + +``` + +Finally, add a server-side check to redirect authenticated users away from this page. If a user is already signed in, they should be redirected to the dashboard instead. + +```html file=src/pages/sign-up/index.astro +--- +export const prerender = false; + +//add-start +if (Astro.locals.user?.id) return Astro.redirect("/dashboard"); +//add-end +--- + + + + + + Sign Up + + +
+

Sign Up

+
+ + + + +
+

Already have an account? Sign in here.

+
+ + + +``` + +### 7.2. Sign in page + +This page allows existing users to authenticate. Start with the basic HTML structure in `src/pages/sign-in/index.astro`. + +```html file=src/pages/sign-in/index.astro +--- +export const prerender = false; +--- + + + + + + Sign In + + +
+

Sign In

+
+ + +``` + +Add a form with input fields for email and password. This form will collect the user's credentials. + +```html file=src/pages/sign-in/index.astro +--- +export const prerender = false; +--- + + + + + + Sign In + + +
+

Sign In

+ //add-start +
+ + + +
+

Don't have an account? Sign up here.

+ //add-end +
+ + +``` + +Now add a script to handle form submission. Import the `authClient` and add an event listener that prevents default submission, extracts the form data, and calls the Better Auth sign-in method. + +```html file=src/pages/sign-in/index.astro +--- +export const prerender = false; +--- + + + + + + Sign In + + +
+

Sign In

+
+ + + +
+

Don't have an account? Sign up here.

+
+ //add-start + + //add-end + + +``` + +Finally, add a server-side check to redirect authenticated users away from this page. If a user is already signed in, they should be redirected to the dashboard instead. + +```html file=src/pages/sign-in/index.astro +--- +export const prerender = false; + +//add-start +if (Astro.locals.user?.id) return Astro.redirect("/dashboard"); +//add-end +--- + + + + + + Sign In + + +
+

Sign In

+
+ + + +
+

Don't have an account? Sign up here.

+
+ + + +``` + +### 7.3. Dashboard page + +This is the protected page for authenticated users. Start with the basic HTML structure in `src/pages/dashboard/index.astro`. + +```html file=src/pages/dashboard/index.astro +--- +export const prerender = false; +--- + + + + + + Dashboard + + +
+

Dashboard

+
+ + +``` + +Add a server-side check to protect this route. If the user is not authenticated, redirect them to the sign-in page. + +```html file=src/pages/dashboard/index.astro +--- +export const prerender = false; + +//add-start +if (!Astro.locals.user?.id) return Astro.redirect("/sign-in"); +//add-end +--- + + + + + + Dashboard + + +
+

Dashboard

+
+ + +``` + +Now display the authenticated user's information. The `Astro.locals.user` object contains the user data that was set by the middleware. + +```html file=src/pages/dashboard/index.astro +--- +export const prerender = false; + +if (!Astro.locals.user?.id) return Astro.redirect("/sign-in"); +--- + + + + + + Dashboard + + +
+

Dashboard

+ //add-next-line +
{JSON.stringify(Astro.locals.user, null, 2)}
+
+ + +``` + +Finally, add a sign-out button. Import the `authClient` and add a button that calls the sign-out method, allowing the user to log out and be redirected to the sign-in page. + +```html file=src/pages/dashboard/index.astro +--- +export const prerender = false; + +if (!Astro.locals.user?.id) return Astro.redirect("/sign-in"); +--- + + + + + + Dashboard + + +
+

Dashboard

+
{JSON.stringify(Astro.locals.user, null, 2)}
+ //add-next-line + +
+ //add-start + + //add-end + + +``` + +### 7.4. Home page + +Finally, update the home page to provide simple navigation. Replace the contents of `src/pages/index.astro` with the following: + +```html file=src/pages/index.astro +--- +export const prerender = false; +--- + + + + + + Better Auth + Astro + Prisma + + +
+

Better Auth + Astro + Prisma

+ { + Astro.locals.user ? ( +
+

Welcome back, {Astro.locals.user.name}!

+ Go to Dashboard +
+ ) : ( + + ) + } +
+ + +``` + +## 8. Test it out + +Your application is now fully configured. + +1. Start the development server to test it: + +```terminal +npm run dev +``` + +2. Navigate to `http://localhost:4321` in your browser. You should see the home page with "Sign Up" and "Sign In" links. + +3. Click on **Sign Up**, create a new account, and you should be redirected to the dashboard. You can then sign out and sign back in. + +4. To view the user data directly in your database, you can use Prisma Studio. + +```terminal +npx prisma studio +``` + +5. This will open a new tab in your browser where you can see the `User`, `Session`, and `Account` tables and their contents. + +:::success + +Congratulations! You now have a fully functional authentication system built with Better Auth, Prisma, and Astro. + +::: + +## Next steps + +- Add support for social login or magic links +- Implement password reset and email verification +- Add user profile and account management pages +- Deploy to Vercel or Netlify and secure your environment variables +- Extend your Prisma schema with custom application models + +## Further reading + +- [Better Auth documentation](https://www.better-auth.com/docs) +- [Prisma documentation](/orm/overview/introduction) +- [Astro documentation](https://astro.build/docs) diff --git a/content/900-ai/prompts/astro.mdx b/content/900-ai/prompts/astro.mdx index 2fb3fe5caa..473c95d336 100644 --- a/content/900-ai/prompts/astro.mdx +++ b/content/900-ai/prompts/astro.mdx @@ -260,3 +260,29 @@ When asked about Prisma + Astro implementation, you MUST: Remember: There are NO EXCEPTIONS to these rules. ```` + +## Running the application + +Get your application running locally in three quick steps: + +**1. Generate the Prisma Client:** + +```terminal +npx prisma generate --no-engine +``` + +**2. View your database in Prisma Studio:** + +```terminal +npm run db:studio +``` + +Prisma Studio opens at `localhost:5555` where you can inspect your `User` table and see the test user stored in your database. + +**3. Start your Next.js development server:** + +```terminal +npm run dev +``` + +Visit `http://localhost:3000` to see your Next.js application live, displaying your first user fetched directly from your Prisma Postgres database! \ No newline at end of file diff --git a/content/900-ai/prompts/nextjs.mdx b/content/900-ai/prompts/nextjs.mdx index 329da64442..a2a01ec1aa 100644 --- a/content/900-ai/prompts/nextjs.mdx +++ b/content/900-ai/prompts/nextjs.mdx @@ -15,6 +15,22 @@ Include this prompt in your AI assistant to guide consistent code generation for - **Zed**: Use `/file` followed by your prompt's path. - **Windsurf**: Use `@Files` and choose your prompt file from the list. +## Video Tutorial + +Watch this step-by-step walkthrough showing this prompt in action: + +
+ +
+ ## Prompt ````md diff --git a/docusaurus.config.ts b/docusaurus.config.ts index 5bc27295e3..6807372575 100644 --- a/docusaurus.config.ts +++ b/docusaurus.config.ts @@ -4,6 +4,7 @@ import { themes as prismThemes } from "prism-react-renderer"; import type { Config, RouteConfig } from "@docusaurus/types"; import type * as Preset from "@docusaurus/preset-classic"; +import type { PluginOptions } from "@signalwire/docusaurus-plugin-llms-txt/public"; const DOCUSAURUS_BASE_URL = process.env.DOCUSAURUS_BASE_URL ?? "/"; @@ -91,6 +92,21 @@ const config: Config = { enableInDevelopment: false, }, ], + [ + "@signalwire/docusaurus-plugin-llms-txt", + { + // Enable with defaults + generate: { + enableMarkdownFiles: true, + enableLlmsFullTxt: false, + }, + include: { + includeBlog: false, + includePages: false, + includeDocs: true, + }, + } satisfies PluginOptions, + ], async function pluginLlmsTxt(context) { return { name: "llms-txt-plugin", @@ -297,7 +313,7 @@ const config: Config = { to: "/postgres/database/prisma-studio", label: "Studio", sub: "Explore and manipulate your data", - icon: "fa-regular fa-table" + icon: "fa-regular fa-table", }, { type: "docSidebar", @@ -305,7 +321,7 @@ const config: Config = { className: "teal", label: "Optimize", sub: "AI-driven query analysis", - icon: "fa-regular fa-magnifying-glass-chart" + icon: "fa-regular fa-magnifying-glass-chart", }, { type: "docSidebar", @@ -313,7 +329,7 @@ const config: Config = { className: "teal", label: "Accelerate", sub: "Make your database global", - icon: "fa-regular fa-bolt" + icon: "fa-regular fa-bolt", }, { type: "docSidebar", @@ -321,7 +337,7 @@ const config: Config = { sidebarId: "aiSidebar", label: "Prisma + AI", sub: "Build faster with Prisma + AI", - icon: "fa-regular fa-robot" + icon: "fa-regular fa-robot", }, ], }, diff --git a/functions/_middleware.ts b/functions/_middleware.ts new file mode 100644 index 0000000000..cfd258bc87 --- /dev/null +++ b/functions/_middleware.ts @@ -0,0 +1,113 @@ +interface Env { + ASSETS: { + fetch: typeof fetch; + }; +} + +const AI_CRAWLER_PATTERNS = [ + 'GPTBot', + 'OAI-SearchBot', + 'ChatGPT-User', + 'ChatGPT-User 2.0', + 'anthropic-ai', + 'OpenAI', + 'ClaudeBot', + 'claude-web', + 'Claude/', + 'Claude-User', + 'anthropic', + 'PerplexityBot', + 'Perplexity-User', + 'Google-Extended', + 'BingBot', + 'Amazonbot', + 'Applebot', + 'Applebot-Extended', + 'FacebookBot', + 'meta-externalagent', + 'LinkedInBot', + 'Bytespider', + 'AI2Bot', + 'CCBot', + 'Diffbot', + 'DuckAssistBot', + 'DuckDuckGo', + 'DeepSeekBot', + 'cohere-ai', + 'omgili', + 'TimpiBot', + 'YouBot', + 'MistralAI-User', + 'ImagesiftBot', + 'Scrapy', + + 'chatgpt', + 'openai', + 'gpt', + 'claude', + 'anthropic', + 'cursor', + 'windsurf', + 'perplexity', + 'copilot', + 'ai-agent', + 'llm-agent', +]; + +function isAICrawler(request: Request): boolean { + // if (!userAgent) return false; + + const userAgent = request.headers.get('user-agent') || ''; + const accept = request.headers.get('accept') || ''; + + const hasHtml = accept.includes('text/html'); + + const prefersNonHtml = + !hasHtml && + (accept.includes('application/json') || + accept.includes('text/plain') || + accept.includes('application/xml')); + + const hasAiUserAgent = AI_CRAWLER_PATTERNS.some((pattern) => userAgent.toLowerCase().includes(pattern.toLowerCase())); + + return prefersNonHtml || hasAiUserAgent + + // const normalizedUA = userAgent.toLowerCase(); + // return AI_CRAWLER_PATTERNS.some((pattern) => normalizedUA.includes(pattern.toLowerCase())); +} + +export const onRequest: PagesFunction = async (context) => { + const { request, next } = context; + + if (isAICrawler(request)) { + const url = new URL(request.url); + const urlPath = url.pathname; + + const markdownPath = `${urlPath}.md`; + + const markdownRequest = new Request(new URL(markdownPath, url.origin), { + method: request.method, + headers: request.headers, + }); + + const response = await context.env.ASSETS.fetch(markdownRequest); + + if (response.ok) { + // Check what content type we actually got + const actualContentType = response.headers.get('content-type'); + console.log(`Fetched ${markdownPath}, got content-type: ${actualContentType}`); + + return new Response(response.body, { + status: 200, + headers: { + 'Content-Type': 'text/markdown; charset=utf-8', + 'Cache-Control': 'public, max-age=3600', + }, + }); + } + + return next(); + } + + return next(); +}; diff --git a/functions/types.d.ts b/functions/types.d.ts new file mode 100644 index 0000000000..86ad944860 --- /dev/null +++ b/functions/types.d.ts @@ -0,0 +1,12 @@ +// TypeScript definitions for Cloudflare Pages Functions +interface EventContext { + request: Request; + env: Env; + params: Record; + data: Record; + next: () => Promise; + waitUntil: (promise: Promise) => void; + passThroughOnException: () => void; +} + +type PagesFunction = (context: EventContext) => Response | Promise; diff --git a/package-lock.json b/package-lock.json index b57e49bc85..128d01fdb5 100644 --- a/package-lock.json +++ b/package-lock.json @@ -16,6 +16,7 @@ "@react-aria/overlays": "^3.29.1", "@react-aria/tooltip": "^3.8.7", "@react-aria/utils": "^3.24.1", + "@signalwire/docusaurus-plugin-llms-txt": "^2.0.0-alpha.2", "clsx": "^2.1.1", "copy-text-to-clipboard": "^3.1.0", "docusaurus-plugin-sass": "^0.2.6", @@ -6511,6 +6512,44 @@ "integrity": "sha512-RNiOoTPkptFtSVzQevY/yWtZwf/RxyVnPy/OcA9HBM3MlGDnBEYL5B41H0MTn0Uec8Hi+2qUtTfG2WWZBmMejQ==", "license": "BSD-3-Clause" }, + "node_modules/@signalwire/docusaurus-plugin-llms-txt": { + "version": "2.0.0-alpha.2", + "resolved": "https://registry.npmjs.org/@signalwire/docusaurus-plugin-llms-txt/-/docusaurus-plugin-llms-txt-2.0.0-alpha.2.tgz", + "integrity": "sha512-jLATcj60UE4/iYtrB4xbBqki9/+WSf2t/BQ2hcszzTnm1Rafl+kW7ykh1TXQSeq97nQaL6zTDzsJYrIdcFig1A==", + "license": "MIT", + "dependencies": { + "fs-extra": "^11.0.0", + "hast-util-select": "^6.0.4", + "hast-util-to-html": "^9.0.5", + "hast-util-to-string": "^3.0.1", + "p-map": "^7.0.2", + "rehype-parse": "^9", + "rehype-remark": "^10", + "remark-gfm": "^4", + "remark-stringify": "^11", + "string-width": "^5.0.0", + "unified": "^11", + "unist-util-visit": "^5" + }, + "engines": { + "node": ">=18.0.0" + }, + "peerDependencies": { + "@docusaurus/core": "^3.0.0" + } + }, + "node_modules/@signalwire/docusaurus-plugin-llms-txt/node_modules/p-map": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/p-map/-/p-map-7.0.3.tgz", + "integrity": "sha512-VkndIv2fIB99swvQoA65bm+fsmt6UNdGeIB0oxBs+WhAhdh08QA04JXpI7rbB9r08/nkbysKoya9rtDERYOYMA==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/@sinclair/typebox": { "version": "0.27.8", "resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.27.8.tgz", @@ -11667,6 +11706,20 @@ "node": ">= 0.4" } }, + "node_modules/hast-util-embedded": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/hast-util-embedded/-/hast-util-embedded-3.0.0.tgz", + "integrity": "sha512-naH8sld4Pe2ep03qqULEtvYr7EjrLK2QHY8KJR6RJkTUjPGObe1vnx585uzem2hGra+s1q08DZZpfgDVYRbaXA==", + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0", + "hast-util-is-element": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, "node_modules/hast-util-from-dom": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/hast-util-from-dom/-/hast-util-from-dom-5.0.1.tgz", @@ -11749,6 +11802,19 @@ "url": "https://opencollective.com/unified" } }, + "node_modules/hast-util-is-body-ok-link": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/hast-util-is-body-ok-link/-/hast-util-is-body-ok-link-3.0.1.tgz", + "integrity": "sha512-0qpnzOBLztXHbHQenVB8uNuxTnm/QBFUOmdOSsEn7GnBtyY07+ENTWVFBAnXd/zEgd9/SUG3lRY7hSIBWRgGpQ==", + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, "node_modules/hast-util-is-element": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/hast-util-is-element/-/hast-util-is-element-3.0.0.tgz", @@ -11762,6 +11828,23 @@ "url": "https://opencollective.com/unified" } }, + "node_modules/hast-util-minify-whitespace": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/hast-util-minify-whitespace/-/hast-util-minify-whitespace-1.0.1.tgz", + "integrity": "sha512-L96fPOVpnclQE0xzdWb/D12VT5FabA7SnZOUMtL1DbXmYiHJMXZvFkIZfiMmTCNJHUeO2K9UYNXoVyfz+QHuOw==", + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0", + "hast-util-embedded": "^3.0.0", + "hast-util-is-element": "^3.0.0", + "hast-util-whitespace": "^3.0.0", + "unist-util-is": "^6.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, "node_modules/hast-util-parse-selector": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/hast-util-parse-selector/-/hast-util-parse-selector-4.0.0.tgz", @@ -11775,6 +11858,23 @@ "url": "https://opencollective.com/unified" } }, + "node_modules/hast-util-phrasing": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/hast-util-phrasing/-/hast-util-phrasing-3.0.1.tgz", + "integrity": "sha512-6h60VfI3uBQUxHqTyMymMZnEbNl1XmEGtOxxKYL7stY2o601COo62AWAYBQR9lZbYXYSBoxag8UpPRXK+9fqSQ==", + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0", + "hast-util-embedded": "^3.0.0", + "hast-util-has-property": "^3.0.0", + "hast-util-is-body-ok-link": "^3.0.0", + "hast-util-is-element": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, "node_modules/hast-util-raw": { "version": "9.1.0", "resolved": "https://registry.npmjs.org/hast-util-raw/-/hast-util-raw-9.1.0.tgz", @@ -11855,6 +11955,29 @@ "url": "https://opencollective.com/unified" } }, + "node_modules/hast-util-to-html": { + "version": "9.0.5", + "resolved": "https://registry.npmjs.org/hast-util-to-html/-/hast-util-to-html-9.0.5.tgz", + "integrity": "sha512-OguPdidb+fbHQSU4Q4ZiLKnzWo8Wwsf5bZfbvu7//a9oTYoqD/fWpe96NuHkoS9h0ccGOTe0C4NGXdtS0iObOw==", + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0", + "@types/unist": "^3.0.0", + "ccount": "^2.0.0", + "comma-separated-tokens": "^2.0.0", + "hast-util-whitespace": "^3.0.0", + "html-void-elements": "^3.0.0", + "mdast-util-to-hast": "^13.0.0", + "property-information": "^7.0.0", + "space-separated-tokens": "^2.0.0", + "stringify-entities": "^4.0.0", + "zwitch": "^2.0.4" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, "node_modules/hast-util-to-jsx-runtime": { "version": "2.3.6", "resolved": "https://registry.npmjs.org/hast-util-to-jsx-runtime/-/hast-util-to-jsx-runtime-2.3.6.tgz", @@ -11882,6 +12005,32 @@ "url": "https://opencollective.com/unified" } }, + "node_modules/hast-util-to-mdast": { + "version": "10.1.2", + "resolved": "https://registry.npmjs.org/hast-util-to-mdast/-/hast-util-to-mdast-10.1.2.tgz", + "integrity": "sha512-FiCRI7NmOvM4y+f5w32jPRzcxDIz+PUqDwEqn1A+1q2cdp3B8Gx7aVrXORdOKjMNDQsD1ogOr896+0jJHW1EFQ==", + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0", + "@types/mdast": "^4.0.0", + "@ungap/structured-clone": "^1.0.0", + "hast-util-phrasing": "^3.0.0", + "hast-util-to-html": "^9.0.0", + "hast-util-to-text": "^4.0.0", + "hast-util-whitespace": "^3.0.0", + "mdast-util-phrasing": "^4.0.0", + "mdast-util-to-hast": "^13.0.0", + "mdast-util-to-string": "^4.0.0", + "rehype-minify-whitespace": "^6.0.0", + "trim-trailing-lines": "^2.0.0", + "unist-util-position": "^5.0.0", + "unist-util-visit": "^5.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, "node_modules/hast-util-to-parse5": { "version": "8.0.0", "resolved": "https://registry.npmjs.org/hast-util-to-parse5/-/hast-util-to-parse5-8.0.0.tgz", @@ -11924,6 +12073,22 @@ "url": "https://opencollective.com/unified" } }, + "node_modules/hast-util-to-text": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/hast-util-to-text/-/hast-util-to-text-4.0.2.tgz", + "integrity": "sha512-KK6y/BN8lbaq654j7JgBydev7wuNMcID54lkRav1P0CaE1e47P72AWWPiGKXTJU271ooYzcvTAn/Zt0REnvc7A==", + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0", + "@types/unist": "^3.0.0", + "hast-util-is-element": "^3.0.0", + "unist-util-find-after": "^5.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, "node_modules/hast-util-whitespace": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/hast-util-whitespace/-/hast-util-whitespace-3.0.0.tgz", @@ -18919,6 +19084,35 @@ "regjsparser": "bin/parser" } }, + "node_modules/rehype-minify-whitespace": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/rehype-minify-whitespace/-/rehype-minify-whitespace-6.0.2.tgz", + "integrity": "sha512-Zk0pyQ06A3Lyxhe9vGtOtzz3Z0+qZ5+7icZ/PL/2x1SHPbKao5oB/g/rlc6BCTajqBb33JcOe71Ye1oFsuYbnw==", + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0", + "hast-util-minify-whitespace": "^1.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/rehype-parse": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/rehype-parse/-/rehype-parse-9.0.1.tgz", + "integrity": "sha512-ksCzCD0Fgfh7trPDxr2rSylbwq9iYDkSn8TCDmEJ49ljEUBxDVCzCHv7QNzZOfODanX4+bWQ4WZqLCRWYLfhag==", + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0", + "hast-util-from-html": "^2.0.0", + "unified": "^11.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, "node_modules/rehype-raw": { "version": "7.0.0", "resolved": "https://registry.npmjs.org/rehype-raw/-/rehype-raw-7.0.0.tgz", @@ -18949,6 +19143,23 @@ "url": "https://opencollective.com/unified" } }, + "node_modules/rehype-remark": { + "version": "10.0.1", + "resolved": "https://registry.npmjs.org/rehype-remark/-/rehype-remark-10.0.1.tgz", + "integrity": "sha512-EmDndlb5NVwXGfUa4c9GPK+lXeItTilLhE6ADSaQuHr4JUlKw9MidzGzx4HpqZrNCt6vnHmEifXQiiA+CEnjYQ==", + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0", + "@types/mdast": "^4.0.0", + "hast-util-to-mdast": "^10.0.0", + "unified": "^11.0.0", + "vfile": "^6.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, "node_modules/relateurl": { "version": "0.2.7", "resolved": "https://registry.npmjs.org/relateurl/-/relateurl-0.2.7.tgz", @@ -20702,6 +20913,16 @@ "url": "https://github.com/sponsors/wooorm" } }, + "node_modules/trim-trailing-lines": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/trim-trailing-lines/-/trim-trailing-lines-2.1.0.tgz", + "integrity": "sha512-5UR5Biq4VlVOtzqkm2AZlgvSlDJtME46uV0br0gENbwN4l5+mMKT4b9gJKqWtuL2zAIqajGJGuvbCbcAJUZqBg==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/trough": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/trough/-/trough-2.2.0.tgz", @@ -20922,6 +21143,20 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/unist-util-find-after": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/unist-util-find-after/-/unist-util-find-after-5.0.0.tgz", + "integrity": "sha512-amQa0Ep2m6hE2g72AugUItjbuM8X8cGQnFoHk0pGfrFeT9GZhzN5SW8nRsiGKK7Aif4CrACPENkA6P/Lw6fHGQ==", + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0", + "unist-util-is": "^6.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, "node_modules/unist-util-is": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/unist-util-is/-/unist-util-is-6.0.0.tgz", diff --git a/package.json b/package.json index f9989b6807..93af9e443b 100644 --- a/package.json +++ b/package.json @@ -24,9 +24,10 @@ "@react-aria/overlays": "^3.29.1", "@react-aria/tooltip": "^3.8.7", "@react-aria/utils": "^3.24.1", + "@signalwire/docusaurus-plugin-llms-txt": "^2.0.0-alpha.2", "clsx": "^2.1.1", - "docusaurus-plugin-sass": "^0.2.6", "copy-text-to-clipboard": "^3.1.0", + "docusaurus-plugin-sass": "^0.2.6", "posthog-docusaurus": "^2.0.4", "prism-react-renderer": "^2.4.1", "react": "^19.1.1", diff --git a/sidebars.ts b/sidebars.ts index e38be5d27a..da2972ced2 100644 --- a/sidebars.ts +++ b/sidebars.ts @@ -44,241 +44,183 @@ const sidebars: SidebarsConfig = { className: "firstTitle", items: [ "getting-started/index", - { - type: "doc", - id: "getting-started/quickstart-prismaPostgres", - label: "Quickstart", - }, - { - type: "doc", - id: "getting-started/quickstart-sqlite", - label: "Quickstart", - className: "hidden-sidebar", - }, + // { + // type: "doc", + // id: "getting-started/quickstart-prismaPostgres", + // label: "Quickstart", + // customProps: { + // badge: "5 Min", + // }, + // }, + // { + // type: "doc", + // id: "getting-started/quickstart-sqlite", + // label: "Quickstart", + // className: "hidden-sidebar", + // }, { type: "category", label: "Prisma ORM", collapsed: false, collapsible: false, - link: { - type: "doc", - id: "getting-started/setup-prisma/index", - }, items: [ { type: "category", - label: "Start from scratch", + label: "Quickstart", + collapsed: true, + collapsible: true, + className: "hide-category-badge", link: { type: "doc", - id: "getting-started/setup-prisma/start-from-scratch/index", + id: "getting-started/prisma-orm/quickstart/prisma-postgres", + }, + customProps: { + hideBadge: true, }, items: [ { - type: "category", - label: "Relational databases", + type: "doc", + id: "getting-started/prisma-orm/quickstart/prisma-postgres", + label: "Prisma Postgres", customProps: { - badge: "15 Min", + badge: "5 Min", }, - link: { - type: "doc", - id: "getting-started/setup-prisma/start-from-scratch/relational-databases-typescript-prismaPostgres", + }, + { + type: "doc", + id: "getting-started/prisma-orm/quickstart/mysql", + label: "MySQL", + customProps: { + badge: "5 Min", }, - items: [ - { - type: "doc", - id: "getting-started/setup-prisma/start-from-scratch/relational-databases-typescript-postgresql", - className: "hidden-sidebar", - }, - { - type: "doc", - id: "getting-started/setup-prisma/start-from-scratch/relational-databases-typescript-prismaPostgres", - className: "hidden-sidebar", - }, - { - type: "doc", - id: "getting-started/setup-prisma/start-from-scratch/relational-databases-typescript-mysql", - className: "hidden-sidebar", - }, - { - type: "doc", - id: "getting-started/setup-prisma/start-from-scratch/relational-databases-typescript-planetscale", - className: "hidden-sidebar", - }, - { - type: "doc", - id: "getting-started/setup-prisma/start-from-scratch/relational-databases-typescript-sqlserver", - className: "hidden-sidebar", - }, - { - type: "doc", - id: "getting-started/setup-prisma/start-from-scratch/relational-databases-typescript-cockroachdb", - className: "hidden-sidebar", - }, - { - type: "doc", - id: "getting-started/setup-prisma/start-from-scratch/relational-databases-node-postgresql", - className: "hidden-sidebar", - }, - { - type: "doc", - id: "getting-started/setup-prisma/start-from-scratch/relational-databases-node-mysql", - className: "hidden-sidebar", - }, - { - type: "doc", - id: "getting-started/setup-prisma/start-from-scratch/relational-databases-node-planetscale", - className: "hidden-sidebar", - }, - { - type: "doc", - id: "getting-started/setup-prisma/start-from-scratch/relational-databases-node-sqlserver", - className: "hidden-sidebar", - }, - { - type: "doc", - id: "getting-started/setup-prisma/start-from-scratch/relational-databases-node-cockroachdb", - className: "hidden-sidebar", - }, - { - type: "autogenerated", - dirName: - "100-getting-started/02-setup-prisma/100-start-from-scratch/110-relational-databases", - }, - ], }, { - type: "category", - label: "MongoDB", + type: "doc", + id: "getting-started/prisma-orm/quickstart/postgresql", + label: "PostgreSQL", + customProps: { + badge: "5 Min", + }, + }, + { + type: "doc", + id: "getting-started/prisma-orm/quickstart/sqlite", + label: "SQLite", + customProps: { + badge: "5 Min", + }, + }, + { + type: "doc", + id: "getting-started/prisma-orm/quickstart/sql-server", + label: "SQL Server", + customProps: { + badge: "5 Min", + }, + }, + { + type: "doc", + id: "getting-started/prisma-orm/quickstart/planetscale", + label: "PlanetScale", + customProps: { + badge: "5 Min", + }, + }, + { + type: "doc", + id: "getting-started/prisma-orm/quickstart/cockroachdb", + label: "CockroachDB", customProps: { - badge: "15 Min", + badge: "5 Min", }, - link: { - type: "doc", - id: "getting-started/setup-prisma/start-from-scratch/mongodb-typescript-mongodb", + }, + { + type: "doc", + id: "getting-started/prisma-orm/quickstart/mongodb", + label: "MongoDB", + customProps: { + badge: "5 Min", }, - items: [ - { - type: "doc", - id: "getting-started/setup-prisma/start-from-scratch/mongodb-node-mongodb", - className: "hidden-sidebar", - }, - { - type: "doc", - id: "getting-started/setup-prisma/start-from-scratch/mongodb-typescript-mongodb", - className: "hidden-sidebar", - }, - { - type: "autogenerated", - dirName: - "100-getting-started/02-setup-prisma/100-start-from-scratch/120-mongodb", - }, - ], }, ], }, { type: "category", label: "Add to existing project", + collapsed: true, + collapsible: true, + className: "hide-category-badge", link: { type: "doc", - id: "getting-started/setup-prisma/add-to-existing-project/index", + id: "getting-started/prisma-orm/add-to-existing-project/prisma-postgres", + }, + customProps: { + hideBadge: true, }, items: [ { - type: "category", - label: "Relational databases", + type: "doc", + id: "getting-started/prisma-orm/add-to-existing-project/prisma-postgres", + label: "Prisma Postgres", customProps: { - badge: "15 Min", + badge: "5 Min", }, - link: { - type: "doc", - id: "getting-started/setup-prisma/add-to-existing-project/relational-databases-typescript-postgresql", + }, + { + type: "doc", + id: "getting-started/prisma-orm/add-to-existing-project/mysql", + label: "MySQL", + customProps: { + badge: "5 Min", }, - items: [ - { - type: "doc", - id: "getting-started/setup-prisma/add-to-existing-project/relational-databases-typescript-postgresql", - className: "hidden-sidebar", - }, - { - type: "doc", - id: "getting-started/setup-prisma/add-to-existing-project/relational-databases-typescript-mysql", - className: "hidden-sidebar", - }, - { - type: "doc", - id: "getting-started/setup-prisma/add-to-existing-project/relational-databases-typescript-planetscale", - className: "hidden-sidebar", - }, - { - type: "doc", - id: "getting-started/setup-prisma/add-to-existing-project/relational-databases-typescript-sqlserver", - className: "hidden-sidebar", - }, - { - type: "doc", - id: "getting-started/setup-prisma/add-to-existing-project/relational-databases-typescript-cockroachdb", - className: "hidden-sidebar", - }, - { - type: "doc", - id: "getting-started/setup-prisma/add-to-existing-project/relational-databases-node-postgresql", - className: "hidden-sidebar", - }, - { - type: "doc", - id: "getting-started/setup-prisma/add-to-existing-project/relational-databases-node-mysql", - className: "hidden-sidebar", - }, - { - type: "doc", - id: "getting-started/setup-prisma/add-to-existing-project/relational-databases-node-planetscale", - className: "hidden-sidebar", - }, - { - type: "doc", - id: "getting-started/setup-prisma/add-to-existing-project/relational-databases-node-sqlserver", - className: "hidden-sidebar", - }, - { - type: "doc", - id: "getting-started/setup-prisma/add-to-existing-project/relational-databases-node-cockroachdb", - className: "hidden-sidebar", - }, - { - type: "autogenerated", - dirName: - "100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases", - }, - ], }, { - type: "category", - label: "MongoDB", + type: "doc", + id: "getting-started/prisma-orm/add-to-existing-project/postgresql", + label: "PostgreSQL", customProps: { - badge: "15 Min", + badge: "5 Min", }, - link: { - type: "doc", - id: "getting-started/setup-prisma/add-to-existing-project/mongodb-typescript-mongodb", + }, + { + type: "doc", + id: "getting-started/prisma-orm/add-to-existing-project/sqlite", + label: "SQLite", + customProps: { + badge: "5 Min", + }, + }, + { + type: "doc", + id: "getting-started/prisma-orm/add-to-existing-project/sql-server", + label: "SQL Server", + customProps: { + badge: "5 Min", + }, + }, + { + type: "doc", + id: "getting-started/prisma-orm/add-to-existing-project/planetscale", + label: "PlanetScale", + customProps: { + badge: "5 Min", + }, + }, + { + type: "doc", + id: "getting-started/prisma-orm/add-to-existing-project/cockroachdb", + label: "CockroachDB", + customProps: { + badge: "5 Min", + }, + }, + { + type: "doc", + id: "getting-started/prisma-orm/add-to-existing-project/mongodb", + label: "MongoDB", + customProps: { + badge: "5 Min", }, - items: [ - { - type: "doc", - id: "getting-started/setup-prisma/add-to-existing-project/mongodb-node-mongodb", - className: "hidden-sidebar", - }, - { - type: "doc", - id: "getting-started/setup-prisma/add-to-existing-project/mongodb-typescript-mongodb", - className: "hidden-sidebar", - }, - { - type: "autogenerated", - dirName: - "100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb", - }, - ], }, ], }, @@ -294,29 +236,83 @@ const sidebars: SidebarsConfig = { id: "getting-started/prisma-postgres/index", }, items: [ - "getting-started/prisma-postgres/from-the-cli", - "getting-started/prisma-postgres/upgrade-from-early-access", { type: "category", - collapsible: false, + label: "Quickstart", + collapsed: true, + collapsible: true, + className: "hide-category-badge", + link: { + type: "doc", + id: "getting-started/prisma-postgres/quickstart/prisma-orm", + }, + customProps: { + hideBadge: true, + }, + items: [ + { + type: "doc", + id: "getting-started/prisma-postgres/quickstart/prisma-orm", + label: "Prisma ORM", + customProps: { + badge: "5 Min", + }, + }, + { + type: "doc", + id: "getting-started/prisma-postgres/quickstart/kysely", + label: "Kysely", + customProps: { + badge: "10 Min", + }, + }, + { + type: "doc", + id: "getting-started/prisma-postgres/quickstart/drizzle-orm", + label: "Drizzle ORM", + customProps: { + badge: "10 Min", + }, + }, + { + type: "doc", + id: "getting-started/prisma-postgres/quickstart/typeorm", + label: "TypeORM", + customProps: { + badge: "10 Min", + }, + }, + ], + }, + { + type: "category", + collapsed: true, + collapsible: true, + className: "hide-category-badge", label: "Import from existing database", link: { type: "doc", id: "getting-started/prisma-postgres/import-from-existing-database-postgresql", }, + customProps: { + hideBadge: true, + }, items: [ { type: "doc", id: "getting-started/prisma-postgres/import-from-existing-database-postgresql", - className: "hidden-sidebar", + label: "PostgreSQL", + className: "sidebar-item-normal-weight", }, { type: "doc", id: "getting-started/prisma-postgres/import-from-existing-database-mysql", - className: "hidden-sidebar", + label: "MySQL", + className: "sidebar-item-normal-weight", }, ], }, + "getting-started/prisma-postgres/from-the-cli", ], }, ], @@ -447,6 +443,7 @@ const sidebars: SidebarsConfig = { "guides/clerk-nextjs", "guides/shopify", "guides/permit-io-access-control", + "guides/betterauth-astro", "guides/betterauth-nextjs", "guides/ai-sdk-nextjs", "guides/authjs-nextjs", @@ -619,5 +616,3 @@ const sidebars: SidebarsConfig = { }; export default sidebars; - - diff --git a/src/components/GettingStarted/index.tsx b/src/components/GettingStarted/index.tsx index 92a0986c82..cfcab301c7 100644 --- a/src/components/GettingStarted/index.tsx +++ b/src/components/GettingStarted/index.tsx @@ -67,6 +67,36 @@ export const SignalStream = ({ color, height, width }: any) => ( ); +export const Plus = ({ color, height, width }: any) => ( + + + +); + +export const Plug = ({ color, height, width }: any) => ( + + + +); + export const PrismaPostgres = ({ color, height, width }: any) => ( { ); }; +export const QuickstartLinkCard = ({ icon, title, desc, link, highlight, children }: any) => { + const linkCardRef = useRef(null); + return ( + +
+ {icon && } +

{title}

+
+ {children ??

{desc}

} + + ); +}; + export const Tab = ({ children, ...props }) => (
{children} diff --git a/src/css/custom.css b/src/css/custom.css index 1aefb1bba6..5ff447caf1 100644 --- a/src/css/custom.css +++ b/src/css/custom.css @@ -1807,4 +1807,24 @@ pre > code { kbd.DocSearch-Commands-Key { padding: 0; +} + +/* Fix sidebar item styling for Import from existing database items */ +.sidebar-item-normal-weight a, +.sidebar-item-normal-weight .menu__link { + font-weight: normal !important; +} + +.sidebar-item-normal-weight a.menu__link--active, +.sidebar-item-normal-weight .menu__link.menu__link--active { + font-weight: 600 !important; +} + +/* More specific selector for nested category items */ +.theme-doc-sidebar-item-category .menu__list .sidebar-item-normal-weight a { + font-weight: normal !important; +} + +.theme-doc-sidebar-item-category .menu__list .sidebar-item-normal-weight a.menu__link--active { + font-weight: 600 !important; } \ No newline at end of file diff --git a/src/css/gettingStarted.module.scss b/src/css/gettingStarted.module.scss index 14fdb997a2..9d78a93d81 100644 --- a/src/css/gettingStarted.module.scss +++ b/src/css/gettingStarted.module.scss @@ -16,8 +16,14 @@ } .borderBox { padding: 24px 24px 32px 24px; + margin-top: 16px; + display: flex; + flex-direction: column; + justify-content: space-between; border-radius: 8px; - background: var(--main-bgd-color); + border: 1px solid var(--border-color); + background: var(--surface-brand-grey-strong); + width: fit-content; a { text-decoration: underline; } @@ -26,7 +32,8 @@ text-align: left; letter-spacing: 0em; line-height: 20px; - font-size: 14px; + font-size: 16px; + margin: 0; :first-child { margin-top: 0; } @@ -34,6 +41,23 @@ margin-bottom: 0; } } + > p { + margin-bottom: 16px; + &:last-child { + margin-bottom: 0; + } + } + pre[class*="language-"] { + background: #121521 !important; + border: 0.7px solid #2d3748; + code span { + font-size: 16px; + color: #e2e8f0 !important; + &::before { + color: #4a5568; + } + } + } } .boxTitle { @@ -45,31 +69,6 @@ letter-spacing: -0.8px; } -.grid { - gap: 16px; - display: grid; - margin-top: 24px; - grid-template-columns: none; - @media (min-width: 600px) { - grid-template-columns: 1fr 1fr; - } - a { - border-color: var(--ifm-btn-border-color); - background: transparent; - color: var(--main-font-color); - &:hover { - border-color: var(--ifm-btn-border-color-active); - background: transparent; - } - } -} - -.separator { - height: 100%; - width: 1px; - border-left: 1px solid var(--ifm-btn-border-color); -} - .linkCardWrapper { border: 1px solid var(--border-color); padding: 20px 24px; @@ -86,15 +85,16 @@ color: inherit; } &.linkCardHighlight { - background: rgba(22, 163, 148, 0.12); - border-color: rgb(22, 163, 148); - &:hover { - // background: #B7F4EE; - border-color: #154f47; - } + border-radius: 8px; + border: 1px solid var(--surface-brand-default); + background: var(--surface-brand-light); } .title { display: inline-flex; + h2 { + font-family: Barlow; + border-bottom: 1px solid var(--main-font-color); + } h6 { font-size: 18px; display: inline-block; @@ -117,22 +117,6 @@ } } -.tab { - padding: 15px; - background-color: var(--main-bgd-color); - border: 1px solid var(--indigo-600); - border-radius: 0px 8px 8px 8px; - font-family: Inter; - font-size: 14px; - font-weight: 400; - line-height: 20px; - letter-spacing: 0em; - text-align: left; - p { - margin-top: 0; - } -} - .squareWrapper { width: 90px; height: 90px; @@ -165,10 +149,14 @@ .list { display: grid; - gap: 16px; margin-top: 16px; - max-width: fit-content; + width: fit-content; grid-template-columns: repeat(2, auto); + gap: 16px; + width: fit-content; + display: flex; + justify-content: flex-start; + &:not(.framedList) { @media (min-width: 1400px) { grid-template-columns: repeat(7, auto); diff --git a/src/data/indexData.ts b/src/data/indexData.ts index 29bc26ad8d..4be0a02a19 100644 --- a/src/data/indexData.ts +++ b/src/data/indexData.ts @@ -125,9 +125,9 @@ export const get_help = [ export const tabs = [ { icon: "fa-solid fa-chart-pyramid", - label: "Use Prisma Postgres", + label: "Use Prisma's managed Postgres", description: - "Get started with your favorite framework and Prisma Postgres. With Prisma Postgres you get an instant, fully hosted high-performance database that includes built-in caching, scales to zero, and integrates deeply with Prisma ORM and Prisma Studio—all backed by a generous free tier.", + "Get started with your favorite framework and Prisma Postgres. With Prisma Postgres you get an instant, fully hosted high-performance database that scales to zero and integrates deeply with Prisma ORM and Prisma Studio—all backed by a generous free tier.", list: [ { url: "/guides/nextjs", @@ -168,35 +168,35 @@ export const tabs = [ "Already have a database? With Prisma ORM and Prisma Data Platform, you can supercharge your existing stack. Add connection pooling and caching with generous free tiers.", list: [ { - url: "/getting-started/setup-prisma/add-to-existing-project/relational-databases-typescript-postgresql", + url: "/getting-started/prisma-orm/add-to-existing-project/postgresql", image: "/img/technologies/postgresqlsimple.svg", tech: "PostgreSQL", }, { - url: "/getting-started/setup-prisma/add-to-existing-project/relational-databases-typescript-planetscale", + url: "/getting-started/prisma-orm/add-to-existing-project/planetscale", image: "/img/technologies/planetscale.svg", imageDark: "/img/technologies/planetscaledark.svg", tech: "Planetscale", }, { - url: "/getting-started/setup-prisma/add-to-existing-project/relational-databases-typescript-sqlserver", + url: "/getting-started/prisma-orm/add-to-existing-project/sql-server", image: "/img/technologies/sqlserver.svg", tech: "SQL Server", }, { - url: "/getting-started/setup-prisma/add-to-existing-project/relational-databases-typescript-mysql", + url: "/getting-started/prisma-orm/add-to-existing-project/mysql", image: "/img/technologies/mysqlsimple.svg", tech: "MySQL", }, { - url: "/getting-started/setup-prisma/add-to-existing-project/mongodb-typescript-mongodb", + url: "/getting-started/prisma-orm/add-to-existing-project/mongodb", image: "/img/technologies/mongodbsimple.svg", imageDark: "/img/technologies/mongodbsimple.svg", tech: "MongoDB", }, ], link: { - url: "/getting-started/setup-prisma/add-to-existing-project", + url: "/getting-started/prisma-orm/add-to-existing-project/postgresql", label: "How to migrate to Prisma ORM", icon: "fa-regular fa-book-open", }, diff --git a/src/pages/index.tsx b/src/pages/index.tsx index e242c4ec34..55f2b82ea3 100644 --- a/src/pages/index.tsx +++ b/src/pages/index.tsx @@ -54,7 +54,7 @@ function HomepageHowDoISection() { const hiddenCards = how_do_i.slice(3); const location = useLocation(); - + return (
@@ -72,7 +72,7 @@ function HomepageHowDoISection() { {e.tags.map((tag: any) => )}
} {e.time &&
- + {e.time} min. read
}
} @@ -89,7 +89,7 @@ function HomepageHowDoISection() { {e.tags.map((tag: any) => )} } {e.time &&
- + {e.time} min. read
} } @@ -100,7 +100,7 @@ function HomepageHowDoISection() { className={clsx(styles.seeMore, seeMore && styles.clicked)} onClick={() => { setSeeMore(!seeMore) - howRef.current.scrollIntoView({behavior: "smooth", offset: 80}); + howRef.current.scrollIntoView({ behavior: "smooth", offset: 80 }); }} > See {seeMore ? `less` : `more`} @@ -110,7 +110,7 @@ function HomepageHowDoISection() { ); } -const CommunityIcon = ({icon, link, label}: any) => { +const CommunityIcon = ({ icon, link, label }: any) => { const [visibleTooltip, setVisibleTooltip] = useState(false); const iconRef = useRef(null); @@ -161,41 +161,41 @@ function HomepageCommunitySection() { ); } -const TabBox = ({icon, label, description, list, link}: any) => { +const TabBox = ({ icon, label, description, list, link }: any) => { const location = useLocation(); return (
- {icon && } + {icon && } {label}
-

+

- {list && list.length && list.map((l: any, idx: number) => + {list && list.length && list.map((l: any, idx: number) => )}
- + {link.label} - +
) } function HomepageHeroSection() { - const { colorMode } = useColorMode(); + const { colorMode } = useColorMode(); return (
@@ -216,7 +216,7 @@ function HomepageHeroSection() { label="Start with an AI prompt →" color="teal" /> */}
- {tabs && tabs.map((tab: any, idx: number) => + {tabs && tabs.map((tab: any, idx: number) => )}
@@ -241,9 +241,9 @@ function HomepageGetHelpSection() {

{e.title}

-

+

- {e.links.map((link: any) => + {e.links.map((link: any) => {link.label} @@ -272,7 +272,7 @@ export default function Home(): JSX.Element { - + diff --git a/static/_redirects b/static/_redirects index e2c2eb925f..c90e320673 100644 --- a/static/_redirects +++ b/static/_redirects @@ -47,18 +47,18 @@ /reference/tools-and-interfaces/prisma-schema/models /docs/reference/tools-and-interfaces/prisma-schema/data-model # sql -> relational-databases -/getting-started/setup-prisma/start-from-scratch-sql-typescript-postgres /docs/getting-started/setup-prisma/start-from-scratch/relational-databases-typescript-postgresql -/getting-started/setup-prisma/start-from-scratch-sql-node-postgres /docs/getting-started/setup-prisma/start-from-scratch/relational-databases-node-postgresql -/getting-started/setup-prisma/start-from-scratch-sql-typescript-mysql /docs/getting-started/setup-prisma/start-from-scratch/relational-databases-typescript-mysql -/getting-started/setup-prisma/start-from-scratch-sql-node-mysql /docs/getting-started/setup-prisma/start-from-scratch/relational-databases-node-mysql -/getting-started/setup-prisma/start-from-scratch-prisma-migrate-typescript-postgres /docs/getting-started/setup-prisma/start-from-scratch/relational-databases-typescript-postgresql -/getting-started/setup-prisma/start-from-scratch-prisma-migrate-node-postgres /docs/getting-started/setup-prisma/start-from-scratch/relational-databases-node-postgresql -/getting-started/setup-prisma/start-from-scratch-prisma-migrate-typescript-mysql /docs/getting-started/setup-prisma/start-from-scratch/relational-databases-typescript-mysql -/getting-started/setup-prisma/start-from-scratch-prisma-migrate-node-mysql /docs/getting-started/setup-prisma/start-from-scratch/relational-databases-node-mysql -/getting-started/setup-prisma/start-from-scratch-typescript-postgres /docs/getting-started/setup-prisma/start-from-scratch/relational-databases-typescript-postgresql -/getting-started/setup-prisma/start-from-scratch-node-postgres /docs/getting-started/setup-prisma/start-from-scratch/relational-databases-node-postgresql -/getting-started/setup-prisma/start-from-scratch-typescript-mysql /docs/getting-started/setup-prisma/start-from-scratch/relational-databases-typescript-mysql -/getting-started/setup-prisma/start-from-scratch-node-mysql /docs/getting-started/setup-prisma/start-from-scratch/relational-databases-node-mysql +/getting-started/setup-prisma/start-from-scratch-sql-typescript-postgres /docs/getting-started/prisma-orm/quickstart/postgresql +/getting-started/setup-prisma/start-from-scratch-sql-node-postgres /docs/getting-started/prisma-orm/start-from-scratch/relational-databases-node-postgresql +/getting-started/setup-prisma/start-from-scratch-sql-typescript-mysql /docs/getting-started/prisma-orm/quickstart/mysql +/getting-started/setup-prisma/start-from-scratch-sql-node-mysql /docs/getting-started/prisma-orm/start-from-scratch/relational-databases-node-mysql +/getting-started/setup-prisma/start-from-scratch-prisma-migrate-typescript-postgres /docs/getting-started/prisma-orm/quickstart/postgresql +/getting-started/setup-prisma/start-from-scratch-prisma-migrate-node-postgres /docs/getting-started/prisma-orm/start-from-scratch/relational-databases-node-postgresql +/getting-started/setup-prisma/start-from-scratch-prisma-migrate-typescript-mysql /docs/getting-started/prisma-orm/quickstart/mysql +/getting-started/setup-prisma/start-from-scratch-prisma-migrate-node-mysql /docs/getting-started/prisma-orm/start-from-scratch/relational-databases-node-mysql +/getting-started/setup-prisma/start-from-scratch-typescript-postgres /docs/getting-started/prisma-orm/quickstart/postgresql +/getting-started/setup-prisma/start-from-scratch-node-postgres /docs/getting-started/prisma-orm/start-from-scratch/relational-databases-node-postgresql +/getting-started/setup-prisma/start-from-scratch-typescript-mysql /docs/getting-started/prisma-orm/quickstart/mysql +/getting-started/setup-prisma/start-from-scratch-node-mysql /docs/getting-started/prisma-orm/start-from-scratch/relational-databases-node-mysql /reference/tools-and-interfaces/prisma-schema/prisma-schema-file /docs/reference/tools-and-interfaces/prisma-schema /reference/tools-and-interfaces/prisma-client/api /docs/reference/tools-and-interfaces/prisma-client @@ -72,8 +72,8 @@ /more/supported-databases /docs/orm/reference/supported-databases /understand-prisma/introduction /docs/concepts/overview/what-is-prisma /understand-prisma/data-modeling /docs/concepts/overview/what-is-prisma/data-modeling -/getting-started/setup-prisma/start-from-scratch-prisma-migrate /docs/getting-started/setup-prisma/start-from-scratch-typescript-postgresql -/getting-started/setup-prisma/start-from-scratch-sql /docs/getting-started/setup-prisma +/getting-started/setup-prisma/start-from-scratch-prisma-migrate /docs/getting-started/prisma-orm/start-from-scratch-typescript-postgresql +/getting-started/setup-prisma/start-from-scratch-sql /docs/getting-started/prisma-orm /guides/prisma-guides/prisma-migrate-guides /docs/guides/prisma-guides/add-prisma-migrate-to-a-project /guides/prisma-guides/prisma-migrate-guides/add-prisma-migrate-to-a-project /docs/guides/prisma-guides/add-prisma-migrate-to-a-project /concepts/components/prisma-client/distinct /docs/concepts/components/prisma-client/aggregation-grouping-summarizing#select-distinct @@ -119,67 +119,246 @@ /concepts/more/codemod /docs/orm/more/upgrade-guides # postgres -> postgresql -/getting-started/setup-prisma/start-from-scratch-typescript-postgres /docs/getting-started/setup-prisma/start-from-scratch/relational-databases-typescript-postgresql -/getting-started/setup-prisma/start-from-scratch/connect-your-database-typescript-postgres /docs/getting-started/setup-prisma/start-from-scratch/relational-databases/connect-your-database-typescript-postgresql -/getting-started/setup-prisma/start-from-scratch/using-prisma-migrate-typescript-postgres /docs/getting-started/setup-prisma/start-from-scratch/relational-databases/using-prisma-migrate-typescript-postgresql -/getting-started/setup-prisma/start-from-scratch/install-prisma-client-typescript-postgres /docs/getting-started/setup-prisma/start-from-scratch/relational-databases/install-prisma-client-typescript-postgresql -/getting-started/setup-prisma/start-from-scratch/querying-the-database-typescript-postgres /docs/getting-started/setup-prisma/start-from-scratch/relational-databases/querying-the-database-typescript-postgresql -/getting-started/setup-prisma/start-from-scratch/next-steps-typescript-postgres /docs/getting-started/setup-prisma/start-from-scratch/relational-databases/next-steps-typescript-postgresql -/getting-started/setup-prisma/start-from-scratch/connect-your-database-node-postgres /docs/getting-started/setup-prisma/start-from-scratch/relational-databases/connect-your-database-node-postgresql -/getting-started/setup-prisma/start-from-scratch/using-prisma-migrate-node-postgres /docs/getting-started/setup-prisma/start-from-scratch/relational-databases/using-prisma-migrate-node-postgresql -/getting-started/setup-prisma/start-from-scratch/install-prisma-client-node-postgres /docs/getting-started/setup-prisma/start-from-scratch/relational-databases/install-prisma-client-node-postgresql -/getting-started/setup-prisma/start-from-scratch/querying-the-database-node-postgres /docs/getting-started/setup-prisma/start-from-scratch/relational-databases/querying-the-database-node-postgresql -/getting-started/setup-prisma/start-from-scratch/next-steps-node-postgres /docs/getting-started/setup-prisma/start-from-scratch/relational-databases/next-steps-node-postgresql -/getting-started/setup-prisma/start-from-scratch/relational-databases/connect-your-database-typescript-postgres /docs/getting-started/setup-prisma/start-from-scratch/relational-databases/connect-your-database-typescript-postgresql -/getting-started/setup-prisma/start-from-scratch/relational-databases/connect-your-database-node-postgres /docs/getting-started/setup-prisma/start-from-scratch/relational-databases/connect-your-database-node-postgresql -/getting-started/setup-prisma/start-from-scratch/relational-databases/using-prisma-migrate-typescript-postgres /docs/getting-started/setup-prisma/start-from-scratch/relational-databases/using-prisma-migrate-typescript-postgresql -/getting-started/setup-prisma/start-from-scratch/relational-databases/using-prisma-migrate-node-postgres /docs/getting-started/setup-prisma/start-from-scratch/relational-databases/using-prisma-migrate-node-postgresql -/getting-started/setup-prisma/start-from-scratch/relational-databases/install-prisma-client-typescript-postgres /docs/getting-started/setup-prisma/start-from-scratch/relational-databases/install-prisma-client-typescript-postgresql -/getting-started/setup-prisma/start-from-scratch/relational-databases/install-prisma-client-node-postgres /docs/getting-started/setup-prisma/start-from-scratch/relational-databases/install-prisma-client-node-postgresql -/getting-started/setup-prisma/start-from-scratch/relational-databases/querying-the-database-typescript-postgres /docs/getting-started/setup-prisma/start-from-scratch/relational-databases/querying-the-database-typescript-postgresql -/getting-started/setup-prisma/start-from-scratch/relational-databases/querying-the-database-node-postgres /docs/getting-started/setup-prisma/start-from-scratch/relational-databases/querying-the-database-node-postgresql -/getting-started/setup-prisma/start-from-scratch/relational-databases/next-steps-typescript-postgres /docs/getting-started/setup-prisma/start-from-scratch/relational-databases/next-steps-typescript-postgresql -/getting-started/setup-prisma/start-from-scratch/relational-databases/next-steps-node-postgres /docs/getting-started/setup-prisma/start-from-scratch/relational-databases/next-steps-node-postgresql -/getting-started/setup-prisma/start-from-scratch/relational-databases-typescript-postgres /docs/getting-started/setup-prisma/start-from-scratch/relational-databases-typescript-postgresql -/getting-started/setup-prisma/start-from-scratch/relational-databases-node-postgres /docs/getting-started/setup-prisma/start-from-scratch/relational-databases-node-postgresql -/getting-started/setup-prisma/add-to-existing-project-typescript-postgres /docs/getting-started/setup-prisma/add-to-existing-project/relational-databases-typescript-postgresql -/getting-started/setup-prisma/add-to-existing-project/connect-your-database-typescript-postgres /docs/getting-started/setup-prisma/add-to-existing-project/relational-databases/connect-your-database-typescript-postgresql -/getting-started/setup-prisma/add-to-existing-project/introspection-typescript-postgres /docs/getting-started/setup-prisma/add-to-existing-project/relational-databases/introspection-typescript-postgresql -/getting-started/setup-prisma/add-to-existing-project/install-prisma-client-typescript-postgres /docs/getting-started/setup-prisma/add-to-existing-project/relational-databases/install-prisma-client-typescript-postgresql -/getting-started/setup-prisma/add-to-existing-project/querying-the-database-typescript-postgres /docs/getting-started/setup-prisma/add-to-existing-project/relational-databases/querying-the-database-typescript-postgresql -/getting-started/setup-prisma/add-to-existing-project/next-steps-typescript-postgres /docs/getting-started/setup-prisma/add-to-existing-project/relational-databases/next-steps-typescript-postgresql -/getting-started/setup-prisma/add-to-existing-project/connect-your-database-node-postgres /docs/getting-started/setup-prisma/add-to-existing-project/relational-databases/connect-your-database-node-postgresql -/getting-started/setup-prisma/add-to-existing-project/introspection-node-postgres /docs/getting-started/setup-prisma/add-to-existing-project/relational-databases/introspection-node-postgresql -/getting-started/setup-prisma/add-to-existing-project/install-prisma-client-node-postgres /docs/getting-started/setup-prisma/add-to-existing-project/relational-databases/install-prisma-client-node-postgresql -/getting-started/setup-prisma/add-to-existing-project/querying-the-database-node-postgres /docs/getting-started/setup-prisma/add-to-existing-project/relational-databases/querying-the-database-node-postgresql -/getting-started/setup-prisma/add-to-existing-project/next-steps-node-postgres /docs/getting-started/setup-prisma/add-to-existing-project/relational-databases/next-steps-node-postgresql -/getting-started/setup-prisma/add-to-existing-project/relational-databases/connect-your-database-typescript-postgres /docs/getting-started/setup-prisma/add-to-existing-project/relational-databases/connect-your-database-typescript-postgresql -/getting-started/setup-prisma/add-to-existing-project/relational-databases/connect-your-database-node-postgres /docs/getting-started/setup-prisma/add-to-existing-project/relational-databases/connect-your-database-node-postgresql -/getting-started/setup-prisma/add-to-existing-project/relational-databases/introspection-typescript-postgres /docs/getting-started/setup-prisma/add-to-existing-project/relational-databases/introspection-typescript-postgresql -/getting-started/setup-prisma/add-to-existing-project/relational-databases/introspection-node-postgres /docs/getting-started/setup-prisma/add-to-existing-project/relational-databases/introspection-node-postgresql -/getting-started/setup-prisma/add-to-existing-project/relational-databases/baseline-your-database-typescript-postgres /docs/getting-started/setup-prisma/add-to-existing-project/relational-databases/baseline-your-database-typescript-postgresql -/getting-started/setup-prisma/add-to-existing-project/relational-databases/baseline-your-database-node-postgres /docs/getting-started/setup-prisma/add-to-existing-project/relational-databases/baseline-your-database-node-postgresql -/getting-started/setup-prisma/add-to-existing-project/relational-databases/install-prisma-client-typescript-postgres /docs/getting-started/setup-prisma/add-to-existing-project/relational-databases/install-prisma-client-typescript-postgresql -/getting-started/setup-prisma/add-to-existing-project/relational-databases/install-prisma-client-node-postgres /docs/getting-started/setup-prisma/add-to-existing-project/relational-databases/install-prisma-client-node-postgresql -/getting-started/setup-prisma/add-to-existing-project/relational-databases/querying-the-database-typescript-postgres /docs/getting-started/setup-prisma/add-to-existing-project/relational-databases/querying-the-database-typescript-postgresql -/getting-started/setup-prisma/add-to-existing-project/relational-databases/querying-the-database-node-postgres /docs/getting-started/setup-prisma/add-to-existing-project/relational-databases/querying-the-database-node-postgresql -/getting-started/setup-prisma/add-to-existing-project/relational-databases/evolve-your-schema-typescript-postgres /docs/getting-started/setup-prisma/add-to-existing-project/relational-databases/evolve-your-schema-typescript-postgresql -/getting-started/setup-prisma/add-to-existing-project/relational-databases/evolve-your-schema-node-postgres /docs/getting-started/setup-prisma/add-to-existing-project/relational-databases/evolve-your-schema-node-postgresql -/getting-started/setup-prisma/add-to-existing-project/relational-databases/next-steps-typescript-postgres /docs/getting-started/setup-prisma/add-to-existing-project/relational-databases/next-steps-typescript-postgresql -/getting-started/setup-prisma/add-to-existing-project/relational-databases/next-steps-node-postgres /docs/getting-started/setup-prisma/add-to-existing-project/relational-databases/next-steps-node-postgresql -/getting-started/setup-prisma/add-to-existing-project/relational-databases-typescript-postgres /docs/getting-started/setup-prisma/add-to-existing-project/relational-databases-typescript-postgresql -/getting-started/setup-prisma/add-to-existing-project/relational-databases-node-postgres /docs/getting-started/setup-prisma/add-to-existing-project/relational-databases-node-postgresql +/getting-started/setup-prisma/start-from-scratch-typescript-postgres /docs/getting-started/prisma-orm/quickstart/postgresql +/getting-started/setup-prisma/start-from-scratch/connect-your-database-typescript-postgres /docs/getting-started/prisma-orm/start-from-scratch/relational-databases/connect-your-database-typescript-postgresql +/getting-started/setup-prisma/start-from-scratch/using-prisma-migrate-typescript-postgres /docs/getting-started/prisma-orm/start-from-scratch/relational-databases/using-prisma-migrate-typescript-postgresql +/getting-started/setup-prisma/start-from-scratch/install-prisma-client-typescript-postgres /docs/getting-started/prisma-orm/start-from-scratch/relational-databases/install-prisma-client-typescript-postgresql +/getting-started/setup-prisma/start-from-scratch/querying-the-database-typescript-postgres /docs/getting-started/prisma-orm/start-from-scratch/relational-databases/querying-the-database-typescript-postgresql +/getting-started/setup-prisma/start-from-scratch/next-steps-typescript-postgres /docs/getting-started/prisma-orm/start-from-scratch/relational-databases/next-steps-typescript-postgresql +/getting-started/setup-prisma/start-from-scratch/connect-your-database-node-postgres /docs/getting-started/prisma-orm/start-from-scratch/relational-databases/connect-your-database-node-postgresql +/getting-started/setup-prisma/start-from-scratch/using-prisma-migrate-node-postgres /docs/getting-started/prisma-orm/start-from-scratch/relational-databases/using-prisma-migrate-node-postgresql +/getting-started/setup-prisma/start-from-scratch/install-prisma-client-node-postgres /docs/getting-started/prisma-orm/start-from-scratch/relational-databases/install-prisma-client-node-postgresql +/getting-started/setup-prisma/start-from-scratch/querying-the-database-node-postgres /docs/getting-started/prisma-orm/start-from-scratch/relational-databases/querying-the-database-node-postgresql +/getting-started/setup-prisma/start-from-scratch/next-steps-node-postgres /docs/getting-started/prisma-orm/start-from-scratch/relational-databases/next-steps-node-postgresql +/getting-started/setup-prisma/start-from-scratch/relational-databases/connect-your-database-typescript-postgres /docs/getting-started/prisma-orm/start-from-scratch/relational-databases/connect-your-database-typescript-postgresql +/getting-started/setup-prisma/start-from-scratch/relational-databases/connect-your-database-node-postgres /docs/getting-started/prisma-orm/start-from-scratch/relational-databases/connect-your-database-node-postgresql +/getting-started/setup-prisma/start-from-scratch/relational-databases/using-prisma-migrate-typescript-postgres /docs/getting-started/prisma-orm/start-from-scratch/relational-databases/using-prisma-migrate-typescript-postgresql +/getting-started/setup-prisma/start-from-scratch/relational-databases/using-prisma-migrate-node-postgres /docs/getting-started/prisma-orm/start-from-scratch/relational-databases/using-prisma-migrate-node-postgresql +/getting-started/setup-prisma/start-from-scratch/relational-databases/install-prisma-client-typescript-postgres /docs/getting-started/prisma-orm/start-from-scratch/relational-databases/install-prisma-client-typescript-postgresql +/getting-started/setup-prisma/start-from-scratch/relational-databases/install-prisma-client-node-postgres /docs/getting-started/prisma-orm/start-from-scratch/relational-databases/install-prisma-client-node-postgresql +/getting-started/setup-prisma/start-from-scratch/relational-databases/querying-the-database-typescript-postgres /docs/getting-started/prisma-orm/start-from-scratch/relational-databases/querying-the-database-typescript-postgresql +/getting-started/setup-prisma/start-from-scratch/relational-databases/querying-the-database-node-postgres /docs/getting-started/prisma-orm/start-from-scratch/relational-databases/querying-the-database-node-postgresql +/getting-started/setup-prisma/start-from-scratch/relational-databases/next-steps-typescript-postgres /docs/getting-started/prisma-orm/start-from-scratch/relational-databases/next-steps-typescript-postgresql +/getting-started/setup-prisma/start-from-scratch/relational-databases/next-steps-node-postgres /docs/getting-started/prisma-orm/start-from-scratch/relational-databases/next-steps-node-postgresql +/getting-started/setup-prisma/start-from-scratch/relational-databases-typescript-postgres /docs/getting-started/prisma-orm/quickstart/postgresql +/getting-started/setup-prisma/start-from-scratch/relational-databases-node-postgres /docs/getting-started/prisma-orm/start-from-scratch/relational-databases-node-postgresql +/getting-started/setup-prisma/add-to-existing-project-typescript-postgres /docs/getting-started/prisma-orm/add-to-existing-project/postgresql +/getting-started/setup-prisma/add-to-existing-project/connect-your-database-typescript-postgres /docs/getting-started/prisma-orm/add-to-existing-project/postgresql/relational-databases/connect-your-database-typescript-postgresql +/getting-started/setup-prisma/add-to-existing-project/introspection-typescript-postgres /docs/getting-started/prisma-orm/add-to-existing-project/postgresql/relational-databases/introspection-typescript-postgresql +/getting-started/setup-prisma/add-to-existing-project/install-prisma-client-typescript-postgres /docs/getting-started/prisma-orm/add-to-existing-project/postgresql/relational-databases/install-prisma-client-typescript-postgresql +/getting-started/setup-prisma/add-to-existing-project/querying-the-database-typescript-postgres /docs/getting-started/prisma-orm/add-to-existing-project/postgresql/relational-databases/querying-the-database-typescript-postgresql +/getting-started/setup-prisma/add-to-existing-project/next-steps-typescript-postgres /docs/getting-started/prisma-orm/add-to-existing-project/postgresql/relational-databases/next-steps-typescript-postgresql +/getting-started/setup-prisma/add-to-existing-project/connect-your-database-node-postgres /docs/getting-started/prisma-orm/add-to-existing-project/postgresql/relational-databases/connect-your-database-node-postgresql +/getting-started/setup-prisma/add-to-existing-project/introspection-node-postgres /docs/getting-started/prisma-orm/add-to-existing-project/postgresql/relational-databases/introspection-node-postgresql +/getting-started/setup-prisma/add-to-existing-project/install-prisma-client-node-postgres /docs/getting-started/prisma-orm/add-to-existing-project/postgresql/relational-databases/install-prisma-client-node-postgresql +/getting-started/setup-prisma/add-to-existing-project/querying-the-database-node-postgres /docs/getting-started/prisma-orm/add-to-existing-project/postgresql/relational-databases/querying-the-database-node-postgresql +/getting-started/setup-prisma/add-to-existing-project/next-steps-node-postgres /docs/getting-started/prisma-orm/add-to-existing-project/postgresql/relational-databases/next-steps-node-postgresql +/getting-started/setup-prisma/add-to-existing-project/relational-databases/connect-your-database-typescript-postgres /docs/getting-started/prisma-orm/add-to-existing-project/postgresql/relational-databases/connect-your-database-typescript-postgresql +/getting-started/setup-prisma/add-to-existing-project/relational-databases/connect-your-database-node-postgres /docs/getting-started/prisma-orm/add-to-existing-project/postgresql/relational-databases/connect-your-database-node-postgresql +/getting-started/setup-prisma/add-to-existing-project/relational-databases/introspection-typescript-postgres /docs/getting-started/prisma-orm/add-to-existing-project/postgresql/relational-databases/introspection-typescript-postgresql +/getting-started/setup-prisma/add-to-existing-project/relational-databases/introspection-node-postgres /docs/getting-started/prisma-orm/add-to-existing-project/postgresql/relational-databases/introspection-node-postgresql +/getting-started/setup-prisma/add-to-existing-project/relational-databases/baseline-your-database-typescript-postgres /docs/getting-started/prisma-orm/add-to-existing-project/postgresql/relational-databases/baseline-your-database-typescript-postgresql +/getting-started/setup-prisma/add-to-existing-project/relational-databases/baseline-your-database-node-postgres /docs/getting-started/prisma-orm/add-to-existing-project/postgresql/relational-databases/baseline-your-database-node-postgresql +/getting-started/setup-prisma/add-to-existing-project/relational-databases/install-prisma-client-typescript-postgres /docs/getting-started/prisma-orm/add-to-existing-project/postgresql/relational-databases/install-prisma-client-typescript-postgresql +/getting-started/setup-prisma/add-to-existing-project/relational-databases/install-prisma-client-node-postgres /docs/getting-started/prisma-orm/add-to-existing-project/postgresql/relational-databases/install-prisma-client-node-postgresql +/getting-started/setup-prisma/add-to-existing-project/relational-databases/querying-the-database-typescript-postgres /docs/getting-started/prisma-orm/add-to-existing-project/postgresql/relational-databases/querying-the-database-typescript-postgresql +/getting-started/setup-prisma/add-to-existing-project/relational-databases/querying-the-database-node-postgres /docs/getting-started/prisma-orm/add-to-existing-project/postgresql/relational-databases/querying-the-database-node-postgresql +/getting-started/setup-prisma/add-to-existing-project/relational-databases/evolve-your-schema-typescript-postgres /docs/getting-started/prisma-orm/add-to-existing-project/postgresql/relational-databases/evolve-your-schema-typescript-postgresql +/getting-started/setup-prisma/add-to-existing-project/relational-databases/evolve-your-schema-node-postgres /docs/getting-started/prisma-orm/add-to-existing-project/postgresql/relational-databases/evolve-your-schema-node-postgresql +/getting-started/setup-prisma/add-to-existing-project/relational-databases/next-steps-typescript-postgres /docs/getting-started/prisma-orm/add-to-existing-project/postgresql/relational-databases/next-steps-typescript-postgresql +/getting-started/setup-prisma/add-to-existing-project/relational-databases/next-steps-node-postgres /docs/getting-started/prisma-orm/add-to-existing-project/postgresql/relational-databases/next-steps-node-postgresql +/getting-started/setup-prisma/add-to-existing-project/relational-databases-typescript-postgres /docs/getting-started/prisma-orm/add-to-existing-project/postgresql +/getting-started/setup-prisma/add-to-existing-project/relational-databases-node-postgres /docs/getting-started/prisma-orm/add-to-existing-project/postgresql/relational-databases-node-postgresql + + +/getting-started/quickstart-prismaPostgres* /docs/getting-started/prisma-orm/quickstart/prisma-postgres +/getting-started/quickstart-sqlite* /docs/getting-started/prisma-orm/quickstart/sqlite + + +/getting-started/setup-prisma/start-from-scratch/relational-databases-node-cockroachdb* /docs/getting-started/prisma-orm/quickstart/cockroachdb +/getting-started/setup-prisma/start-from-scratch/relational-databases-node-mysql* /docs/getting-started/prisma-orm/quickstart/mysql +/getting-started/setup-prisma/start-from-scratch/relational-databases-node-planetscale* /docs/getting-started/prisma-orm/quickstart/planetscale +/getting-started/setup-prisma/start-from-scratch/relational-databases-node-postgresql* /docs/getting-started/prisma-orm/quickstart/postgresql +/getting-started/setup-prisma/start-from-scratch/relational-databases-node-sqlserver* /docs/getting-started/prisma-orm/quickstart/sql-server +/getting-started/setup-prisma/start-from-scratch/relational-databases-typescript-cockroachdb* /docs/getting-started/prisma-orm/quickstart/cockroachdb +/getting-started/setup-prisma/start-from-scratch/relational-databases-typescript-mysql* /docs/getting-started/prisma-orm/quickstart/mysql +/getting-started/setup-prisma/start-from-scratch/relational-databases-typescript-planetscale* /docs/getting-started/prisma-orm/quickstart/planetscale +/getting-started/setup-prisma/start-from-scratch/relational-databases-typescript-postgresql* /docs/getting-started/prisma-orm/quickstart/postgresql +/getting-started/setup-prisma/start-from-scratch/relational-databases-typescript-prismaPostgres* /docs/getting-started/prisma-orm/quickstart/prisma-postgres +/getting-started/setup-prisma/start-from-scratch/relational-databases-typescript-sqlserver* /docs/getting-started/prisma-orm/quickstart/sql-server + + +/getting-started/setup-prisma/start-from-scratch/relational-databases/connect-your-database-node-cockroachdb* /docs/getting-started/prisma-orm/quickstart/cockroachdb +/getting-started/setup-prisma/start-from-scratch/relational-databases/connect-your-database-node-mysql* /docs/getting-started/prisma-orm/quickstart/mysql +/getting-started/setup-prisma/start-from-scratch/relational-databases/connect-your-database-node-planetscale* /docs/getting-started/prisma-orm/quickstart/planetscale +/getting-started/setup-prisma/start-from-scratch/relational-databases/connect-your-database-node-postgresql* /docs/getting-started/prisma-orm/quickstart/postgresql +/getting-started/setup-prisma/start-from-scratch/relational-databases/connect-your-database-node-sqlserver* /docs/getting-started/prisma-orm/quickstart/sql-server +/getting-started/setup-prisma/start-from-scratch/relational-databases/connect-your-database-typescript-cockroachdb* /docs/getting-started/prisma-orm/quickstart/cockroachdb +/getting-started/setup-prisma/start-from-scratch/relational-databases/connect-your-database-typescript-mysql* /docs/getting-started/prisma-orm/quickstart/mysql +/getting-started/setup-prisma/start-from-scratch/relational-databases/connect-your-database-typescript-planetscale* /docs/getting-started/prisma-orm/quickstart/planetscale +/getting-started/setup-prisma/start-from-scratch/relational-databases/connect-your-database-typescript-postgresql* /docs/getting-started/prisma-orm/quickstart/postgresql +/getting-started/setup-prisma/start-from-scratch/relational-databases/connect-your-database-typescript-prismaPostgres* /docs/getting-started/prisma-orm/quickstart/prisma-postgres +/getting-started/setup-prisma/start-from-scratch/relational-databases/connect-your-database-typescript-sqlserver* /docs/getting-started/prisma-orm/quickstart/sql-server + + +/getting-started/setup-prisma/start-from-scratch/relational-databases/using-prisma-migrate-node-cockroachdb* /docs/getting-started/prisma-orm/quickstart/cockroachdb +/getting-started/setup-prisma/start-from-scratch/relational-databases/using-prisma-migrate-node-mysql* /docs/getting-started/prisma-orm/quickstart/mysql +/getting-started/setup-prisma/start-from-scratch/relational-databases/using-prisma-migrate-node-planetscale* /docs/getting-started/prisma-orm/quickstart/planetscale +/getting-started/setup-prisma/start-from-scratch/relational-databases/using-prisma-migrate-node-postgresql* /docs/getting-started/prisma-orm/quickstart/postgresql +/getting-started/setup-prisma/start-from-scratch/relational-databases/using-prisma-migrate-node-sqlserver* /docs/getting-started/prisma-orm/quickstart/sql-server +/getting-started/setup-prisma/start-from-scratch/relational-databases/using-prisma-migrate-typescript-cockroachdb* /docs/getting-started/prisma-orm/quickstart/cockroachdb +/getting-started/setup-prisma/start-from-scratch/relational-databases/using-prisma-migrate-typescript-mysql* /docs/getting-started/prisma-orm/quickstart/mysql +/getting-started/setup-prisma/start-from-scratch/relational-databases/using-prisma-migrate-typescript-planetscale* /docs/getting-started/prisma-orm/quickstart/planetscale +/getting-started/setup-prisma/start-from-scratch/relational-databases/using-prisma-migrate-typescript-postgresql* /docs/getting-started/prisma-orm/quickstart/postgresql +/getting-started/setup-prisma/start-from-scratch/relational-databases/using-prisma-migrate-typescript-prismaPostgres* /docs/getting-started/prisma-orm/quickstart/prisma-postgres +/getting-started/setup-prisma/start-from-scratch/relational-databases/using-prisma-migrate-typescript-sqlserver* /docs/getting-started/prisma-orm/quickstart/sql-server + + +/getting-started/setup-prisma/start-from-scratch/relational-databases/install-prisma-client-node-cockroachdb* /docs/getting-started/prisma-orm/quickstart/cockroachdb +/getting-started/setup-prisma/start-from-scratch/relational-databases/install-prisma-client-node-mysql* /docs/getting-started/prisma-orm/quickstart/mysql +/getting-started/setup-prisma/start-from-scratch/relational-databases/install-prisma-client-node-planetscale* /docs/getting-started/prisma-orm/quickstart/planetscale +/getting-started/setup-prisma/start-from-scratch/relational-databases/install-prisma-client-node-postgresql* /docs/getting-started/prisma-orm/quickstart/postgresql +/getting-started/setup-prisma/start-from-scratch/relational-databases/install-prisma-client-node-sqlserver* /docs/getting-started/prisma-orm/quickstart/sql-server +/getting-started/setup-prisma/start-from-scratch/relational-databases/install-prisma-client-typescript-cockroachdb* /docs/getting-started/prisma-orm/quickstart/cockroachdb +/getting-started/setup-prisma/start-from-scratch/relational-databases/install-prisma-client-typescript-mysql* /docs/getting-started/prisma-orm/quickstart/mysql +/getting-started/setup-prisma/start-from-scratch/relational-databases/install-prisma-client-typescript-planetscale* /docs/getting-started/prisma-orm/quickstart/planetscale +/getting-started/setup-prisma/start-from-scratch/relational-databases/install-prisma-client-typescript-postgresql* /docs/getting-started/prisma-orm/quickstart/postgresql +/getting-started/setup-prisma/start-from-scratch/relational-databases/install-prisma-client-typescript-prismaPostgres* /docs/getting-started/prisma-orm/quickstart/prisma-postgres +/getting-started/setup-prisma/start-from-scratch/relational-databases/install-prisma-client-typescript-sqlserver* /docs/getting-started/prisma-orm/quickstart/sql-server + + +/getting-started/setup-prisma/start-from-scratch/relational-databases/querying-the-database-node-cockroachdb* /docs/getting-started/prisma-orm/quickstart/cockroachdb +/getting-started/setup-prisma/start-from-scratch/relational-databases/querying-the-database-node-mysql* /docs/getting-started/prisma-orm/quickstart/mysql +/getting-started/setup-prisma/start-from-scratch/relational-databases/querying-the-database-node-planetscale* /docs/getting-started/prisma-orm/quickstart/planetscale +/getting-started/setup-prisma/start-from-scratch/relational-databases/querying-the-database-node-postgresql* /docs/getting-started/prisma-orm/quickstart/postgresql +/getting-started/setup-prisma/start-from-scratch/relational-databases/querying-the-database-node-sqlserver* /docs/getting-started/prisma-orm/quickstart/sql-server +/getting-started/setup-prisma/start-from-scratch/relational-databases/querying-the-database-typescript-cockroachdb* /docs/getting-started/prisma-orm/quickstart/cockroachdb +/getting-started/setup-prisma/start-from-scratch/relational-databases/querying-the-database-typescript-mysql* /docs/getting-started/prisma-orm/quickstart/mysql +/getting-started/setup-prisma/start-from-scratch/relational-databases/querying-the-database-typescript-planetscale* /docs/getting-started/prisma-orm/quickstart/planetscale +/getting-started/setup-prisma/start-from-scratch/relational-databases/querying-the-database-typescript-postgresql* /docs/getting-started/prisma-orm/quickstart/postgresql +/getting-started/setup-prisma/start-from-scratch/relational-databases/querying-the-database-typescript-prismaPostgres* /docs/getting-started/prisma-orm/quickstart/prisma-postgres +/getting-started/setup-prisma/start-from-scratch/relational-databases/querying-the-database-typescript-sqlserver* /docs/getting-started/prisma-orm/quickstart/sql-server + + +/getting-started/setup-prisma/start-from-scratch/relational-databases/next-steps* /docs/getting-started/prisma-orm/quickstart/prisma-postgres +/getting-started/setup-prisma/start-from-scratch/mongodb-node-mongodb* /docs/getting-started/prisma-orm/quickstart/mongodb +/getting-started/setup-prisma/start-from-scratch/mongodb-typescript-mongodb* /docs/getting-started/prisma-orm/quickstart/mongodb +/getting-started/setup-prisma/start-from-scratch/mongodb/connect-your-database-node-mongodb* /docs/getting-started/prisma-orm/quickstart/mongodb +/getting-started/setup-prisma/start-from-scratch/mongodb/connect-your-database-typescript-mongodb* /docs/getting-started/prisma-orm/quickstart/mongodb +/getting-started/setup-prisma/start-from-scratch/mongodb/creating-the-prisma-schema-node-mongodb* /docs/getting-started/prisma-orm/quickstart/mongodb +/getting-started/setup-prisma/start-from-scratch/mongodb/creating-the-prisma-schema-typescript-mongodb* /docs/getting-started/prisma-orm/quickstart/mongodb +/getting-started/setup-prisma/start-from-scratch/mongodb/install-prisma-client-node-mongodb* /docs/getting-started/prisma-orm/quickstart/mongodb +/getting-started/setup-prisma/start-from-scratch/mongodb/install-prisma-client-typescript-mongodb* /docs/getting-started/prisma-orm/quickstart/mongodb +/getting-started/setup-prisma/start-from-scratch/mongodb/querying-the-database-node-mongodb* /docs/getting-started/prisma-orm/quickstart/mongodb +/getting-started/setup-prisma/start-from-scratch/mongodb/querying-the-database-typescript-mongodb* /docs/getting-started/prisma-orm/quickstart/mongodb +/getting-started/setup-prisma/start-from-scratch/mongodb/next-steps* /docs/getting-started/prisma-orm/quickstart/mongodb +/getting-started/setup-prisma/start-from-scratch* /docs/getting-started/prisma-orm/quickstart/prisma-postgres + +# Add to existing project - main pages +/getting-started/setup-prisma/add-to-existing-project/relational-databases-node-cockroachdb* /docs/getting-started/prisma-orm/add-to-existing-project/cockroachdb +/getting-started/setup-prisma/add-to-existing-project/relational-databases-node-mysql* /docs/getting-started/prisma-orm/add-to-existing-project/mysql +/getting-started/setup-prisma/add-to-existing-project/relational-databases-node-planetscale* /docs/getting-started/prisma-orm/add-to-existing-project/planetscale +/getting-started/setup-prisma/add-to-existing-project/relational-databases-node-postgresql* /docs/getting-started/prisma-orm/add-to-existing-project/postgresql +/getting-started/setup-prisma/add-to-existing-project/relational-databases-node-sqlserver* /docs/getting-started/prisma-orm/add-to-existing-project/sql-server +/getting-started/setup-prisma/add-to-existing-project/relational-databases-typescript-cockroachdb* /docs/getting-started/prisma-orm/add-to-existing-project/cockroachdb +/getting-started/setup-prisma/add-to-existing-project/relational-databases-typescript-mysql* /docs/getting-started/prisma-orm/add-to-existing-project/mysql +/getting-started/setup-prisma/add-to-existing-project/relational-databases-typescript-planetscale* /docs/getting-started/prisma-orm/add-to-existing-project/planetscale +/getting-started/setup-prisma/add-to-existing-project/relational-databases-typescript-postgresql* /docs/getting-started/prisma-orm/add-to-existing-project/postgresql +/getting-started/setup-prisma/add-to-existing-project/relational-databases-typescript-sqlserver* /docs/getting-started/prisma-orm/add-to-existing-project/sql-server + + +/getting-started/setup-prisma/add-to-existing-project/relational-databases/connect-your-database-node-cockroachdb* /docs/getting-started/prisma-orm/add-to-existing-project/cockroachdb +/getting-started/setup-prisma/add-to-existing-project/relational-databases/connect-your-database-node-mysql* /docs/getting-started/prisma-orm/add-to-existing-project/mysql +/getting-started/setup-prisma/add-to-existing-project/relational-databases/connect-your-database-node-planetscale* /docs/getting-started/prisma-orm/add-to-existing-project/planetscale +/getting-started/setup-prisma/add-to-existing-project/relational-databases/connect-your-database-node-postgresql* /docs/getting-started/prisma-orm/add-to-existing-project/postgresql +/getting-started/setup-prisma/add-to-existing-project/relational-databases/connect-your-database-node-sqlserver* /docs/getting-started/prisma-orm/add-to-existing-project/sql-server +/getting-started/setup-prisma/add-to-existing-project/relational-databases/connect-your-database-typescript-cockroachdb* /docs/getting-started/prisma-orm/add-to-existing-project/cockroachdb +/getting-started/setup-prisma/add-to-existing-project/relational-databases/connect-your-database-typescript-mysql* /docs/getting-started/prisma-orm/add-to-existing-project/mysql +/getting-started/setup-prisma/add-to-existing-project/relational-databases/connect-your-database-typescript-planetscale* /docs/getting-started/prisma-orm/add-to-existing-project/planetscale +/getting-started/setup-prisma/add-to-existing-project/relational-databases/connect-your-database-typescript-postgresql* /docs/getting-started/prisma-orm/add-to-existing-project/postgresql +/getting-started/setup-prisma/add-to-existing-project/relational-databases/connect-your-database-typescript-sqlserver* /docs/getting-started/prisma-orm/add-to-existing-project/sql-server + + +/getting-started/setup-prisma/add-to-existing-project/relational-databases/introspection-node-cockroachdb* /docs/getting-started/prisma-orm/add-to-existing-project/cockroachdb +/getting-started/setup-prisma/add-to-existing-project/relational-databases/introspection-node-mysql* /docs/getting-started/prisma-orm/add-to-existing-project/mysql +/getting-started/setup-prisma/add-to-existing-project/relational-databases/introspection-node-planetscale* /docs/getting-started/prisma-orm/add-to-existing-project/planetscale +/getting-started/setup-prisma/add-to-existing-project/relational-databases/introspection-node-postgresql* /docs/getting-started/prisma-orm/add-to-existing-project/postgresql +/getting-started/setup-prisma/add-to-existing-project/relational-databases/introspection-node-sqlserver* /docs/getting-started/prisma-orm/add-to-existing-project/sql-server +/getting-started/setup-prisma/add-to-existing-project/relational-databases/introspection-typescript-cockroachdb* /docs/getting-started/prisma-orm/add-to-existing-project/cockroachdb +/getting-started/setup-prisma/add-to-existing-project/relational-databases/introspection-typescript-mysql* /docs/getting-started/prisma-orm/add-to-existing-project/mysql +/getting-started/setup-prisma/add-to-existing-project/relational-databases/introspection-typescript-planetscale* /docs/getting-started/prisma-orm/add-to-existing-project/planetscale +/getting-started/setup-prisma/add-to-existing-project/relational-databases/introspection-typescript-postgresql* /docs/getting-started/prisma-orm/add-to-existing-project/postgresql +/getting-started/setup-prisma/add-to-existing-project/relational-databases/introspection-typescript-sqlserver* /docs/getting-started/prisma-orm/add-to-existing-project/sql-server + + +/getting-started/setup-prisma/add-to-existing-project/relational-databases/baseline-your-database-node-cockroachdb* /docs/getting-started/prisma-orm/add-to-existing-project/cockroachdb +/getting-started/setup-prisma/add-to-existing-project/relational-databases/baseline-your-database-node-mysql* /docs/getting-started/prisma-orm/add-to-existing-project/mysql +/getting-started/setup-prisma/add-to-existing-project/relational-databases/baseline-your-database-node-postgresql* /docs/getting-started/prisma-orm/add-to-existing-project/postgresql +/getting-started/setup-prisma/add-to-existing-project/relational-databases/baseline-your-database-node-sqlserver* /docs/getting-started/prisma-orm/add-to-existing-project/sql-server +/getting-started/setup-prisma/add-to-existing-project/relational-databases/baseline-your-database-typescript-cockroachdb* /docs/getting-started/prisma-orm/add-to-existing-project/cockroachdb +/getting-started/setup-prisma/add-to-existing-project/relational-databases/baseline-your-database-typescript-mysql* /docs/getting-started/prisma-orm/add-to-existing-project/mysql +/getting-started/setup-prisma/add-to-existing-project/relational-databases/baseline-your-database-typescript-postgresql* /docs/getting-started/prisma-orm/add-to-existing-project/postgresql +/getting-started/setup-prisma/add-to-existing-project/relational-databases/baseline-your-database-typescript-sqlserver* /docs/getting-started/prisma-orm/add-to-existing-project/sql-server + +/getting-started/setup-prisma/add-to-existing-project/relational-databases/install-prisma-client-node-cockroachdb* /docs/getting-started/prisma-orm/add-to-existing-project/cockroachdb +/getting-started/setup-prisma/add-to-existing-project/relational-databases/install-prisma-client-node-mysql* /docs/getting-started/prisma-orm/add-to-existing-project/mysql +/getting-started/setup-prisma/add-to-existing-project/relational-databases/install-prisma-client-node-planetscale* /docs/getting-started/prisma-orm/add-to-existing-project/planetscale +/getting-started/setup-prisma/add-to-existing-project/relational-databases/install-prisma-client-node-postgresql* /docs/getting-started/prisma-orm/add-to-existing-project/postgresql +/getting-started/setup-prisma/add-to-existing-project/relational-databases/install-prisma-client-node-sqlserver* /docs/getting-started/prisma-orm/add-to-existing-project/sql-server +/getting-started/setup-prisma/add-to-existing-project/relational-databases/install-prisma-client-typescript-cockroachdb* /docs/getting-started/prisma-orm/add-to-existing-project/cockroachdb +/getting-started/setup-prisma/add-to-existing-project/relational-databases/install-prisma-client-typescript-mysql* /docs/getting-started/prisma-orm/add-to-existing-project/mysql +/getting-started/setup-prisma/add-to-existing-project/relational-databases/install-prisma-client-typescript-planetscale* /docs/getting-started/prisma-orm/add-to-existing-project/planetscale +/getting-started/setup-prisma/add-to-existing-project/relational-databases/install-prisma-client-typescript-postgresql* /docs/getting-started/prisma-orm/add-to-existing-project/postgresql +/getting-started/setup-prisma/add-to-existing-project/relational-databases/install-prisma-client-typescript-sqlserver* /docs/getting-started/prisma-orm/add-to-existing-project/sql-server + + +/getting-started/setup-prisma/add-to-existing-project/relational-databases/querying-the-database-node-cockroachdb* /docs/getting-started/prisma-orm/add-to-existing-project/cockroachdb +/getting-started/setup-prisma/add-to-existing-project/relational-databases/querying-the-database-node-mysql* /docs/getting-started/prisma-orm/add-to-existing-project/mysql +/getting-started/setup-prisma/add-to-existing-project/relational-databases/querying-the-database-node-planetscale* /docs/getting-started/prisma-orm/add-to-existing-project/planetscale +/getting-started/setup-prisma/add-to-existing-project/relational-databases/querying-the-database-node-postgresql* /docs/getting-started/prisma-orm/add-to-existing-project/postgresql +/getting-started/setup-prisma/add-to-existing-project/relational-databases/querying-the-database-node-sqlserver* /docs/getting-started/prisma-orm/add-to-existing-project/sql-server +/getting-started/setup-prisma/add-to-existing-project/relational-databases/querying-the-database-typescript-cockroachdb* /docs/getting-started/prisma-orm/add-to-existing-project/cockroachdb +/getting-started/setup-prisma/add-to-existing-project/relational-databases/querying-the-database-typescript-mysql* /docs/getting-started/prisma-orm/add-to-existing-project/mysql +/getting-started/setup-prisma/add-to-existing-project/relational-databases/querying-the-database-typescript-planetscale* /docs/getting-started/prisma-orm/add-to-existing-project/planetscale +/getting-started/setup-prisma/add-to-existing-project/relational-databases/querying-the-database-typescript-postgresql* /docs/getting-started/prisma-orm/add-to-existing-project/postgresql +/getting-started/setup-prisma/add-to-existing-project/relational-databases/querying-the-database-typescript-sqlserver* /docs/getting-started/prisma-orm/add-to-existing-project/sql-server + + +/getting-started/setup-prisma/add-to-existing-project/relational-databases/evolve-your-schema-node-cockroachdb* /docs/getting-started/prisma-orm/add-to-existing-project/cockroachdb +/getting-started/setup-prisma/add-to-existing-project/relational-databases/evolve-your-schema-node-mysql* /docs/getting-started/prisma-orm/add-to-existing-project/mysql +/getting-started/setup-prisma/add-to-existing-project/relational-databases/evolve-your-schema-node-postgresql* /docs/getting-started/prisma-orm/add-to-existing-project/postgresql +/getting-started/setup-prisma/add-to-existing-project/relational-databases/evolve-your-schema-node-sqlserver* /docs/getting-started/prisma-orm/add-to-existing-project/sql-server +/getting-started/setup-prisma/add-to-existing-project/relational-databases/evolve-your-schema-typescript-cockroachdb* /docs/getting-started/prisma-orm/add-to-existing-project/cockroachdb +/getting-started/setup-prisma/add-to-existing-project/relational-databases/evolve-your-schema-typescript-mysql* /docs/getting-started/prisma-orm/add-to-existing-project/mysql +/getting-started/setup-prisma/add-to-existing-project/relational-databases/evolve-your-schema-typescript-postgresql* /docs/getting-started/prisma-orm/add-to-existing-project/postgresql +/getting-started/setup-prisma/add-to-existing-project/relational-databases/evolve-your-schema-typescript-sqlserver* /docs/getting-started/prisma-orm/add-to-existing-project/sql-server + +/getting-started/setup-prisma/add-to-existing-project/relational-databases/next-steps* /docs/getting-started/prisma-orm/add-to-existing-project/prisma-postgres +/getting-started/setup-prisma/add-to-existing-project/mongodb-node-mongodb* /docs/getting-started/prisma-orm/add-to-existing-project/mongodb +/getting-started/setup-prisma/add-to-existing-project/mongodb-typescript-mongodb* /docs/getting-started/prisma-orm/add-to-existing-project/mongodb +/getting-started/setup-prisma/add-to-existing-project/mongodb/connect-your-database-node-mongodb* /docs/getting-started/prisma-orm/add-to-existing-project/mongodb +/getting-started/setup-prisma/add-to-existing-project/mongodb/connect-your-database-typescript-mongodb* /docs/getting-started/prisma-orm/add-to-existing-project/mongodb +/getting-started/setup-prisma/add-to-existing-project/mongodb/introspection-node-mongodb* /docs/getting-started/prisma-orm/add-to-existing-project/mongodb +/getting-started/setup-prisma/add-to-existing-project/mongodb/introspection-typescript-mongodb* /docs/getting-started/prisma-orm/add-to-existing-project/mongodb +/getting-started/setup-prisma/add-to-existing-project/mongodb/install-prisma-client-node-mongodb* /docs/getting-started/prisma-orm/add-to-existing-project/mongodb +/getting-started/setup-prisma/add-to-existing-project/mongodb/install-prisma-client-typescript-mongodb* /docs/getting-started/prisma-orm/add-to-existing-project/mongodb +/getting-started/setup-prisma/add-to-existing-project/mongodb/querying-the-database-node-mongodb* /docs/getting-started/prisma-orm/add-to-existing-project/mongodb +/getting-started/setup-prisma/add-to-existing-project/mongodb/querying-the-database-typescript-mongodb* /docs/getting-started/prisma-orm/add-to-existing-project/mongodb +/getting-started/setup-prisma/add-to-existing-project/mongodb/next-steps* /docs/getting-started/prisma-orm/add-to-existing-project/mongodb +/getting-started/setup-prisma/add-to-existing-project* /docs/getting-started/prisma-orm/add-to-existing-project/prisma-postgres + +# Setup prisma parent and middleware +/getting-started/setup-prisma* /docs/getting-started/prisma-orm +/orm/prisma-client/client-extensions/middleware/soft-delete-middleware* /docs/orm/prisma-client/client-extensions/middleware +/orm/prisma-client/client-extensions/middleware/logging-middleware* /docs/orm/prisma-client/client-extensions/middleware +/orm/prisma-client/client-extensions/middleware/session-data-middleware* /docs/orm/prisma-client/client-extensions/middleware /concepts/more/environment-variables /docs/guides/development-environment/environment-variables /concepts/more/environment-variables/managing-env-files-and-setting-variables /docs/guides/development-environment/environment-variables /concepts/more/environment-variables/using-multiple-env-files /docs/guides/development-environment/environment-variables /concepts/more/editor-setup /docs/guides/development-environment/editor-setup /about/about-the-docs /docs/about -/about/style-guide /docs/about/style-guide -/about/style-guide/mdx-examples /docs/about/style-guide/mdx-examples -/about/style-guide/frontmatter /docs/about/style-guide/frontmatter -/about/style-guide/template /docs/about/style-guide/template -/concepts/components/preview-features/sql-server/sql-server-start-from-scratch-typescript /docs/getting-started/setup-prisma/start-from-scratch/relational-databases-typescript-sqlserver +/concepts/components/preview-features/sql-server/sql-server-start-from-scratch-typescript /docs/getting-started/prisma-orm/quickstart/sql-server /concepts/database-connectors/microsoft-sql-server /docs/concepts/database-connectors/sql-server /concepts/components/preview-features/sql-server/sql-server-connection-string /docs/concepts/database-connectors/sql-server /concepts/components/preview-features/sql-server/sql-server-local /docs/concepts/database-connectors/sql-server/sql-server-local @@ -497,7 +676,7 @@ /orm/more/migrating-to-prisma/migrate-from-sequelize /docs/guides/migrate-from-sequelize /orm/more/migrating-to-prisma/migrate-from-mongoose /docs/guides/migrate-from-mongoose /orm/more/migrating-to-prisma/migrate-from-drizzle /docs/guides/migrate-from-drizzle -/getting-started/quickstart /docs/getting-started/quickstart-prismaPostgres +/getting-started/quickstart /docs/getting-started/prisma-orm/quickstart/prisma-postgres /guides/realtime-apps /docs/postgres # move help articles up a level @@ -565,6 +744,8 @@ /postgres/database/error-reference /docs/postgres/database/api-reference/error-reference /postgres/integrations/vscode-extension /postgres/integrations/vscode +/postgres/introduction/getting-started /docs/postgres/getting-started + ### Dynamic redirects ### /faq/* https://v1.prisma.io/docs/1.34/faq/:splat /understand-prisma/* https://v1.prisma.io/docs/1.34/understand-prisma/:splat @@ -604,15 +785,14 @@ /concepts/overview/api-comparisons/* /docs/orm/more/comparisons:splat /concepts/overview/why-prisma/api-comparisons/* /docs/orm/more/comparisons:splat /guides/migrate-to-prisma* /docs/orm/more/migrating-to-prisma:splat -/getting-started/setup-prisma/start-from-scratch/relational-databases/next-steps-* /docs/getting-started/setup-prisma/start-from-scratch/relational-databases/next-steps -/getting-started/setup-prisma/start-from-scratch/mongodb/next-steps-* /docs/getting-started/setup-prisma/start-from-scratch/mongodb/next-steps -/getting-started/setup-prisma/add-to-existing-project/relational-databases/next-steps-* /docs/getting-started/setup-prisma/add-to-existing-project/relational-databases/next-steps -/getting-started/setup-prisma/add-to-existing-project/mongodb/next-steps-* /docs/getting-started/setup-prisma/add-to-existing-project/mongodb/next-steps -/getting-started/setup-prisma/add-to-existing-project/relational-databases-typescript-prismaPostgres /docs/getting-started/setup-prisma/add-to-existing-project/relational-databases-typescript-postgresql +/getting-started/setup-prisma/start-from-scratch/relational-databases/next-steps-* /docs/getting-started/prisma-orm/start-from-scratch/relational-databases/next-steps +/getting-started/setup-prisma/start-from-scratch/mongodb/next-steps-* /docs/getting-started/prisma-orm/start-from-scratch/mongodb/next-steps +/getting-started/setup-prisma/add-to-existing-project/relational-databases/next-steps-* /docs/getting-started/prisma-orm/add-to-existing-project/postgresql/relational-databases/next-steps +/getting-started/setup-prisma/add-to-existing-project/mongodb/next-steps-* /docs/getting-started/prisma-orm/add-to-existing-project/postgresql/mongodb/next-steps +/getting-started/setup-prisma/add-to-existing-project/relational-databases-typescript-prismaPostgres /docs/getting-started/prisma-orm/add-to-existing-project/postgresql /pulse* /docs/postgres -/postgres/getting-started* /docs/postgres/introduction/getting-started /postgres/overview* /docs/postgres/introduction/overview /postgres/caching* /docs/postgres/database/caching @@ -636,5 +816,10 @@ /postgres/database/tooling /docs/postgres/integrations/viewing-data /postgres/integrations/tooling /docs/postgres/integrations/viewing-data +/orm/getting-started/quickstart* /docs/getting-started/prisma-orm/quickstart/prisma-postgres +/orm/getting-started/add-to-existing-project* /docs/getting-started/prisma-orm/add-to-existing-project/prisma-postgres + +/getting-started/prisma-postgres/upgrade-from-early-access* /docs/postgres/getting-started + ### NO REDIRECTS BELOW THIS LINE. ADD REDIRECTS ABOVE THIS SECTION ### diff --git a/static/img/guides/prisma-betterauth-astro-cover.png b/static/img/guides/prisma-betterauth-astro-cover.png new file mode 100644 index 0000000000..5ac0879424 Binary files /dev/null and b/static/img/guides/prisma-betterauth-astro-cover.png differ diff --git a/static/img/technologies/astro.svg b/static/img/technologies/astro.svg new file mode 100644 index 0000000000..e52118199d --- /dev/null +++ b/static/img/technologies/astro.svg @@ -0,0 +1,4 @@ + + + + diff --git a/static/img/technologies/astrodark.svg b/static/img/technologies/astrodark.svg new file mode 100644 index 0000000000..52b76d5509 --- /dev/null +++ b/static/img/technologies/astrodark.svg @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/static/img/technologies/drizzle.svg b/static/img/technologies/drizzle.svg new file mode 100644 index 0000000000..fdacf2c789 --- /dev/null +++ b/static/img/technologies/drizzle.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/static/img/technologies/kysely.svg b/static/img/technologies/kysely.svg new file mode 100644 index 0000000000..5ca04a32b0 --- /dev/null +++ b/static/img/technologies/kysely.svg @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + diff --git a/static/img/technologies/remix.svg b/static/img/technologies/remix.svg new file mode 100644 index 0000000000..25faf57061 --- /dev/null +++ b/static/img/technologies/remix.svg @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/static/img/technologies/sequelize.svg b/static/img/technologies/sequelize.svg new file mode 100644 index 0000000000..728f77161e --- /dev/null +++ b/static/img/technologies/sequelize.svg @@ -0,0 +1,36 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/static/img/technologies/typeorm.svg b/static/img/technologies/typeorm.svg new file mode 100644 index 0000000000..e91fbd55c8 --- /dev/null +++ b/static/img/technologies/typeorm.svg @@ -0,0 +1,4 @@ + + + +