Skip to content

Commit

Permalink
finalize getting started tutorial
Browse files Browse the repository at this point in the history
  • Loading branch information
nikolasburk committed Oct 23, 2024
1 parent e4667b6 commit 1d5c443
Show file tree
Hide file tree
Showing 6 changed files with 298 additions and 111 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,14 @@ pagination_next: getting-started/setup-prisma/start-from-scratch/relational-data
slugSwitch: /getting-started/setup-prisma/start-from-scratch/relational-databases-
---

Learn how to create a new Node.js or TypeScript project with a Prisma Postgres database from scratch, connecting Prisma ORM to the 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).

It covers the following workflows:
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://prisma.io/data-platform/postgres) database
- 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))
- Real-time database change events (via [Prisma Pulse](https://prisma.io/data-platform/pulse))


## Prerequisites

To successfully complete this tutorial, you need:
Expand All @@ -29,24 +27,7 @@ To successfully complete this tutorial, you need:

> See [System requirements](/orm/reference/system-requirements) for exact version requirements.
## 1. Set up a Prisma Postgres database in the PDP Console

Follow these steps to create your Prisma Postgres database:

1. Log in to [Prisma Data Platform](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.

Copy the connection string you see in the Console UI, since you will need it later. Then you can move on the next section.

## 2. Create project setup
## Create project setup

Create a project directory and navigate into it:

Expand Down Expand Up @@ -82,7 +63,9 @@ Next, set up your Prisma ORM project by creating your [Prisma Schema](/orm/prism
npx prisma init
```

This command does two things:
This command did the following:

- It created 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
- It created a [`.env`](/orm/more/development-environment/environment-variables/env-files) file in the root directory of the project, which is used for defining environment variables (such as your database connection and API keys).

- 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
- creates the [`.env` file](/orm/more/development-environment/environment-variables/env-files) in the root directory of the project, which is used for defining environment variables (such as your database connection)
In the next section, you'll learn how to connect your Prisma Postgres database to the project you just created on your file system.
Original file line number Diff line number Diff line change
Expand Up @@ -11,53 +11,44 @@ pagination_next: getting-started/setup-prisma/start-from-scratch/relational-data
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):
## Set up a Prisma Postgres database in the PDP Console

```prisma file=prisma/schema.prisma showLineNumbers
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
```
Follow these steps to create your Prisma Postgres database:

Note that the default schema created by `prisma init` uses PostgreSQL as the `provider`. For CockroachDB, you need to edit the `datasource` block to use the `prisma-postgres` provider instead:
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.

```prisma file=prisma/schema.prisma highlight=2;edit showLineNumbers
datasource db {
//edit-next-line
provider = ""
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.
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`**.

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):
Once the green **`CONNECTED`** label appears, your database is ready to use.

```no-lines
postgresql://USER:PASSWORD@HOST:PORT/DATABASE?PARAMETERS
```
In the Console UI, you'll see a code snippet for a `.env` file with two environment variables defined, looking similar to this:

Here's a short explanation of each component:
**TODO:** Add screenshot

- `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).
## Set environment variables in your local project

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/get-started-cockroachdb/), the [connection URL](/orm/reference/connection-urls) looks similar to this:
Copy both environment variables from the Console UI and paste them into your `.env` file. Your `.env` file should look similar to this:

```bash file=.env
DATABASE_URL="postgresql://<myusername>:<mypassword>@<short-id>.<region>.cockroachlabs.cloud:26257/defaultdb?sslmode=verify-full&sslrootcert=$HOME/.postgresql/root.crt&options=--<mycluster>"
```bash file=.env no-copy
DATABASE_URL="prisma+postgres://accelerate.prisma-data.net/?api_key=ey..."
PULSE_API_KEY="ey..."
```

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.
> **Note**: The `api_key` in the `DATABASE_URL` should be identical to the `PULSE_API_KEY`. Don't worry too much about the `PULSE_API_KEY` yet, we'll explain later why you need that.
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:
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:

```bash file=.env
DATABASE_URL="postgresql://root@localhost:26257?sslmode=disable"
```prisma file=prisma/schema.prisma
datasource db {
provider = "postgresql"
// highlight-next-line
url = env("DATABASE_URL")
}
```

Your connection string is displayed as part of the welcome text when starting CockroachDB from the command line.
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.
Original file line number Diff line number Diff line change
Expand Up @@ -13,49 +13,70 @@ slugSwitch: /getting-started/setup-prisma/start-from-scratch/relational-database

## 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`:
In this guide, you'll use [Prisma Migrate](/orm/prisma-migrate) to create the tables in your database.

```prisma file=prisma/schema.prisma copy showLineNumbers
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 BigInt @id @default(sequence())
id Int @id @default(autoincrement())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
title String
title String
content String?
published Boolean @default(false)
author User @relation(fields: [authorId], references: [id])
authorId BigInt
authorId Int
}
model Profile {
id BigInt @id @default(sequence())
id Int @id @default(autoincrement())
bio String?
user User @relation(fields: [userId], references: [id])
userId BigInt @unique
userId Int @unique
}
model User {
id BigInt @id @default(sequence())
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 does two things:
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
```

1. It creates a new SQL migration file for this migration
1. It runs the SQL migration file against the database
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.

:::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 🚀
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.
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,31 @@ To get started with Prisma Client, you need to install the `@prisma/client` pack
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.
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

The [`@prisma/client` npm package](/orm/prisma-client/setup-and-configuration/generating-prisma-client#the-prismaclient-npm-package) that was created in your `node_modules` is a _special_ library compared to other npm libraries.

Usually, the code of an npm package is downloaded in your project from the [npm](https://www.npmjs.com/) registry and is only updated when you explicitly call `npm install` again. The `@prisma/client` npm package is different!

It contains code (TypeScript types, methods, queries, ...) that is tailored to _your_ Prisma schema file in `prisma/schema.prisma`. This means, that whenever you make changes to your Prisma schema file, you also need to update the `@prisma/client` folder inside `node_modules`.

However, instead of doing this using an `npm install` as with other npm packages, you can do this by running the `prisma generate` command, 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 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. The commands will also regenerate Prisma Client.

:::

## 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.

Loading

0 comments on commit 1d5c443

Please sign in to comment.