Skip to content

[D1] Adding "Deploy to Cloudflare" button into D1 Getting started. #22140

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
May 6, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
158 changes: 116 additions & 42 deletions src/content/docs/d1/get-started.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,24 @@ This guide instructs you through:

- Creating your first database using D1, Cloudflare's native serverless SQL database.
- Creating a schema and querying your database via the command-line.
- Connecting a [Cloudflare Worker](/workers/) to your D1 database to query your D1 database programmatically.
- Connecting a [Cloudflare Worker](/workers/) to your D1 database using bindings, and querying your D1 database programmatically.

You can perform these tasks through the CLI or through the Cloudflare dashboard.

:::note
If you already have an existing Worker and an existing D1 database, follow this tutorial from [3. Bind your Worker to your D1 database](/d1/get-started/#3-bind-your-worker-to-your-d1-database).
:::

## Quick start

If you want to skip the steps and get started quickly, click on the button below.

[![Deploy to Cloudflare](https://deploy.workers.cloudflare.com/button)](https://deploy.workers.cloudflare.com/?url=https://github.com/cloudflare/docs-examples/tree/d1-get-started/d1/d1-get-started)

This creates a repository in your GitHub account and deploys the application to Cloudflare Workers. Use this option if you are familiar with Cloudflare Workers, and wish to skip the step-by-step guidance.

You may wish to manually follow the steps if you are new to Cloudflare Workers.

## Prerequisites

<Render file="prereqs" product="workers" />
Expand Down Expand Up @@ -80,17 +90,17 @@ For example: `CI=true npm create cloudflare@latest d1-tutorial --type=simple --g

<Steps>
1. Log in to your [Cloudflare dashboard](https://dash.cloudflare.com/) and select your account.
2. Go to your account > **Workers & Pages** > **Overview**.
2. Go to your account > **Compute (Workers)** > **Workers & Pages**.
3. Select **Create**.
4. Select **Create Worker**.
4. Under **Start from a template**, select **Hello world**.
5. Name your Worker. For this tutorial, name your Worker `d1-tutorial`.
6. Select **Deploy**.
</Steps>
</TabItem> </Tabs>

## 2. Create a database

A D1 database is conceptually similar to many other databases: a database may contain one or more tables, the ability to query those tables, and optional indexes. D1 uses the familiar [SQL query language](https://www.sqlite.org/lang.html) (as used by SQLite).
A D1 database is conceptually similar to many other SQL databases: a database may contain one or more tables, the ability to query those tables, and optional indexes. D1 uses the familiar [SQL query language](https://www.sqlite.org/lang.html) (as used by SQLite).

To create your first D1 database:

Expand All @@ -103,37 +113,46 @@ To create your first D1 database:
cd d1-tutorial
```

2. Run the following `wrangler d1` command and give your database a name. In this tutorial, the database is named `prod-d1-tutorial`:
2. Run the following `wrangler@latest d1` command and give your database a name. In this tutorial, the database is named `prod-d1-tutorial`:

:::note
The [Wrangler command-line interface](/workers/wrangler/) is Cloudflare's tool for managing and deploying Workers applications and D1 databases in your terminal. It was installed when you used `npm create cloudflare@latest` to initialize your new project.

While Wrangler gets installed locally to your project, you can use it outside the project by using the command `npx wrangler`.
:::

```sh
npx wrangler d1 create prod-d1-tutorial
npx wrangler@latest d1 create prod-d1-tutorial
```

```sh output

✅ Successfully created DB 'prod-d1-tutorial'
✅ Successfully created DB 'prod-d1-tutorial' in region WEUR
Created your new D1 database.

[[d1_databases]]
binding = "DB" # available in your Worker on env.DB
database_name = "prod-d1-tutorial"
database_id = "<unique-ID-for-your-database>"
```
{
"d1_databases": [
{
"binding": "DB",
"database_name": "prod-d1-tutorial",
"database_id": "<unique-ID-for-your-database>"
}
]
}

</Steps>
```

This creates a new D1 database and outputs the [binding](/workers/runtime-apis/bindings/) configuration needed in the next step.

:::note

The `wrangler` command-line interface is Cloudflare's tool for managing and deploying Workers applications and D1 databases in your terminal. It was installed when you used `npm create cloudflare@latest` to initialize your new project.
</Steps>

:::
This creates a new D1 database and outputs the [binding](/workers/runtime-apis/bindings/) configuration needed in the next step.

</TabItem> <TabItem label='Dashboard'>

<Steps>
1. Go to **Storage & Databases** > **D1**.
2. Select **Create**.
1. Go to **Storage & Databases** > **D1 SQL Database**.
2. Select **Create Database**.
3. Name your database. For this tutorial, name your D1 database `prod-d1-tutorial`.
4. (Optional) Provide a location hint. Location hint is an optional parameter you can provide to indicate your desired geographical location for your database. Refer to [Provide a location hint](/d1/configuration/data-location/#provide-a-location-hint) for more information.
5. Select **Create**.
Expand Down Expand Up @@ -198,7 +217,7 @@ You can also bind your D1 database to a [Pages Function](/pages/functions/). For
You create bindings by adding them to the Worker you have created.

<Steps>
1. Go to **Workers & Pages** > **Overview**.
1. Go to **Compute (Workers)** > **Workers & Pages**.
2. Select the `d1-tutorial` Worker you created in [step 1](/d1/get-started/#1-create-a-worker).
3. Select **Settings**.
4. Scroll to **Bindings**, then select **Add**.
Expand All @@ -217,11 +236,11 @@ You create bindings by adding them to the Worker you have created.

## 4. Run a query against your D1 database

### Configure your D1 database
### Populate your D1 database

<Tabs syncKey='CLIvDash'> <TabItem label='CLI'>

After correctly preparing your [Wrangler configuration file](/workers/wrangler/configuration/), set up your database. Use the example `schema.sql` file below to initialize your database.
After correctly preparing your [Wrangler configuration file](/workers/wrangler/configuration/), set up your database. Create a `schema.sql` file using the SQL syntax below to initialize your database.

<Steps>
1. Copy the following code and save it as a `schema.sql` file in the `d1-tutorial` Worker directory you created in step 1:
Expand All @@ -237,16 +256,28 @@ After correctly preparing your [Wrangler configuration file](/workers/wrangler/c
```sh
npx wrangler d1 execute prod-d1-tutorial --local --file=./schema.sql
```
```output
⛅️ wrangler 4.13.2
-------------------

🌀 Executing on local database prod-d1-tutorial (<DATABASE_ID>) from .wrangler/state/v3/d1:
🌀 To execute on your remote database, add a --remote flag to your wrangler command.
🚣 3 commands executed successfully.
```

:::note
The command `npx wrangler d1 execute` initializes your database locally, not on the remote database.
:::

3. Validate your data is in your database by running:
3. Validate that your data is in the database by running:

```sh
npx wrangler d1 execute prod-d1-tutorial --local --command="SELECT * FROM Customers"
```

```sh output
🌀 Mapping SQL input into an array of statements
🌀 Executing on local database production-db-backend (5f092302-3fbd-4247-a873-bf1afc5150b) from .wrangler/state/v3/d1:
🌀 Executing on local database production-db-backend (<DATABASE_ID>) from .wrangler/state/v3/d1:
┌────────────┬─────────────────────┬───────────────────┐
│ CustomerId │ CompanyName │ ContactName │
├────────────┼─────────────────────┼───────────────────┤
Expand All @@ -267,7 +298,7 @@ After correctly preparing your [Wrangler configuration file](/workers/wrangler/c
Use the Dashboard to create a table and populate it with data.

<Steps>
1. Go to **Storage & Databases** > **D1**.
1. Go to **Storage & Databases** > **D1 SQL Database**.
2. Select the `prod-d1-tutorial` database you created in [step 2](/d1/get-started/#2-create-a-database).
3. Select **Console**.
4. Paste the following SQL snippet.
Expand Down Expand Up @@ -329,9 +360,9 @@ After you have set up your database, run an SQL query from within your Worker.

In the code above, you:

1. Define a binding to your D1 database in your TypeScript code. This binding matches the `binding` value you set in the [Wrangler configuration file](/workers/wrangler/configuration/) under `[[d1_databases]]`.
1. Define a binding to your D1 database in your code. This binding matches the `binding` value you set in the [Wrangler configuration file](/workers/wrangler/configuration/) under `d1_databases`.
2. Query your database using `env.DB.prepare` to issue a [prepared query](/d1/worker-api/d1-database/#prepare) with a placeholder (the `?` in the query).
3. Call `bind()` to safely and securely bind a value to that placeholder. In a real application, you would allow a user to define the `CompanyName` they want to list results for. Using `bind()` prevents users from executing arbitrary SQL (known as "SQL injection") against your application and deleting or otherwise modifying your database.
3. Call `bind()` to safely and securely bind a value to that placeholder. In a real application, you would allow a user to pass the `CompanyName` they want to list results for. Using `bind()` prevents users from executing arbitrary SQL (known as "SQL injection") against your application and deleting or otherwise modifying your database.
4. Execute the query by calling `all()` to return all rows (or none, if the query returns none).
5. Return your query results, if any, in JSON format with `Response.json(results)`.

Expand All @@ -344,9 +375,9 @@ After configuring your Worker, you can test your project locally before you depl
You can query your D1 database using your Worker.

<Steps>
1. Go to **Workers & Pages** > **Overview**.
1. Go to **Compute (Workers)** > **Workers & Pages**.
2. Select the `d1-tutorial` Worker you created.
3. Select **Edit Code**.
3. Select the **Edit code** icon (**\<\/\>**).
4. Clear the contents of the `worker.js` file, then paste the following code:

```js
Expand Down Expand Up @@ -379,36 +410,75 @@ You can query your D1 database using your Worker.
</TabItem>
</Tabs>

## 5. Deploy your database
## 5. Deploy your application

Deploy your database on Cloudflare's global network.
Deploy your application on Cloudflare's global network.

<Tabs syncKey='CLIvDash'> <TabItem label='CLI'>

To deploy your Worker to production using Wrangler, you must first repeat the [database configuration](/d1/get-started/#configure-your-d1-database) steps after replacing the `--local` flag with the `--remote` flag to give your Worker data to read. This creates the database tables and imports the data into the production version of your database.
To deploy your Worker to production using Wrangler, you must first repeat the [database configuration](/d1/get-started/#populate-your-d1-database) steps after replacing the `--local` flag with the `--remote` flag to give your Worker data to read. This creates the database tables and imports the data into the production version of your database.

<Steps>
1. Bootstrap your database with the `schema.sql` file you created in step 4:
1. Create tables and add entries to your remote database with the `schema.sql` file you created in step 4. Enter `y` to confirm your decision.

```sh
npx wrangler d1 execute prod-d1-tutorial --remote --file=./schema.sql
```
```sh output
✔ ⚠️ This process may take some time, during which your D1 database will be unavailable to serve queries.
Ok to proceed? y
🚣 Executed 3 queries in 0.00 seconds (5 rows read, 6 rows written)
Database is currently at bookmark 00000002-00000004-00004ef1-ad4a06967970ee3b20860c86188a4b31.
┌────────────────────────┬───────────┬──────────────┬────────────────────┐
│ Total queries executed │ Rows read │ Rows written │ Database size (MB) │
├────────────────────────┼───────────┼──────────────┼────────────────────┤
│ 3 │ 5 │ 6 │ 0.02 │
└────────────────────────┴───────────┴──────────────┴────────────────────┘
```

2. Validate the data is in production by running:

```sh
npx wrangler d1 execute prod-d1-tutorial --remote --command="SELECT * FROM Customers"
```
```sh
npx wrangler d1 execute prod-d1-tutorial --remote --command="SELECT * FROM Customers"
```
```sh output
⛅️ wrangler 4.13.2
-------------------

🌀 Executing on remote database prod-d1-tutorial (<DATABASE_ID>):
🌀 To execute on your local development database, remove the --remote flag from your wrangler command.
🚣 Executed 1 command in 0.4069ms
┌────────────┬─────────────────────┬───────────────────┐
│ CustomerId │ CompanyName │ ContactName │
├────────────┼─────────────────────┼───────────────────┤
│ 1 │ Alfreds Futterkiste │ Maria Anders │
├────────────┼─────────────────────┼───────────────────┤
│ 4 │ Around the Horn │ Thomas Hardy │
├────────────┼─────────────────────┼───────────────────┤
│ 11 │ Bs Beverages │ Victoria Ashworth │
├────────────┼─────────────────────┼───────────────────┤
│ 13 │ Bs Beverages │ Random Name │
└────────────┴─────────────────────┴───────────────────┘
```

3. Deploy your Worker to make your project accessible on the Internet. Run:

```sh
npx wrangler deploy
```

```sh output
Outputs: https://d1-tutorial.<YOUR_SUBDOMAIN>.workers.dev
```
⛅️ wrangler 4.13.2
-------------------

Total Upload: 0.19 KiB / gzip: 0.16 KiB
Your worker has access to the following bindings:
- D1 Databases:
- DB: prod-d1-tutorial (<DATABASE_ID>)
Uploaded d1-tutorial (3.76 sec)
Deployed d1-tutorial triggers (2.77 sec)
https://d1-tutorial.<YOUR_SUBDOMAIN>.workers.dev
Current Version ID: <VERSION_ID>
```

You can now visit the URL for your newly created project to query your live database.

Expand All @@ -421,7 +491,7 @@ To deploy your Worker to production using Wrangler, you must first repeat the [d
</TabItem> <TabItem label='Dashboard'>
<Steps>

1. Go to **Workers & Pages** > **Overview**.
1. Go to **Compute (Workers)** > **Workers & Pages**.
2. Select your `d1-tutorial` Worker.
3. Select **Deployments**.
4. From the **Version History** table, select **Deploy version**.
Expand Down Expand Up @@ -475,7 +545,7 @@ npx wrangler d1 delete prod-d1-tutorial
</TabItem><TabItem label='Dashboard'>

<Steps>
1. Go to **Storages & Databases** > **D1**.
1. Go to **Storages & Databases** > **D1 SQL Database**.

2. Select your `prod-d1-tutorial` D1 database.

Expand All @@ -489,6 +559,10 @@ npx wrangler d1 delete prod-d1-tutorial

</TabItem> </Tabs>

:::caution
Note that deleting your D1 database will stop your application from functioning as before.
:::

If you want to delete your Worker:

<Tabs syncKey='CLIvDash'> <TabItem label='CLI'>
Expand All @@ -502,7 +576,7 @@ npx wrangler delete d1-tutorial
</TabItem> <TabItem label='Dashboard'>

<Steps>
1. Go to **Workers & Pages** > **Overview**.
1. Go to **Compute (Workers)** > **Workers & Pages**.

2. Select your `d1-tutorial` Worker.

Expand Down
Loading