Skip to content
Merged
Show file tree
Hide file tree
Changes from 27 commits
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
702c550
Adding placeholder for new API section.
Oxyjun Oct 31, 2024
b59f2a8
Initializing await stmt API chapter.
Oxyjun Nov 1, 2024
192fa36
Reordering the sidebar. Adding intro to stmt.methods.
Oxyjun Nov 4, 2024
3f7dee4
Setting up Worker Bindings API chapters.
Oxyjun Nov 4, 2024
d1dcb91
Settling on naming convention, fleshing out .db chapter.
Oxyjun Nov 5, 2024
ce19b83
Setting up the database API section.
Oxyjun Nov 6, 2024
1684e9c
Fleshing out API chapters.
Oxyjun Nov 6, 2024
f5d8282
Updating D1 API docs.
Oxyjun Nov 7, 2024
5aa097a
Adding in more information to be complete.
Oxyjun Nov 7, 2024
6ab8172
Apply suggestions from code review
Oxyjun Nov 7, 2024
3d5cb99
Update src/content/docs/d1/worker-api/query.mdx
Oxyjun Nov 7, 2024
c89fc37
Updating the Return Object chapter. Testing more APIs.
Oxyjun Nov 8, 2024
4880d8f
Fleshing out the API docs in more detail.
Oxyjun Nov 11, 2024
66182a0
Fixing broken link.
Oxyjun Nov 11, 2024
a0fb41f
Changing reference to mention Worker Binding APIs.
Oxyjun Nov 11, 2024
e1c2357
Small rename.
Oxyjun Nov 12, 2024
93f6674
Small rename.
Oxyjun Nov 12, 2024
e3741dd
Updating the chapters
Oxyjun Nov 12, 2024
0a349be
Merge branch 'jun/d1/API-reshuffle' of github.com:cloudflare/cloudfla…
Oxyjun Nov 12, 2024
bf9ced4
Modifying the structure to align with discussion.
Oxyjun Nov 12, 2024
8817761
Renaming extensions header for better clarity.
Oxyjun Nov 13, 2024
696a82a
Adding changelog entry for including multiple queries in a single pre…
Oxyjun Nov 13, 2024
1d3637f
Updating wording in Get started to match new folders.
Oxyjun Nov 13, 2024
c3023ab
Fixing broken link
Oxyjun Nov 13, 2024
73083c0
Implementing feedback.
Oxyjun Nov 15, 2024
4f2a119
Removing references to multi-statement prepare().
Oxyjun Nov 15, 2024
7dbf844
Fixing broken links
Oxyjun Nov 15, 2024
9efd9e9
Grammar fixes and deleting redundant comment block.
Oxyjun Nov 15, 2024
caf3890
Apply suggestions from code review
Oxyjun Nov 15, 2024
d3cdce6
Minor rename of the chapter
Oxyjun Nov 15, 2024
ba5fbde
Cleaning up the structure by method hierarchy.
Oxyjun Nov 19, 2024
b7d850d
Adding a note for those who are following the tutorial with an existi…
Oxyjun Nov 19, 2024
cc0de6f
Actioning PR feedback.
Oxyjun Nov 19, 2024
236aad9
Turning all method names into links to the relevant header.
Oxyjun Nov 19, 2024
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
1 change: 1 addition & 0 deletions public/_redirects
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,7 @@
/d1/configuration/remote-development/ /d1/build-with-d1/remote-development/ 301
/d1/build-with-d1/import-data/ /d1/build-with-d1/import-export-data/ 301
/d1/reference/database-commands/ /d1/reference/sql-statements/ 301
/d1/reference/sql-statements/ /d1/sql-api/sql-statements/ 301

# data loss prevention (dlp)
/cloudflare-one/policies/data-loss-prevention/integration-profiles/ /cloudflare-one/policies/data-loss-prevention/dlp-profiles/integration-profiles/ 301
Expand Down
2 changes: 1 addition & 1 deletion src/content/docs/d1/build-with-d1/d1-client-api.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -449,7 +449,7 @@ D1 PRAGMA statements only apply to the current transaction.

:::

