# Demos and architectures URL: https://developers.cloudflare.com/d1/demos/ import { ExternalResources, GlossaryTooltip, ResourcesBySelector } from "~/components" Learn how you can use D1 within your existing application and architecture. ## Demos Explore the following demo applications for D1. ## Reference architectures Explore the following reference architectures that use D1: --- # Get started URL: https://developers.cloudflare.com/d1/get-started/ import { Render, PackageManagers, Steps, FileTree, Tabs, TabItem, TypeScriptExample, WranglerConfig } from "~/components"; 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. 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). ::: ## Prerequisites ## 1. Create a Worker Create a new Worker as the means to query your database. 1. Create a new project named `d1-tutorial` by running: This creates a new `d1-tutorial` directory as illustrated below. - d1-tutorial - node_modules/ - test/ - src - **index.ts** - package-lock.json - package.json - testconfig.json - vitest.config.mts - worker-configuration.d.ts - **wrangler.jsonc** Your new `d1-tutorial` directory includes: - A `"Hello World"` [Worker](/workers/get-started/guide/#3-write-code) in `index.ts`. - A [Wrangler configuration file](/workers/wrangler/configuration/). This file is how your `d1-tutorial` Worker accesses your D1 database. :::note If you are familiar with Cloudflare Workers, or initializing projects in a Continuous Integration (CI) environment, initialize a new project non-interactively by setting `CI=true` as an environmental variable when running `create cloudflare@latest`. For example: `CI=true npm create cloudflare@latest d1-tutorial --type=simple --git --ts --deploy=false` creates a basic "Hello World" project ready to build on. ::: 1. Log in to your [Cloudflare dashboard](https://dash.cloudflare.com/) and select your account. 2. Go to your account > **Workers & Pages** > **Overview**. 3. Select **Create**. 4. Select **Create Worker**. 5. Name your Worker. For this tutorial, name your Worker `d1-tutorial`. 6. Select **Deploy**. ## 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). To create your first D1 database: 1. Change into the directory you just created for your Workers project: ```sh 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`: ```sh npx wrangler d1 create prod-d1-tutorial ``` ```sh output ✅ Successfully created DB 'prod-d1-tutorial' [[d1_databases]] binding = "DB" # available in your Worker on env.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. ::: 1. Go to **Storage & Databases** > **D1**. 2. Select **Create**. 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**. :::note For reference, a good database name: - Uses a combination of ASCII characters, shorter than 32 characters, and uses dashes (-) instead of spaces. - Is descriptive of the use-case and environment. For example, "staging-db-web" or "production-db-backend". - Only describes the database, and is not directly referenced in code. ::: ## 3. Bind your Worker to your D1 database You must create a binding for your Worker to connect to your D1 database. [Bindings](/workers/runtime-apis/bindings/) allow your Workers to access resources, like D1, on the Cloudflare developer platform. To bind your D1 database to your Worker: You create bindings by updating your Wrangler file. 1. Copy the lines obtained from [step 2](/d1/get-started/#2-create-a-database) from your terminal. 2. Add them to the end of your Wrangler file. ```toml [[d1_databases]] binding = "DB" # available in your Worker on env.DB database_name = "prod-d1-tutorial" database_id = "" ``` Specifically: - The value (string) you set for `binding` is the **binding name**, and is used to reference this database in your Worker. In this tutorial, name your binding `DB`. - The binding name must be [a valid JavaScript variable name](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#variables). For example, `binding = "MY_DB"` or `binding = "productionDB"` would both be valid names for the binding. - Your binding is available in your Worker at `env.` and the D1 [Workers Binding API](/d1/worker-api/) is exposed on this binding. :::note When you execute the `wrangler d1 create` command, the client API package (which implements the D1 API and database class) is automatically installed. For more information on the D1 Workers Binding API, refer to [Workers Binding API](/d1/worker-api/). ::: You can also bind your D1 database to a [Pages Function](/pages/functions/). For more information, refer to [Functions Bindings for D1](/pages/functions/bindings/#d1-databases). You create bindings by adding them to the Worker you have created. 1. Go to **Workers & Pages** > **Overview**. 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**. 5. Select **D1 database**. 6. Name your binding in **Variable name**, then select the `prod-d1-tutorial` D1 database you created in [step 2](/d1/get-started/#2-create-a-database) from the dropdown menu. For this tutorial, name your binding `DB`. 7. Select **Deploy** to deploy your binding. When deploying, there are two options: - **Deploy:** Immediately deploy the binding to 100% of your audience. - **Save version:** Save a version of the binding which you can deploy in the future. For this tutorial, select **Deploy**. ## 4. Run a query against your D1 database ### Configure 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. 1. Copy the following code and save it as a `schema.sql` file in the `d1-tutorial` Worker directory you created in step 1: ```sql DROP TABLE IF EXISTS Customers; CREATE TABLE IF NOT EXISTS Customers (CustomerId INTEGER PRIMARY KEY, CompanyName TEXT, ContactName TEXT); INSERT INTO Customers (CustomerID, CompanyName, ContactName) VALUES (1, 'Alfreds Futterkiste', 'Maria Anders'), (4, 'Around the Horn', 'Thomas Hardy'), (11, 'Bs Beverages', 'Victoria Ashworth'), (13, 'Bs Beverages', 'Random Name'); ``` 2. Initialize your database to run and test locally first. Bootstrap your new D1 database by running: ```sh npx wrangler d1 execute prod-d1-tutorial --local --file=./schema.sql ``` 3. Validate your data is in your 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: ┌────────────┬─────────────────────┬───────────────────┐ │ CustomerId │ CompanyName │ ContactName │ ├────────────┼─────────────────────┼───────────────────┤ │ 1 │ Alfreds Futterkiste │ Maria Anders │ ├────────────┼─────────────────────┼───────────────────┤ │ 4 │ Around the Horn │ Thomas Hardy │ ├────────────┼─────────────────────┼───────────────────┤ │ 11 │ Bs Beverages │ Victoria Ashworth │ ├────────────┼─────────────────────┼───────────────────┤ │ 13 │ Bs Beverages │ Random Name │ └────────────┴─────────────────────┴───────────────────┘ ``` Use the Dashboard to create a table and populate it with data. 1. Go to **Storage & Databases** > **D1**. 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. ```sql DROP TABLE IF EXISTS Customers; CREATE TABLE IF NOT EXISTS Customers (CustomerId INTEGER PRIMARY KEY, CompanyName TEXT, ContactName TEXT); INSERT INTO Customers (CustomerID, CompanyName, ContactName) VALUES (1, 'Alfreds Futterkiste', 'Maria Anders'), (4, 'Around the Horn', 'Thomas Hardy'), (11, 'Bs Beverages', 'Victoria Ashworth'), (13, 'Bs Beverages', 'Random Name'); ``` 5. Select **Execute**. This creates a table called `Customers` in your `prod-d1-tutorial` database. 6. Select **Tables**, then select the `Customers` table to view the contents of the table. ### Write queries within your Worker After you have set up your database, run an SQL query from within your Worker. 1. Navigate to your `d1-tutorial` Worker and open the `index.ts` file. The `index.ts` file is where you configure your Worker's interactions with D1. 2. Clear the content of `index.ts`. 3. Paste the following code snippet into your `index.ts` file: ```typescript export interface Env { // If you set another name in the Wrangler config file for the value for 'binding', // replace "DB" with the variable name you defined. DB: D1Database; } export default { async fetch(request, env): Promise { const { pathname } = new URL(request.url); if (pathname === "/api/beverages") { // If you did not use `DB` as your binding name, change it here const { results } = await env.DB.prepare( "SELECT * FROM Customers WHERE CompanyName = ?", ) .bind("Bs Beverages") .all(); return Response.json(results); } return new Response( "Call /api/beverages to see everyone who works at Bs Beverages", ); }, } satisfies ExportedHandler; ``` 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]]`. 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. 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)`. After configuring your Worker, you can test your project locally before you deploy globally. You can query your D1 database using your Worker. 1. Go to **Workers & Pages** > **Overview**. 2. Select the `d1-tutorial` Worker you created. 3. Select **Edit Code**. 4. Clear the contents of the `worker.js` file, then paste the following code: ```js export default { async fetch(request, env) { const { pathname } = new URL(request.url); if (pathname === "/api/beverages") { // If you did not use `DB` as your binding name, change it here const { results } = await env.DB.prepare( "SELECT * FROM Customers WHERE CompanyName = ?" ) .bind("Bs Beverages") .all(); return new Response(JSON.stringify(results), { headers: { 'Content-Type': 'application/json' } }); } return new Response( "Call /api/beverages to see everyone who works at Bs Beverages" ); }, }; ``` 5. Select **Save**. ## 5. Deploy your database Deploy your database 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. 1. Bootstrap your database with the `schema.sql` file you created in step 4: ```sh npx wrangler d1 execute prod-d1-tutorial --remote --file=./schema.sql ``` 2. Validate the data is in production by running: ```sh npx wrangler d1 execute prod-d1-tutorial --remote --command="SELECT * FROM Customers" ``` 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 ``` You can now visit the URL for your newly created project to query your live database. For example, if the URL of your new Worker is `d1-tutorial..workers.dev`, accessing `https://d1-tutorial..workers.dev/api/beverages` sends a request to your Worker that queries your live database directly. 4. Test your database is running successfully. Add `/api/beverages` to the provided Wrangler URL. For example, `https://d1-tutorial..workers.dev/api/beverages`. 1. Go to **Workers & Pages** > **Overview**. 2. Select your `d1-tutorial` Worker. 3. Select **Deployments**. 4. From the **Version History** table, select **Deploy version**. 5. From the **Deploy version** page, select **Deploy**. This deploys the latest version of the Worker code to production. ## 6. (Optional) Develop locally with Wrangler If you are using D1 with Wrangler, you can test your database locally. While in your project directory: 1. Run `wrangler dev`: ```sh npx wrangler dev ``` When you run `wrangler dev`, Wrangler provides a URL (most likely `localhost:8787`) to review your Worker. 2. Go to the URL. The page displays `Call /api/beverages to see everyone who works at Bs Beverages`. 3. Test your database is running successfully. Add `/api/beverages` to the provided Wrangler URL. For example, `localhost:8787/api/beverages`. If successful, the browser displays your data. :::note You can only develop locally if you are using Wrangler. You cannot develop locally through the Cloudflare dashboard. ::: ## 7. (Optional) Delete your database To delete your database: Run: ```sh npx wrangler d1 delete prod-d1-tutorial ``` 1. Go to **Storages & Databases** > **D1**. 2. Select your `prod-d1-tutorial` D1 database. 3. Select **Settings**. 4. Select **Delete**. 5. Type the name of the database (`prod-d1-tutorial`) to confirm the deletion. If you want to delete your Worker: Run: ```sh npx wrangler delete d1-tutorial ``` 1. Go to **Workers & Pages** > **Overview**. 2. Select your `d1-tutorial` Worker. 3. Select **Settings**. 4. Scroll to the bottom of the page, then select **Delete**. 5. Type the name of the Worker (`d1-tutorial`) to confirm the deletion. ## Summary In this tutorial, you have: - Created a D1 database - Created a Worker to access that database - Deployed your project globally ## Next steps If you have any feature requests or notice any bugs, share your feedback directly with the Cloudflare team by joining the [Cloudflare Developers community on Discord](https://discord.cloudflare.com). - See supported [Wrangler commands for D1](/workers/wrangler/commands/#d1). - Learn how to use [D1 Worker Binding APIs](/d1/worker-api/) within your Worker, and test them from the [API playground](/d1/worker-api/#api-playground). - Explore [community projects built on D1](/d1/reference/community-projects/). --- # Overview URL: https://developers.cloudflare.com/d1/ import { CardGrid, Description, Feature, LinkTitleCard, Plan, RelatedProduct } from "~/components" Create new serverless SQL databases to query from your Workers and Pages projects. D1 is Cloudflare's managed, serverless database with SQLite's SQL semantics, built-in disaster recovery, and Worker and HTTP API access. D1 is designed for horizontal scale out across multiple, smaller (10 GB) databases, such as per-user, per-tenant or per-entity databases. D1 allows you to build applications with thousands of databases at no extra cost for isolating with multiple databases. D1 pricing is based only on query and storage costs. Create your first D1 database by [following the Get started guide](/d1/get-started/), learn how to [import data into a database](/d1/best-practices/import-export-data/), and how to [interact with your database](/d1/worker-api/) directly from [Workers](/workers/) or [Pages](/pages/functions/bindings/#d1-databases). *** ## Features Create your first D1 database, establish a schema, import data and query D1 directly from an application [built with Workers](/workers/). Execute SQL with SQLite's SQL compatibility and D1 Client API. Time Travel is D1’s approach to backups and point-in-time-recovery, and allows you to restore a database to any minute within the last 30 days. *** ## Related products Build serverless applications and deploy instantly across the globe for exceptional performance, reliability, and scale. Deploy dynamic front-end applications in record time. *** ## More resources Learn about D1's pricing and how to estimate your usage. Learn about what limits D1 has and how to work within them. Browse what developers are building with D1. Learn more about the storage and database options you can build on with Workers. Connect with the Workers community on Discord to ask questions, show what you are building, and discuss the platform with other developers. Follow @CloudflareDev on Twitter to learn about product announcements, and what is new in Cloudflare Developer Platform. --- # Wrangler commands URL: https://developers.cloudflare.com/d1/wrangler-commands/ import { Render, Type, MetaInfo } from "~/components" D1 Wrangler commands use REST APIs to interact with the control plane. This page lists the Wrangler commands for D1. ## Global commands ## Experimental commands ### `insights` Returns statistics about your queries. ```sh npx wrangler d1 insights --