diff --git a/databases/prisma-postgres/README.md b/databases/prisma-postgres/README.md index 2979ee8c7bba..c0bcea3bbbae 100644 --- a/databases/prisma-postgres/README.md +++ b/databases/prisma-postgres/README.md @@ -1,140 +1,57 @@ -# Prisma Postgres Example: Queries, Connection Pooling & Caching +# Prisma Postgres -This project contains a sample application demonstrating various capabilities and workflows of [Prisma Postgres](https://prisma.io/data-platform/postgres): +This example shows how to use [Prisma ORM](https://www.prisma.io/orm) with [Prisma Postgres](https://prisma.io/postgres). -- Schema migrations and queries (via [Prisma ORM](https://www.prisma.io/orm)) -- Connection pooling and caching (via [Prisma Accelerate](https://prisma.io/data-platform/accelerate)) +## Getting Started -## Getting started +### 1. Download the example & install dependencies -### 1. Set up a Prisma Postgres database in Prisma Data Platform - -Follow these steps to create your Prisma Postgres database: - -1. Log in to [Prisma Data Platform](https://console.prisma.io/). -1. In a [workspace](https://www.prisma.io/docs/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 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! - -Then, find your database credentials in the **Set up database access** section, copy the `DATABASE_URL` environment variable and store it securely. - -```bash no-copy -DATABASE_URL= -``` - -> These `DATABASE_URL` environment variable will be required in the next steps. - -Once that setup process has finished, move to the next step. - -### 2. Download example and install dependencies - -Copy the `try-prisma` command that', paste it into your terminal, and execute it: - -```terminal -npx try-prisma@latest \ - --template databases/prisma-postgres \ - --name hello-prisma \ - --install npm -``` - - - -Navigate into the project directory and (if you haven't done so via the CLI wizard) install dependencies: - -```terminal -cd hello-prisma -npm install -``` - -### 3. Set database connection - -The connection to your database is configured via environment variables in a `.env` file. - -First, rename the existing `.env.example` file to just `.env`: - -```terminal -mv .env.example .env -``` - -Then, 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: +Clone this repository and install dependencies: ```bash -DATABASE_URL="prisma+postgres://accelerate.prisma-data.net/?api_key=ey...." +npx try-prisma@latest --template databases/prisma-postgres ``` -### 4. Create database tables (with a schema migration) +Then navigate into the project directory and install dependencies: -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 +```bash +cd prisma-postgres +bun install ``` -This will map the `User` and `Post` models that are defined in your [Prisma schema](./prisma/schema.prisma) to your database. You can also review the SQL migration that was executed and created the tables in the newly created `prisma/migrations` directory. +### 2. Create a Prisma Postgres database -### 5. Execute queries with Prisma ORM +Run the following command to create a Prisma Postgres database: -The [`src/queries.ts`](./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 +```bash +npx create-db@latest ``` -### 6. Explore caching with Prisma Accelerate +Copy the `DATABASE_URL` from the output and add it to a `.env` file: -The [`src/caching.ts`](./src/caching.ts) script contains a sample query that uses [Stale-While-Revalidate](https://www.prisma.io/docs/accelerate/caching#stale-while-revalidate-swr) (SWR) and [Time-To-Live](https://www.prisma.io/docs/accelerate/caching#time-to-live-ttl) (TTL) to cache a database query using Prisma Accelerate. You can execute it as follows: - -```terminal -npm run caching +```bash +DATABASE_URL="postgresql://..." ``` -Take note of the time that it took to execute the query, e.g.: +> **Tip:** Claim your database at the provided URL to keep it permanently. -```terminal -The query took 2009.2467149999998ms. -``` +### 3. Push the schema & generate Prisma Client -Now, run the script again: +Push the schema to the database and generate Prisma Client: -```terminal -npm run caching +```bash +npx prisma db push +npx prisma generate ``` -You'll notice that the time the query took will be a lot shorter this time, e.g.: +### 4. Run the example -```terminal -The query took 300.5655280000001ms. +```bash +bun run dev ``` ## Next steps -- Check out the [Prisma docs](https://www.prisma.io/docs) -- [Join our community on Discord](https://pris.ly/discord?utm_source=github&utm_medium=prisma_examples&utm_content=next_steps_section) to share feedback and interact with other users. -- [Subscribe to our YouTube channel](https://pris.ly/youtube?utm_source=github&utm_medium=prisma_examples&utm_content=next_steps_section) for live demos and video tutorials. -- [Follow us on X](https://pris.ly/x?utm_source=github&utm_medium=prisma_examples&utm_content=next_steps_section) for the latest updates. -- Report issues or ask [questions on GitHub](https://pris.ly/github?utm_source=github&utm_medium=prisma_examples&utm_content=next_steps_section). +- [Prisma Postgres documentation](https://www.prisma.io/docs/postgres) +- [Prisma ORM documentation](https://www.prisma.io/docs/orm) +- [Join the Prisma Discord](https://pris.ly/discord) diff --git a/databases/prisma-postgres/package.json b/databases/prisma-postgres/package.json index acd0691ea596..2d9bda277aa5 100644 --- a/databases/prisma-postgres/package.json +++ b/databases/prisma-postgres/package.json @@ -1,18 +1,18 @@ { - "name": "hello-prisma", + "name": "prisma-postgres-example", "license": "MIT", "scripts": { - "queries": "tsx ./src/queries.ts", - "caching": "tsx ./src/caching.ts" + "dev": "tsx src/index.ts" }, "dependencies": { - "@prisma/client": "7.0.0", - "@types/node": "22.18.12", - "dotenv": "16.6.1" + "@prisma/adapter-pg": "^7.1.0", + "@prisma/client": "^7.1.0", + "dotenv": "^17.2.3" }, "devDependencies": { - "prisma": "7.0.0", - "typescript": "5.8.2", - "tsx": "^4.20.6" + "@types/node": "^22.15.21", + "prisma": "^7.1.0", + "tsx": "^4.19.4", + "typescript": "^5.8.3" } } \ No newline at end of file diff --git a/databases/prisma-postgres/src/caching.ts b/databases/prisma-postgres/src/caching.ts deleted file mode 100644 index 930e297af68c..000000000000 --- a/databases/prisma-postgres/src/caching.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { PrismaClient } from '../prisma/generated/client'; - -const prisma = new PrismaClient({ - accelerateUrl: process.env.DATABASE_URL, -}); - -async function main() { - - const startTime = performance.now(); - - // Learn more about caching strategies: - // https://www.prisma.io/docs/accelerate/caching - const cachedUsersWithPosts = await prisma.user.findMany({ - where: { - email: { contains: "alice" } - }, - include: { posts: true }, - cacheStrategy: { - swr: 30, // 30 seconds - ttl: 60 // 60 seconds - } - }); - - const endTime = performance.now(); - - // Calculate the elapsed time - const elapsedTime = endTime - startTime; - - console.log(`The query took ${elapsedTime}ms.`); - console.log(`It returned the following data: \n`, cachedUsersWithPosts); - -} - -main() - .then(async () => { - await prisma.$disconnect(); - }) - .catch(async (e) => { - console.error(e); - await prisma.$disconnect(); - process.exit(1); - }); diff --git a/databases/prisma-postgres/src/index.ts b/databases/prisma-postgres/src/index.ts new file mode 100644 index 000000000000..7944fd9124c1 --- /dev/null +++ b/databases/prisma-postgres/src/index.ts @@ -0,0 +1,43 @@ +import "dotenv/config"; +import { PrismaClient } from "../prisma/generated/client"; +import { PrismaPg } from "@prisma/adapter-pg"; + +const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL }); +const prisma = new PrismaClient({ adapter }); + +async function main() { + // Create a user with a post + const user = await prisma.user.create({ + data: { + email: `alice${Date.now()}@prisma.io`, + name: "Alice", + posts: { + create: { + title: "Hello from Prisma Postgres!", + content: "This is my first post", + published: true, + }, + }, + }, + include: { posts: true }, + }); + console.log("Created user with post:", user); + + // Query all published posts + const posts = await prisma.post.findMany({ + where: { published: true }, + include: { author: true }, + }); + console.log("All published posts:", posts); + + // Update a post + const updatedPost = await prisma.post.update({ + where: { id: user.posts[0].id }, + data: { title: "Hello from Prisma Postgres! (updated)" }, + }); + console.log("Updated post:", updatedPost); +} + +main() + .catch(console.error) + .finally(() => prisma.$disconnect()); diff --git a/databases/prisma-postgres/src/queries.ts b/databases/prisma-postgres/src/queries.ts deleted file mode 100644 index 5bcb39eba70a..000000000000 --- a/databases/prisma-postgres/src/queries.ts +++ /dev/null @@ -1,111 +0,0 @@ -import { PrismaClient } from '../prisma/generated/client'; -import 'dotenv/config'; - -const prisma = new PrismaClient({ - accelerateUrl: process.env.DATABASE_URL, -}); - -// A `main` function so that we can use async/await -async function main() { - - const user1Email = `alice${Date.now()}@prisma.io`; - const user2Email = `bob${Date.now()}@prisma.io`; - - // Seed the database with users and posts - const user1 = await prisma.user.create({ - data: { - email: user1Email, - name: 'Alice', - posts: { - create: { - title: 'Join the Prisma community on Discord', - content: 'https://pris.ly/discord', - published: true, - }, - }, - }, - include: { - posts: true, - }, - }); - const user2 = await prisma.user.create({ - data: { - email: user2Email, - name: 'Bob', - posts: { - create: [ - { - title: 'Check out Prisma on YouTube', - content: 'https://pris.ly/youtube', - published: true, - }, - { - title: 'Follow Prisma on Twitter', - content: 'https://twitter.com/prisma/', - published: false, - }, - ], - }, - }, - include: { - posts: true, - }, - }); - console.log( - `Created users: ${user1.name} (${user1.posts.length} post) and ${user2.name} (${user2.posts.length} posts) `, - ); - - // Retrieve all published posts - const allPosts = await prisma.post.findMany({ - where: { published: true }, - }); - console.log(`Retrieved all published posts: ${JSON.stringify(allPosts)}`); - - // Create a new post (written by an already existing user with email alice@prisma.io) - const newPost = await prisma.post.create({ - data: { - title: 'Join the Prisma Discord community', - content: 'https://pris.ly/discord', - published: false, - author: { - connect: { - email: user1Email, - }, - }, - }, - }); - console.log(`Created a new post: ${JSON.stringify(newPost)}`); - - // Publish the new post - const updatedPost = await prisma.post.update({ - where: { - id: newPost.id, - }, - data: { - published: true, - }, - }); - console.log(`Published the newly created post: ${JSON.stringify(updatedPost)}`); - - // Retrieve all posts by user with email alice@prisma.io - const postsByUser = await prisma.post - .findMany({ - where: { - author: { - email: user1Email - } - }, - }); - console.log(`Retrieved all posts from a specific user: ${JSON.stringify(postsByUser)}`); - -} - -main() - .then(async () => { - await prisma.$disconnect(); - }) - .catch(async (e) => { - console.error(e); - await prisma.$disconnect(); - process.exit(1); - });