From 1c58baf6b5a2f65b90d6e83f97bdc8b0f8971ffa Mon Sep 17 00:00:00 2001 From: Daniel Bruzual Date: Mon, 6 Nov 2023 16:44:01 +0200 Subject: [PATCH 1/4] Fixes link caption in Prisma Migration docs (#5426) --- content/200-concepts/100-components/03-prisma-migrate/index.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/content/200-concepts/100-components/03-prisma-migrate/index.mdx b/content/200-concepts/100-components/03-prisma-migrate/index.mdx index 80a978c6bd..f6a269797b 100644 --- a/content/200-concepts/100-components/03-prisma-migrate/index.mdx +++ b/content/200-concepts/100-components/03-prisma-migrate/index.mdx @@ -18,7 +18,7 @@ Prisma Migrate is an **declarative database schema migration tool** that enables - Keep your database schema in sync with your [Prisma schema](/concepts/components/prisma-schema) as it evolves _and_ - Maintain existing data in your database -Prisma Migrate generates [a history of `.sql` migration files](/concepts/components/prisma-migrate/migration-histories), and plays a role in both [development and deployment](/concepts/components/prisma-migrate/migrate-development-production). +Prisma Migrate generates [a history of `.sql` migration files](/concepts/components/prisma-migrate/migration-histories), and plays a role in both [development and production](/concepts/components/prisma-migrate/migrate-development-production). From 6f0a6cf2b1c0f9c5296b961352e5ed7e86bb7bc7 Mon Sep 17 00:00:00 2001 From: Alex Ruheni <33921841+ruheni@users.noreply.github.com> Date: Tue, 7 Nov 2023 10:07:40 +0100 Subject: [PATCH 2/4] add snippet installing ws types (#5432) --- content/300-guides/050-database/890-neon.mdx | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/content/300-guides/050-database/890-neon.mdx b/content/300-guides/050-database/890-neon.mdx index 1b74ac4d6a..0dfc244da5 100644 --- a/content/300-guides/050-database/890-neon.mdx +++ b/content/300-guides/050-database/890-neon.mdx @@ -151,6 +151,7 @@ Install the Prisma adapter for Neon, Neon serverless driver and `ws` packages: ```sh npm install @prisma/adapter-neon @neondatabase/serverless ws +npm install --save-dev @types/ws ``` Update your Prisma Client instance: @@ -171,4 +172,4 @@ const adapter = new PrismaNeon(pool) const prisma = new PrismaClient({ adapter }) ``` -You can then use Prisma Client as you normally would with full-type-safety. Prisma Migrate, introspection, and Prisma Studio will continue working as before, using the connection string defined in the Prisma schema. +You can then use Prisma Client as you normally would with full type-safety. Prisma Migrate, introspection, and Prisma Studio will continue working as before, using the connection string defined in the Prisma schema. From bbdb265453f21d2cc94a6f6a7f80c032a03d9c2b Mon Sep 17 00:00:00 2001 From: Ankur Datta <64993082+ankur-arch@users.noreply.github.com> Date: Tue, 7 Nov 2023 15:21:26 +0100 Subject: [PATCH 3/4] chore: remove mentions of Data Proxy (#5377) * chore: remove mentions of data proxy * Update content/300-guides/200-deployment/301-edge/450-deploy-to-cloudflare-workers.mdx Co-authored-by: Nikolas * Update content/300-guides/200-deployment/301-edge/450-deploy-to-cloudflare-workers.mdx Co-authored-by: Nikolas * Update content/300-guides/200-deployment/301-edge/450-deploy-to-cloudflare-workers.mdx Co-authored-by: Nikolas * Update content/300-guides/200-deployment/301-edge/450-deploy-to-cloudflare-workers.mdx Co-authored-by: Jan Piotrowski * Update content/300-guides/200-deployment/301-edge/450-deploy-to-cloudflare-workers.mdx Co-authored-by: Jan Piotrowski * fix: add create method and change project name * fix: add steps to perform mirgations * fix: remove redundancy * Update content/300-guides/200-deployment/301-edge/450-deploy-to-cloudflare-workers.mdx Co-authored-by: Jan Piotrowski * Update content/300-guides/200-deployment/301-edge/450-deploy-to-cloudflare-workers.mdx Co-authored-by: Jan Piotrowski * Update content/300-guides/200-deployment/301-edge/450-deploy-to-cloudflare-workers.mdx Co-authored-by: Alex Ruheni <33921841+ruheni@users.noreply.github.com> * Update content/300-guides/200-deployment/301-edge/550-deploy-to-deno-deploy.mdx Co-authored-by: Alex Ruheni <33921841+ruheni@users.noreply.github.com> * Update content/300-guides/200-deployment/301-edge/450-deploy-to-cloudflare-workers.mdx Co-authored-by: Alex Ruheni <33921841+ruheni@users.noreply.github.com> * Update content/300-guides/200-deployment/301-edge/550-deploy-to-deno-deploy.mdx Co-authored-by: Alex Ruheni <33921841+ruheni@users.noreply.github.com> * Update content/300-guides/200-deployment/301-edge/450-deploy-to-cloudflare-workers.mdx Co-authored-by: Alex Ruheni <33921841+ruheni@users.noreply.github.com> * Update content/300-guides/200-deployment/301-edge/450-deploy-to-cloudflare-workers.mdx Co-authored-by: Alex Ruheni <33921841+ruheni@users.noreply.github.com> * Update content/300-guides/200-deployment/301-edge/450-deploy-to-cloudflare-workers.mdx Co-authored-by: Alex Ruheni <33921841+ruheni@users.noreply.github.com> * Update content/300-guides/200-deployment/301-edge/450-deploy-to-cloudflare-workers.mdx Co-authored-by: Alex Ruheni <33921841+ruheni@users.noreply.github.com> * Update content/300-guides/200-deployment/301-edge/450-deploy-to-cloudflare-workers.mdx Co-authored-by: Alex Ruheni <33921841+ruheni@users.noreply.github.com> * Update content/300-guides/200-deployment/301-edge/450-deploy-to-cloudflare-workers.mdx Co-authored-by: Jon Harrell <4829245+jharrell@users.noreply.github.com> * Update content/300-guides/200-deployment/301-edge/450-deploy-to-cloudflare-workers.mdx Co-authored-by: Alex Ruheni <33921841+ruheni@users.noreply.github.com> * Update content/300-guides/200-deployment/301-edge/450-deploy-to-cloudflare-workers.mdx Co-authored-by: Jon Harrell <4829245+jharrell@users.noreply.github.com> * update cfw example * update guide * polish the example further * iterate on example * reorder list * update deno deploy guide * Update content/300-guides/200-deployment/301-edge/550-deploy-to-deno-deploy.mdx * remove admonition * update connection string information * fix diffing issue add note about environment variables * chore: update wording * update wrangler.toml note * fix indentation * chore: add image back in * clean up steps and results --------- Co-authored-by: Nikolas Co-authored-by: Jan Piotrowski Co-authored-by: Jon Harrell <4829245+jharrell@users.noreply.github.com> Co-authored-by: Alex Ruheni <33921841+ruheni@users.noreply.github.com> Co-authored-by: ruheni --- .../450-deploy-to-cloudflare-workers.mdx | 290 ++++++++---------- .../301-edge/550-deploy-to-deno-deploy.mdx | 167 ++++------ 2 files changed, 183 insertions(+), 274 deletions(-) diff --git a/content/300-guides/200-deployment/301-edge/450-deploy-to-cloudflare-workers.mdx b/content/300-guides/200-deployment/301-edge/450-deploy-to-cloudflare-workers.mdx index 83349cafa6..b25b852b17 100644 --- a/content/300-guides/200-deployment/301-edge/450-deploy-to-cloudflare-workers.mdx +++ b/content/300-guides/200-deployment/301-edge/450-deploy-to-cloudflare-workers.mdx @@ -1,89 +1,48 @@ --- title: 'Deploy to Cloudflare Workers' metaTitle: 'Deploy to Cloudflare Workers' -metaDescription: 'Learn how to deploy a TypeScript application to Cloudflare Workers that connects to MongoDB Atlas.' +metaDescription: 'Learn how to deploy a TypeScript application to Cloudflare Workers that connects to PostgreSQL.' --- -Today you'll be building and deploying a Cloudflare Worker that uses Prisma to save every request to a MongoDB database for inspection later. +Today you'll be deploying a Cloudflare Worker that uses Prisma to save every request to a PostgreSQL database and fetches 20 of the most recent logs. -This guide covers Prisma, TypeScript, MongoDB, Data Proxy, and Cloudflare Workers from the ground up. Let's get started! - - - -**Note**

-We are continuously testing the Data Proxy with Cloudflare Workers. [Open an issue](https://github.com/prisma/prisma/issues/new/choose) if you run into problems or have questions about deploying to Cloudflare Workers. - -
+This guide covers Prisma, TypeScript, PostgreSQL, Prisma Accelerate, and Cloudflare Workers.
## Prerequisites -- Free [MongoDB Atlas](https://www.mongodb.com/cloud/atlas) account -- Free [Cloudflare Workers](https://workers.cloudflare.com/) account -- Free [GitHub](https://github.com/) account -- Node.js & NPM installed +- A PostgreSQL database that is publicly accessible +- [Cloudflare Workers](https://workers.cloudflare.com/) account +- [Prisma Data Platform](https://console.prisma.io/) account +- Node.js & npm installed - Git installed -## 1. Get a MongoDB Atlas connection string +## 1. Set up your application -After you create a MongoDB Atlas database cluster, you can get its connection string. By default, that connection string does not include a database name. +Wrangler is the official Cloudflare Worker CLI. You will use it to develop and deploy to Cloudflare Workers. This guide uses [Wrangler v3](https://developers.cloudflare.com/workers/wrangler/). -When you import your project in the Prisma Data Platform at [step 6](#6-import-your-project-into-the-prisma-data-platform), you must provide a connection string that includes a database name. - -However, you do not need to manually create a database in MongoDB Atlas. The project creation workflow in the Prisma Data Platform will create a database with the name you define in the connection string. - -1. [Create a free shared cluster](https://www.mongodb.com/docs/atlas/tutorial/create-new-cluster/) in MongoDB Atlas. -2. On the _Security Quickstart_ screen, complete the initial security configuration. - 1. Add a new database user. - 2. Click **Add My Current IP Address** so that you can connect to the MongoDB shared cluster from your current system. - 3. Click **Finish and Close**. -3. [Get the database cluster connection string](https://www.mongodb.com/docs/guides/atlas/connection-string/). -4. Paste the connection string in a text editor and add the collection name `Log`. - - The code sample below shows a connection string, that is originally provided by MongoDB Atlas, with the database name now added. - - ```diff - # The first line is a default-style MongoDB Atlas connection string. - # The second line includes the inserted `Log` database name. - - mongodb+srv://:@cluster.mongodb.net/?retryWrites=true&w=majority - + mongodb+srv://:@cluster.mongodb.net/Log?retryWrites=true&w=majority - ``` - -You now have a complete connection string. You will paste the connection string when you create your project in [6. Import your project into the Prisma Data Platform](#6-import-your-project-into-the-prisma-data-platform). - -For security reasons, do not keep the connection string in the text editor or save it in a text file. - -## 2. Set up your application - -Open your terminal and navigate to a location of your choice. Run the following commands to set up your application. +Open your terminal and navigate to a location of your choice. First, initialize your project using the [create-cloudflare-cli](https://www.npmjs.com/package/create-cloudflare). To do this, run the following command in your terminal: ```terminal -mkdir prisma-mongodb-cloudflare -cd prisma-mongodb-cloudflare -npm init -y -npm install -D prisma typescript wrangler +npm create cloudflare@latest ``` -## 3. Set up Wrangler - -Wrangler is the official Cloudflare Worker CLI. You will use it to develop and deploy to Cloudflare Workers. This guide uses [Wrangler v2](https://developers.cloudflare.com/workers/wrangler/). - -First, initialize Wrangler. To do this, run the following command in your terminal: +This will ask you a few questions. ```terminal -npx wrangler init +In which directory do you want to create your application? ``` -This will ask you a few questions. +Enter the name of your project, for example: `prisma-cloudflare-accelerate` ```terminal -Would you like to use git to manage this Worker? (y/n) +What type of application do you want to create? ``` -We want to use Git, so answer yes. +Select the `"Hello World" Worker` option. ```terminal Would you like to use TypeScript? (y/n) @@ -92,12 +51,12 @@ Would you like to use TypeScript? (y/n) We also want to use TypeScript, so answer yes. ```terminal -Would you like to create a Worker at src/index.ts? +Would you like to use git to manage this Worker? (y/n) ``` -Select the `Fetch Handler` option. +We want to use Git, so answer yes. -Once you're done, this will create a `wrangler.toml` file with some initial configuration. +The command this will create a new project with a minimal preset configuration. Once `create-cloudflare-cli` is done, navigate to the project and open it on your editor of choice. Next, authenticate the Wrangler CLI with your Cloudflare Workers account. To do this, run the following command in your terminal: @@ -111,10 +70,18 @@ You can now verify that you're logged in by running `npx wrangler whoami`. npx wrangler whoami ``` -## 4. Set up Prisma +## 2. Set up Prisma Now you're ready to add Prisma to the project. +Install `prisma` as a development dependency: + +```terminal +npm install --save-dev prisma +``` + +Next, initialize Prisma in your project with the following command: + ```terminal npx prisma init ``` @@ -125,11 +92,11 @@ This creates a Prisma schema in `prisma/schema.prisma`. **Note:**

-This process also creates an `.env` file, but this file has no effect when you use Cloudflare Workers. +`prisma init` also creates an `.env` file. The `.env` file will contain a placeholder `DATABASE_URL` variable that will be used to update your database schema using Prisma Migrate. Update this value with your database's connection string. -Inside `prisma/schema.prisma`, add the following schema: +Update your Prisma schema with the following data model: ```prisma generator client { @@ -137,12 +104,12 @@ generator client { } datasource db { - provider = "mongodb" + provider = "postgresql" url = env("DATABASE_URL") } model Log { - id String @id @default(auto()) @map("_id") @db.ObjectId + id Int @id @default(autoincrement()) level Level message String meta Json @@ -155,92 +122,84 @@ enum Level { } ``` -This data model will be used to store incoming requests from your Worker. +The above data model will be used to persist and retrieve logs from your Cloudflare Worker -## 5. Create a repository and push to GitHub +## 3. Update your database schema -To prepare for the steps ahead, let's [create a private repository](https://github.com/new) on GitHub. - -![Create a private repository](../../../doc-images/guides/deploy/create-repo.png) - -Next, initialize your repository, then push your changes up to GitHub. +To map your data model to the database schema, you need to use the `prisma migrate dev` CLI command: ```terminal -git remote add origin https://github.com//prisma-mongodb-cloudflare -git add . -git commit -m "initial commit" -git push -u origin main +npx prisma migrate dev --name init ``` -You're ready to import your project into the Prisma Data Platform. - -## 6. Import your Project into the Prisma Data Platform +The command does two things: -With Cloudflare Workers, you can't directly access your database because there is no TCP support. Fortunately, Prisma has your back with the [Data Proxy](/data-platform/classic-projects/data-proxy). +1. It creates a new SQL migration file for this migration +1. It runs the SQL migration file against the database -1. To get started, sign up for a free [Prisma Data Platform account](https://cloud.prisma.io/). +## 4. Enable Accelerate in the Prisma Data Platform - +Prisma currently does not work on Cloudflare Workers yet. However, you can use Prisma on Cloudflare Workers through [Prisma Accelerate](/data-platform/accelerate). - **Note**

- A GitHub account is required to sign up for the Prisma Data Platform. +To get started with Prisma Accelerate: -
+1. Sign up for a free [Prisma Data Platform account](https://console.prisma.io/) +1. Create a project +1. Navigate to the project you created +1. Enable Accelerate +1. Generate an Accelerate connection string and copy it to your clipboard - ![Signup for Prisma Data Platform](../../../doc-images/data-platform/pdp-signup.png) +## 5. Configure the Accelerate connection string in your project -2. Click **New Project** and then select **Import a Prisma repository**. -3. Fill in the repository and project details, and click **Next**. +1. Rename the existing `DATABASE_URL` environment variable to `DIRECT_URL`. The `DIRECT_URL` variable will be used perform migrations and introspections. +1. Add the Prisma Accelerate connection string to your `.env` file. - ![Import a Project](./images/450-03-import-project.png) - -4. Next, you connect the Prisma Data Platform to the MongoDB Atlas database and set up the Data Proxy. - - 1. Paste the MongoDB Atlas connection string which also includes the database name as described in [1. Get a MongoDB Atlas connection string](#1-get-a-mongodb-atlas-connection-string). - 2. Under **Location**, select a Data Proxy location that is geographically close to your MongoDB database location. - 3. Enable **Static IPs** and copy and paste them in the _Network Access_ screen in MongoDB Atlas. - - ![Connect your Database](./images/450-04-connect-db.png) - - 4. Click **Create Project** to test the connection and set up the Data Proxy. - - + ```diff file=.env + -DATABASE_URL="postgres://..." + +DATABASE_URL="prisma://accelerate.prisma-data.net/?api_key=__API_KEY__" + +DIRECT_URL="postgres://..." + ``` - If you see, "The database needs to be empty to proceed", you can simply use a different database name. Using the screenshot above, that would be renaming `Log` to something else. + Add [`directUrl`](/reference/api-reference/prisma-schema-reference#fields) property in `datasource` block in the `schema.prisma` file. - + ```prisma highlight=4;add file=prisma/schema.prisma + datasource db { + provider = "postgresql" + url = env("DATABASE_URL") + directUrl = env("DIRECT_URL") + } + ``` - If all goes well, you'll be greeted with a new connection string that starts with `prisma://`. + > The `directUrl` field is not required for Prisma Accelerate. It allows you to introspect and perform schema migrations. - 5. Copy the `prisma://` connection string to your clipboard. +1. In `wrangler.toml` file, add a `[vars]` key and your connection string. - ![Data Proxy Page](./images/450-05-data-proxy.png) + ```diff file=wrangler.toml + name = "prisma-cloudflare-accelerate" + main = "src/main.ts" + compatibility_date = "2022-11-07" -## 7. Set the Data Proxy Connection string in your environment + + [vars] + + DATABASE_URL = "prisma://accelerate.prisma-data.net/?api_key=__API_KEY__" + ``` -1. Add the Data Proxy connection string to your local environment `.env` file. + - ```diff file=.env - - DATABASE_URL = "mongodb+srv://:@cluster.mongodb.net/Log?retryWrites=true&w=majority" - + DATABASE_URL = "prisma://aws-us-east-1.prisma-data.com/?api_key=•••••••••••••••••" - ``` + Cloudflare Workers does not support `.env` files. To set environment variables, you can either adding the `[vars]` key in your `wrangler.toml` file or saving your environment variables in a `.dev.vars` file. Refer to [Cloudflare's documentation](https://developers.cloudflare.com/pages/platform/functions/bindings/#interact-with-your-environment-variables-locally) to learn more. -2. In your code editor, add the connection string in the `wrangler.toml` file. + - ```diff file=wrangler.toml - name = "prisma-mongodb-cloudflare" - main = "src/main.ts" - compatibility_date = "2022-11-07" +1. Install the Prisma Accelerate extension - + [vars] - + DATABASE_URL = "prisma://aws-us-east-1.prisma-data.com/?api_key=•••••••••••••••••" + ```bash + npm install @prisma/extension-accelerate ``` You are now ready to generate a Prisma Client. -## 8. Generate a Prisma Client +## 6. Generate a Prisma Client -Next, you'll generate a Prisma Client that connects through the [Data Proxy](/data-platform/classic-projects/data-proxy) over HTTP. +Next, generate Prisma Client that connects to your database through [Prisma Accelerate](/data-platform/accelerate) over HTTP. ```terminal npx prisma generate --no-engine @@ -248,53 +207,70 @@ npx prisma generate --no-engine -Prior to Prisma 5.2.0, the `--no-engine` flag is not available. Instead, use the `--data-proxy` flag. +The `--no-engine` flag is available from Prisma 5.2.0 and later. If you're using an earlier version of Prisma, use the `--accelerate` flag. ```terminal -npx prisma generate --data-proxy +npx prisma generate --accelerate ``` The generated Client has a smaller bundle size and is optimized for edge environments like Cloudflare Workers. -The smaller bundle size is due to the fact that the interfaces talking to the database (the [Prisma engines](/concepts/components/prisma-engines)) are no longer bundled with Prisma Client as this logic is now handled by the Data Proxy. +The smaller bundle size is due to the fact that the interfaces talking to the database (the [Prisma engines](/concepts/components/prisma-engines)) are no longer bundled with Prisma Client as this logic is now handled by Prisma Accelerate. -## 9. Develop the Cloudflare Worker function +## 7. Develop the Cloudflare Worker function You're now ready to create a Cloudflare Worker. Create a `src/index.ts` file with the following code: ```ts import { PrismaClient } from '@prisma/client/edge' -const prisma = new PrismaClient() - -addEventListener('fetch', (event) => { - event.respondWith(handleEvent(event)) -}) - -async function handleEvent(event: FetchEvent): Promise { - const { request } = event - - // waitUntil method is used for sending logs, after response is sent - event.waitUntil( - prisma.log - .create({ - data: { - level: 'Info', - message: `${request.method} ${request.url}`, - meta: { - headers: JSON.stringify(request.headers), - }, +import { withAccelerate } from '@prisma/extension-accelerate' + +export interface Env { + DATABASE_URL: string +} + +export default { + async fetch( + request: Request, + env: Env, + ctx: ExecutionContext + ): Promise { + const prisma = new PrismaClient({ + datasourceUrl: env.DATABASE_URL, + }).$extends(withAccelerate()) + + await prisma.log.create({ + data: { + level: 'Info', + message: `${request.method} ${request.url}`, + meta: { + headers: JSON.stringify(request.headers), + }, + }, + }) + + const { data, info } = await prisma.log + .findMany({ + take: 20, + orderBy: { + id: 'desc', }, }) - .then() - ) + .withAccelerateInfo() - return new Response(`request method: ${request.method}!`) + console.log(JSON.stringify(info)) + + return new Response(`request method: ${request.method}!`) + }, } ``` -Run `npx wrangler dev` to see your worker in development: +> The [`info`](data-platform/accelerate/api-reference#return-type) object has additional information which can be useful for debugging. +> Accelerate can also be used to cache your query results. You can find more information on caching with Prisma Accelerate in [here](/data-platform/accelerate). + +Run `npm run dev` to see your worker in development: ``` 👂 Listening on http://127.0.0.1:8787 @@ -306,26 +282,22 @@ Go ahead and open `http://127.0.0.1:8787`. If all goes well, you should see: request method: GET! ``` -Refresh the page a couple times to verify that it's working. Now if you click on the **Data Browser** tab on your Prisma Cloud project, you should see `Info` logs written to your database. +Refresh the page a couple times to verify that it's working. -![Prisma Data Browser](../../../doc-images/data-platform/data-browser/data-browser-simple-app-data.png) - -It's working locally! - -## 10. Publish to Cloudflare Workers +## 8. Publish to Cloudflare Workers You're now ready to deploy to Cloudflare Workers. Run the following command: ```terminal -npx wrangler publish +npm run deploy ``` -This will pack your application with webpack and upload to Cloudflare. With a bit of luck, you'll see the following: +This will package and upload to Cloudflare. With a bit of luck, you'll see the following: ``` ✨ Built successfully, built project size is 94 KiB. ✨ Successfully published your script to -https://prisma-mongodb-cloudflare.mattm.workers.dev +https://prisma-cloudflare-accelerate.ankman.workers.dev ``` Visit your deployment URL and you'll again see: @@ -334,6 +306,4 @@ Visit your deployment URL and you'll again see: request method: GET! ``` -You're all set! You've successfully deployed a Cloudflare Worker written in TypeScript that uses Prisma to talk to your MongoDB database. - -Give yourself a pat on the back, you deserve it! +You're all set! You've successfully deployed a Cloudflare Worker written in TypeScript that uses Prisma to talk to your PostgreSQL database. diff --git a/content/300-guides/200-deployment/301-edge/550-deploy-to-deno-deploy.mdx b/content/300-guides/200-deployment/301-edge/550-deploy-to-deno-deploy.mdx index 22159e42b1..b69b11c4dc 100644 --- a/content/300-guides/200-deployment/301-edge/550-deploy-to-deno-deploy.mdx +++ b/content/300-guides/200-deployment/301-edge/550-deploy-to-deno-deploy.mdx @@ -8,7 +8,7 @@ metaDescription: 'Learn how to deploy a TypeScript application to Deno Deploy.' With this guide, you can learn how to build and deploy a simple application to [Deno Deploy](https://deno.com/deploy). The application uses Prisma to save a log of each request to a PostgreSQL database. -This guide covers the use of Prisma CLI with Deno CLI, Deno Deploy, Prisma Client, and Data Proxy. +This guide covers the use of Prisma CLI with Deno CLI, Deno Deploy, Prisma Client, and Prisma Accelerate. @@ -20,19 +20,19 @@ This guide demonstrates how to deploy an application to Deno Deploy in conjuncti ## Prerequisites -- a free [GitHub](https://github.com/) account +- a free [Prisma Data Platform](https://console.prisma.io) account - a free [Deno Deploy](https://deno.com/deploy) account - a PostgreSQL database - Node.js & npm installed -- git installed - Deno v1.29.4 or later installed. [Learn more](https://deno.land/manual/getting_started/installation). +- (Recommended) Latest version of Prisma ORM. - (Recommended) Deno extension for VS Code. [Learn more](https://deno.land/manual/getting_started/setup_your_environment#visual-studio-code). ## 1. Set up your application To start, you create a directory for your project, and then use `deno run` to initialize your application with `prisma init` as an [npm package with npm specifiers](https://deno.land/manual/node/npm_specifiers). -### Steps +To set up your application: 1. Open your terminal and navigate to a location of your choice. 2. Run the following commands to set up your application. @@ -81,21 +81,20 @@ To start, you create a directory for your project, and then use `deno run` to in With the data model in place and your database connection configured, you can now apply the data model to your database. -### Steps - ```terminal -deno run -A npm:prisma db push +deno run -A npm:prisma migrate dev --name init ``` -### Result +The command does two things: -With `prisma db push`, you apply the data model in `schema.prisma` to your database. +1. It creates a new SQL migration file for this migration +1. It runs the SQL migration file against the database At this point, the command has two additional side effects. The command installs Prisma Client and creates the `package.json` file for the project, which includes the `@prisma/client` package as a dependency. -## 3. Generate Prisma Client for the Data Proxy +## 3. Generate Prisma Client for Prisma Accelerate -Next, generate Prisma Client for the Data Proxy with the `--no-engine` flag. Later, you use the [Data Proxy](/data-platform/classic-projects/data-proxy) to connect to your database over HTTP. +Next, generate Prisma Client for the Prisma Accelerate with the `--no-engine` flag. Later, you will use [Prisma Accelerate](/data-platform/accelerate/) to connect to your database over HTTP. ```terminal deno run -A --unstable npm:prisma generate --no-engine @@ -103,25 +102,19 @@ deno run -A --unstable npm:prisma generate --no-engine -Prior to Prisma 5.2.0, the `--no-engine` flag is not available. Instead, use the `--data-proxy` flag. +Prior to Prisma 5.2.0, the `--no-engine` flag is not available. Instead, use the `--accelerate` flag. ```terminal -deno run -A npm:prisma generate --data-proxy +deno run -A npm:prisma generate --accelerate ``` -### Result - -You now have a database schema and a locally generated Prisma Client for the Data Proxy. +You now have a database schema and a locally generated Prisma Client for the Prisma Accelerate. ## 4. Create your application -You can now create a local Deno application. - -### Steps - -Create `index.ts` in the root folder of your project and add the content below. +You can now create a local Deno application. Create `index.ts` in the root folder of your project and add the content below: ```ts import { serve } from 'https://deno.land/std@0.140.0/http/server.ts' @@ -158,116 +151,66 @@ If you use VS Code and see the error `An import path cannot end with a '.ts' ext ### What's next -You cannot run this script yet, because you do not yet have the required Data Proxy credentials to use Prisma Client with your database. Later in this guide, you will obtain the required credentials when you next add your application to the Prisma Data Platform. +You cannot run this script yet, because you do not yet have the required Prisma Accelerate connection string to use Prisma Client with your database. Later in this guide, you will obtain the required credentials when you next add your application to the Prisma Data Platform. After that, you test your application locally. -## 5. Create a project in the Prisma Data Platform - -Sign up for the Prisma Data Platform and create a project for your application so that you can enable the [Data Proxy](/data-platform/classic-projects/data-proxy) for it. - -### Steps - -1. Sign up for a free [Prisma Data Platform account](https://cloud.prisma.io/). - - - - **Note**

- You need a GitHub account to sign up for the Prisma Data Platform. - -
- - ![Signup for Prisma Data Platform](../../../doc-images/data-platform/pdp-signup.png) - -1. Click **New Project**. -1. Connect the Prisma Data Platform to your database and enable the Data Proxy. +## 5. Enable Accelerate in the Prisma Data Platform - 1. Paste your PostgreSQL connection string. - 1. (Optional) If your database provider requires it, for **Static IPs** select **Enabled** to enable connections to your database from static IPs and add them to the database allowlist. - 1. Under **Choose a Data Proxy region**, select a Data Proxy location that is geographically close to your database. - 1. Click **Create project**. +To get started with Prisma Accelerate: - If the connection to the database is successful, Prisma Data Platform creates your project and redirects your browser to the **Get started** page. On the **Get started** page, you can [optionally link your GitHub repository](/data-platform/classic-projects/platform/projects/create#optional-enable-schema-synchronization) to keep your Prisma schema up-to-date.

- For a project in Prisma Data Platform, you need a linked Prisma schema if you plan to use [Data Browser](/data-platform/classic-projects/platform/data-browser) and [Query Console](/data-platform/classic-projects/platform/query-console).

- Deno Deploy requires a GitHub repository and you create that in [Create a repository and push to GitHub](#8-create-a-repository-and-push-to-github). +1. Sign up for a free [Prisma Data Platform account](https://console.prisma.io/) +1. Create a project +1. Navigate to the project you created +1. Enable Accelerate +1. Generate an Accelerate connection string and copy it to your clipboard - ![Prisma Data Platform - Create project - Paste database connection string, select Data Proxy region, enable static IPs](../../../doc-images/data-platform/projects/create-01-paste-connection-string.png) +## 6. Configure Prisma Accelerate in your environment -1. Create a Data Proxy connection string. +With the Accelerate connection string copied, you can replace the existing connection string that you used to create the database schema in your `.env` file. - 1. On the **Get started** screen, click **Create a new connection string**. - 1. Enter a name for the connection string and click **Create**. - 1. Copy the `prisma://` connection string to your clipboard. +Prisma Client does not read `.env` files by default on Deno, so you must also install `dotenv-cli` locally. - ![Prisma Data Platform - Create project - Paste database connection string, select Data Proxy region, enable static IPs](../../../doc-images/data-platform/projects/create-03-copy-data-proxy-connection-string.png) +To configure Prisma Accelerate: - 1. Save the connection string in a password manager or another safe location. - 1. Click **Skip and continue to Data Platform** to open the Data Browser for your project.

- When you test your application later, you come back to the Data Browser to review the records that your application creates. +1. Install the `dotenv-cli`. -### What's next - -Next in this guide, you use the connection string in your local `.env` file to connect to your database through the Data Proxy. - -## 6. Configure the Data Proxy connection string in your environment - -With the Data Proxy connection string copied, you can replace the direct PostgreSQL connection string that you used to create the database schema in your `.env` file. - -Prisma Client for the Data Proxy does not read `.env` files by default, so you must also install `dotenv-cli` locally. - -### Steps - -1. Install `dotenv-cli`. - - ```terminal + ```sh npm install dotenv-cli ``` -2. Add the Data Proxy connection string to the `.env` file. Also, comment out the direct connection string. +2. Add the Prisma Accelerate connection string to the `.env` file. Also, comment out the direct connection string. ```bash file=.env + DATABASE_URL="prisma://accelerate.prisma-data.net/?api_key=__API_KEY__" + # Previous database connection # DATABASE_URL="postgres://..." - DATABASE_URL="prisma://..." ``` -### Result - -The configuration of your local environment is now ready to send Prisma queries to the database through the Data Proxy. - -### What's next - -You are now ready to test your script locally. +The configuration of your local environment is now ready to send Prisma queries to the database through Prisma Accelerate. ## 7. Test your application locally You can now start your application locally and test the creation of log entries. -### Steps - -1. Run your script locally. - - ```terminal - npx dotenv -- deno run -A ./index.ts - ``` - -2. In a web browser, open [http://localhost:8000/](http://localhost:8000/). This page writes your request to the database. - - ``` - { - "id": 3, - "level": "Info", - "message": "GET http://localhost:8000/", - "meta": { - "headers": "{}" - } - } - ``` +```terminal +npx dotenv -- deno run -A ./index.ts +``` -3. Reload the page a few times.

Every time you reload, the script generates a new log entry and the id of the current log entry increments. If you open the [Data Browser](/data-platform/classic-projects/platform/data-browser) for your project in Prisma Data Platform, you can verify that the application writes `Info` level logs to your database. +In a web browser, open [http://localhost:8000/](http://localhost:8000/). This page writes your request to the database. - ![Prisma Data Browser](../../../doc-images/data-platform/data-browser/data-browser-simple-app-data.png) +``` +{ + "id": 3, + "level": "Info", + "message": "GET http://localhost:8000/", + "meta": { + "headers": "{}" + } +} +``` -### Result +Reload the page a few times.

Every time you reload, the script generates a new log entry and the id of the current log entry increments. This confirms that your application works when you run it from your local environment. @@ -275,10 +218,10 @@ This confirms that your application works when you run it from your local enviro You need a GitHub repository to add your project to Deno Deploy and enable automated deployments whenever you push changes. -### Steps +To set up a GitHub repository: 1. [Create a private GitHub repository](https://github.com/new). - ![Create a private repository](../../../doc-images/guides/deploy/create-repo.png) + 2. Initialize your repository locally and push your changes to GitHub, with the following commands: ```terminal @@ -299,23 +242,19 @@ Optionally, you can now also [link your GitHub repository to your project](/data ## 9. Deploy to Deno Deploy -Use the GitHub repository to add your application to Deno Deploy. - -### Steps +Use the GitHub repository to add your application to Deno Deploy: 1. Go to [https://dash.deno.com/new](https://dash.deno.com/new). 1. Select a GitHub organization or user and then select a repository. 1. Select a production branch and select **Automatic** mode so that Deno Deploy can deploy every time you push a change to the repository. 1. Select `index.ts` as the entry point to your project. -1. To define the Data Proxy connection string, click **Add Env Variable**. +1. To define the Accelerate connection string, click **Add Env Variable**. 1. For **KEY**, enter `DATABASE_URL`. - 1. For **VALUE**, paste the Data Proxy connection string. + 1. For **VALUE**, paste the Accelerate connection string. ![Deno Deploy - project parameters](./images/550-02-deploy-to-deno-project-parameters.png) 1. Click **Link**.
Wait for the first Deno deployment to finish. -### Result - When the first deployment finishes, your browser is redirected to the project view. ### What's next @@ -337,4 +276,4 @@ The application shows a similar result as when you tested locally with a further ## Summary -You successfully deployed a Deno application that you created in TypeScript, which uses Prisma Client for the Data Proxy to connect to a PostgreSQL database. +You successfully deployed a Deno application that you created in TypeScript, which uses Prisma Client for the Prisma Accelerate to connect to a PostgreSQL database. From da7e9542502e920a6c14a021aed1d74c6fcd47ff Mon Sep 17 00:00:00 2001 From: Alex Ruheni <33921841+ruheni@users.noreply.github.com> Date: Tue, 7 Nov 2023 15:50:34 +0100 Subject: [PATCH 4/4] chore: add section on community-maintained driver adapters (#5434) --- content/200-concepts/100-components/database-drivers.mdx | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/content/200-concepts/100-components/database-drivers.mdx b/content/200-concepts/100-components/database-drivers.mdx index 6d7a022377..7c5a3c6c22 100644 --- a/content/200-concepts/100-components/database-drivers.mdx +++ b/content/200-concepts/100-components/database-drivers.mdx @@ -28,6 +28,10 @@ Prisma will use the Query Engine to transform the Prisma Client query to SQL and - [Turso](/guides/database/turso#connect-and-query-your-primary-database) +## Community maintained database driver adapters + +- [TiDB](https://github.com/tidbcloud/prisma-adapter) + ### How to use driver adapters To use this feature: @@ -48,7 +52,7 @@ To use this feature: ``` 3. Refer to the following pages to learn more how to use the specific driver adapters with the specific database providers: - + - [Neon](/guides/database/neon#how-to-use-the-neon-serverless-driver-with-prisma-preview) - [PlanetScale](/guides/database/planetscale#how-to-use-the-planetscale-serverless-driver-with-prisma-preview) - [Turso](/guides/database/turso#connect-and-query-your-primary-database)