For the full list of PRAGMA statements supported by D1, see [SQL statements](/d1/reference/sql-statements).
For the full list of PRAGMA statements supported by D1, see [SQL statements](/d1/sql-api/sql-statements).

## Errors

Expand Down
2 changes: 1 addition & 1 deletion src/content/docs/d1/configuration/index.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
title: Configuration
pcx_content_type: navigation
sidebar:
order: 4
order: 6
group:
hideIndex: true
---
Expand Down
2 changes: 1 addition & 1 deletion src/content/docs/d1/d1-api.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,6 @@ pcx_content_type: navigation
title: D1 REST API
external_link: /api/operations/cloudflare-d1-create-database
sidebar:
order: 10
order: 5

---
2 changes: 1 addition & 1 deletion src/content/docs/d1/demos.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
pcx_content_type: navigation
title: Demos and architectures
sidebar:
order: 8
order: 10

---

Expand Down
2 changes: 1 addition & 1 deletion src/content/docs/d1/examples/index.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ hideChildren: false
pcx_content_type: navigation
title: Examples
sidebar:
order: 6
order: 8
group:
hideIndex: true
---
Expand Down
2 changes: 1 addition & 1 deletion src/content/docs/d1/get-started.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -532,5 +532,5 @@ In this tutorial, you have:
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 the [D1 client API](/d1/build-with-d1/d1-client-api/) within your Worker.
- Learn how to use the [D1 Worker Binding API](/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/).
2 changes: 1 addition & 1 deletion src/content/docs/d1/observability/index.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
title: Observability
pcx_content_type: navigation
sidebar:
order: 5
order: 7
group:
hideIndex: true
---
Expand Down
2 changes: 1 addition & 1 deletion src/content/docs/d1/platform/index.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
pcx_content_type: navigation
title: Platform
sidebar:
order: 8
order: 10
group:
hideIndex: true
---
Expand Down
2 changes: 1 addition & 1 deletion src/content/docs/d1/reference/index.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
pcx_content_type: navigation
title: Reference
sidebar:
order: 9
order: 11
group:
hideIndex: true
---
Expand Down
12 changes: 12 additions & 0 deletions src/content/docs/d1/sql-api/index.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---
title: SQL API
pcx_content_type: navigation
sidebar:
order: 5
group:
hideIndex: true
---

import { DirectoryListing } from "~/components";

<DirectoryListing />
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,33 @@
title: SQL statements
pcx_content_type: concept
sidebar:
order: 6
order: 1
---

import { Details, Render } from "~/components";

D1 supports a number of database-level commands that allow you to list tables, indexes, and inspect the schema for a given table or index.
D1 is compatible with most SQLite's SQL convention since it leverages SQLite's query engine. D1 supports a number of database-level statements that allow you to list tables, indexes, and inspect the schema for a given table or index.

