diff --git a/src/content/docs/d1/get-started.mdx b/src/content/docs/d1/get-started.mdx index 399df132a6c8cb..745f3fc3d35a0e 100644 --- a/src/content/docs/d1/get-started.mdx +++ b/src/content/docs/d1/get-started.mdx @@ -12,7 +12,7 @@ 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. @@ -20,6 +20,16 @@ You can perform these tasks through the CLI or through the Cloudflare dashboard. 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 @@ -80,9 +90,9 @@ For example: `CI=true npm create cloudflare@latest d1-tutorial --type=simple --g 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**. @@ -90,7 +100,7 @@ For example: `CI=true npm create cloudflare@latest d1-tutorial --type=simple --g ## 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: @@ -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 = "" - ``` + { + "d1_databases": [ + { + "binding": "DB", + "database_name": "prod-d1-tutorial", + "database_id": "" + } + ] + } - + ``` -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. + -::: +This creates a new D1 database and outputs the [binding](/workers/runtime-apis/bindings/) configuration needed in the next step. -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**. @@ -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. -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**. @@ -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 -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. 1. Copy the following code and save it as a `schema.sql` file in the `d1-tutorial` Worker directory you created in step 1: @@ -237,8 +256,20 @@ 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 () 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" @@ -246,7 +277,7 @@ After correctly preparing your [Wrangler configuration file](/workers/wrangler/c ```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 () from .wrangler/state/v3/d1: ┌────────────┬─────────────────────┬───────────────────┐ │ CustomerId │ CompanyName │ ContactName │ ├────────────┼─────────────────────┼───────────────────┤ @@ -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. -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. @@ -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)`. @@ -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. -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 @@ -379,36 +410,75 @@ You can query your D1 database using your Worker. -## 5. Deploy your database +## 5. Deploy your application -Deploy your database on Cloudflare's global network. +Deploy your application on Cloudflare's global network. -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. -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 (): + 🌀 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..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 () + Uploaded d1-tutorial (3.76 sec) + Deployed d1-tutorial triggers (2.77 sec) + https://d1-tutorial..workers.dev + Current Version ID: + ``` You can now visit the URL for your newly created project to query your live database. @@ -421,7 +491,7 @@ To deploy your Worker to production using Wrangler, you must first repeat the [d -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**. @@ -475,7 +545,7 @@ npx wrangler d1 delete prod-d1-tutorial -1. Go to **Storages & Databases** > **D1**. +1. Go to **Storages & Databases** > **D1 SQL Database**. 2. Select your `prod-d1-tutorial` D1 database. @@ -489,6 +559,10 @@ npx wrangler d1 delete prod-d1-tutorial +:::caution +Note that deleting your D1 database will stop your application from functioning as before. +::: + If you want to delete your Worker: @@ -502,7 +576,7 @@ npx wrangler delete d1-tutorial -1. Go to **Workers & Pages** > **Overview**. +1. Go to **Compute (Workers)** > **Workers & Pages**. 2. Select your `d1-tutorial` Worker.