## Database statements
You can execute any of these statements via the D1 console in the Cloudflare dashboard, [`wrangler d1 execute`](/workers/wrangler/commands/#d1), or with the [D1 Worker Bindings API](/d1/worker-api/prepare-a-statement).

D1 supports a number of database-level statements that allow you to list tables, indexes, and inspect the schema for a given table or index.
## Supported SQLite Extensions

You can execute any of these statements via the D1 console in the Cloudflare dashboard, [`wrangler d1 execute`](/workers/wrangler/commands/#d1), or with the [D1 client API](/d1/build-with-d1/d1-client-api/).
D1 supports a subset of SQLite extensions for added functionality, including:

- Default SQLite extensions.
- [FTS5 module](https://www.sqlite.org/fts5.html) for full-text search.

## Compatible PRAGMA statements

D1 supports some [SQLite PRAGMA](https://www.sqlite.org/pragma.html) statements. The PRAGMA statement is an SQL extension for SQLite. PRAGMA commands can be used to:

- Modify the behavior of certain SQLite operations.
- Query the SQLite library for internal data about schemas or tables (but note that PRAGMA statements cannot query the contents of a table).
- Control environmental variables.

<Render file="use-pragma-statements" />

### Query `sqlite_master`
## Query `sqlite_master`

You can also query the `sqlite_master` table to show all tables, indexes, and the original SQL used to generate them:

Expand All @@ -44,11 +55,21 @@ SELECT name, sql FROM sqlite_master
}
```

## SQLite Extensions
## Search with LIKE

D1 supports a subset of SQLite extensions for added functionality, including:
You can perform a search using SQL's `LIKE` operator:

- [FTS5 module](https://www.sqlite.org/fts5.html) for full-text search
```js
const { results } = await env.DB.prepare(
"SELECT * FROM Customers WHERE CompanyName LIKE ?",
)
.bind("%eve%")
.all();
console.log("results: ", results);
```
```js output
results: [...]
```

## Related resources

Expand Down
2 changes: 1 addition & 1 deletion src/content/docs/d1/tutorials/index.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ pcx_content_type: navigation
title: Tutorials
hideChildren: true
sidebar:
order: 7
order: 9

---

Expand Down
137 changes: 137 additions & 0 deletions src/content/docs/d1/worker-api/index.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
---
pcx_content_type: navigation
title: D1 Worker Binding API
sidebar:
order: 4
---

import { DirectoryListing, Details, Steps } from "~/components";

You can execute SQL queries on your D1 database from a Worker using the Worker Binding API. To do this, you can perform the following steps:

1. [Prepare a statement](/d1/worker-api/prepare-a-statement).
2. [Run the prepared statement](/d1/worker-api/run-a-statement).
3. Analyze the [return object](/d1/worker-api/return-object) (if necessary).

Refer to the relevant sections for the API documentation.

## Typescript support

D1 Worker Bindings API is fully-typed via the [`@cloudflare/workers-types`](/workers/languages/typescript/#typescript) package, and also supports [generic types](https://www.typescriptlang.org/docs/handbook/2/generics.html#generic-types) as part of its TypeScript API. A generic type allows you to provide an optional _type parameter_ so that a function understands the type of the data it is handling.

When using the [query statement methods](/d1/worker-api/run-a-statement) `stmt.run()`, `stmt.raw()` and `stmt.first()`, you can provide a type representing each database row. D1's API will [return the result object](#return-object) with the correct type.

For example, providing an `OrderRow` type as a type parameter to `stmt.run()` will return a typed `Array<OrderRow>` object instead of the default `Record<string, unknown>` type:

```ts
// Row definition
type OrderRow = {
Id: string;
CustomerName: string;
OrderDate: number;
};

// Elsewhere in your application
const result = await env.MY_DB.prepare(
"SELECT Id, CustomerName, OrderDate FROM [Order] ORDER BY ShippedDate DESC LIMIT 100",
).run<OrderRow>();
```

## API playground

The D1 Worker Binding API playground is an `index.js` file where you can test each of the documented Worker Binding APIs for D1. The file builds from the end-state of the [Get started](/d1/get-started/#write-queries-within-your-worker) code.

You can use this alongside the API documentation to better understand how each API works.

Follow the steps to setup your API playground.

### 1. Complete the Get started tutorial

Complete the [Get started](/d1/get-started/#write-queries-within-your-worker) tutorial. Ensure you use JavaScript instead of TypeScript.

### 2. Modify the content of `index.js`

Replace the contents of your `index.js` file with the below to view the effect of each API.

<Details header="index.js" open={false}>
```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 Response.json(results);
// }

const companyName1 = `Bs Beverages`;
const companyName2 = `Around the Horn`;
const stmt = env.DB.prepare(`SELECT * FROM Customers WHERE CompanyName = ?`);

if (pathname === `/RUN`){
const returnValue = await stmt.bind(companyName1).run();
return Response.json(returnValue);

} else if (pathname === `/RAW`){
const returnValue = await stmt.bind(companyName1).raw();
return Response.json(returnValue);

} else if (pathname === `/FIRST`){
const returnValue = await stmt.bind(companyName1).first();
return Response.json(returnValue);

} else if (pathname === `/BATCH`) {
const batchResult = await env.DB.batch([
stmt.bind(companyName1),
stmt.bind(companyName2)
]);
return Response.json(batchResult);

} else if (pathname === `/EXEC`){
const returnValue = await env.DB.exec(`SELECT * FROM Customers WHERE CompanyName = "Bs Beverages"`);
return Response.json(returnValue);
}

return new Response(
`Welcome to the D1 API Playground!
\nChange the URL to test the various methods inside your index.js file.`,
);
},
};

```
</Details>

### 3. Deploy the Worker

<Steps>
1. Navigate to your tutorial directory you created by following step 1.
2. Run `npx wrangler dev`.
```sh
npx wrangler dev
```
```sh output
⛅️ wrangler 3.85.0 (update available 3.86.1)
-------------------------------------------------------

Your worker has access to the following bindings:
- D1 Databases:
- DB: <DATABASE_NAME> (DATABASE_ID) (local)
⎔ Starting local server...
[wrangler:inf] Ready on http://localhost:8787
╭───────────────────────────╮
│ [b] open a browser │
│ [d] open devtools │
│ [l] turn off local mode │
│ [c] clear console │
│ [x] to exit
╰───────────────────────────╯
```
3. Open a browser at the specified address.
</Steps>

### 4. Test the APIs

Change the URL to test the various D1 Worker Binding APIs.

84 changes: 84 additions & 0 deletions src/content/docs/d1/worker-api/prepare-a-statement.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
---
title: Prepare a statement
pcx_content_type: concept
sidebar:
order: 1
---

import { Type, MetaInfo, Details } from "~/components";

This chapter documents how to prepare a statement.

## Methods

### `db.prepare()`

Prepares a query statement to be later executed.

```js
const someVariable = `Bs Beverages`;
const stmt = env.DB.prepare("SELECT * FROM Customers WHERE CompanyName = ?").bind(someVariable);
```

#### Parameters

- <code>sqlQuery</code>: <Type text="String"/> <MetaInfo text="Required"/>
- The SQL query you wish to execute on the database.

#### Return values

- None.

#### Guidance

- D1 follows the [SQLite convention](https://www.sqlite.org/lang_expr.html#varparam) for prepared statements parameter binding. Currently, D1 only supports Ordered (`?NNNN`) and Anonymous (`?`) parameters. In the future, D1 will support named parameters as well.

| Syntax | Type | Description |
| ------ | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `?NNN` | Ordered | A question mark followed by a number `NNN` holds a spot for the `NNN`-th parameter. `NNN` must be between `1` and `SQLITE_MAX_VARIABLE_NUMBER` |
| `?` | Anonymous | A question mark that is not followed by a number creates a parameter with a number one greater than the largest parameter number already assigned. If this means the parameter number is greater than SQLITE_MAX_VARIABLE_NUMBER, it is an error. This parameter format is provided for compatibility with other database engines. But because it is easy to miscount the question marks, the use of this parameter format is discouraged. Programmers are encouraged to use one of the symbolic formats below or the `?NNN` format above instead |

To bind a parameter, use the `stmt.bind()` method.

Order and anonymous examples:

```js
const stmt = db.prepare("SELECT * FROM Customers WHERE CompanyName = ?").bind("");
```

```js
const stmt = db
.prepare("SELECT * FROM Customers WHERE CompanyName = ? AND CustomerId = ?")
.bind("Alfreds Futterkiste", 1);
```

```js
const stmt = db
.prepare("SELECT * FROM Customers WHERE CompanyName = ?2 AND CustomerId = ?1")
.bind(1, "Alfreds Futterkiste");
```

## Static statements

D1 API supports static statements. Static statements are SQL statements where the variables have been hard coded. When writing a static statement, you manually type the variable within the statement string.

:::note
The recommended approach is to bind parameters to create a prepared statement (which are precompiled objects used by the database) to run the SQL. Prepared statements lead to faster overall execution and prevent SQL injection attacks.
:::

Example of a prepared statement with dynamically bound value:

```js
const someVariable = `Bs Beverages`;
const stmt = env.DB.prepare("SELECT * FROM Customers WHERE CompanyName = ?").bind(someVariable);
// A variable (someVariable) will replace the placeholder '?' in the query.
// `stmt` is a prepared statement.
```

Example of a static statement:

```js
const stmt = env.DB.prepare("SELECT * FROM Customers WHERE CompanyName = Bs Beverages");
// "Bs Beverages" is hard-coded into the query.
// `stmt` is a static statement.
```
Loading
Loading