Skip to content

Commit bf9ced4

Browse files
committed
Modifying the structure to align with discussion.
1 parent 0a349be commit bf9ced4

File tree

4 files changed

+141
-148
lines changed

4 files changed

+141
-148
lines changed

src/content/docs/d1/worker-api/api-playground.mdx

Lines changed: 0 additions & 95 deletions
This file was deleted.

src/content/docs/d1/worker-api/index.mdx

Lines changed: 121 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,128 @@
11
---
22
pcx_content_type: navigation
3-
title: Worker Binding API
3+
title: D1 Worker Binding API
44
sidebar:
55
order: 4
6-
group:
7-
hideIndex: true
86
---
97

10-
import { DirectoryListing } from "~/components";
8+
import { DirectoryListing, Details, Steps } from "~/components";
9+
10+
You can execute queries on your D1 database through SQL query statements. To do this, you need to perform the following steps:
11+
12+
1. [Prepare a statement](/d1/worker-api/prepare-a-statement).
13+
2. [Run the prepared statement](/d1/worker-api/run-a-statement).
14+
3. Analyze the [return object](/d1/worker-api/return-object) (if necessary).
15+
16+
Refer to the relevant sections for the API documentation.
17+
18+
## Typescript support
19+
20+
D1 Worker Bindings API is fully-typed via the `@cloudflare/workers-types` 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.
21+
22+
When using the [query statement methods](#query-statement-methods) `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.
23+
24+
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:
25+
26+
```ts
27+
// Row definition
28+
type OrderRow = {
29+
Id: string;
30+
CustomerName: string;
31+
OrderDate: number;
32+
};
33+
34+
// Elsewhere in your application
35+
const result = await env.MY_DB.prepare(
36+
"SELECT Id, CustomerName, OrderDate FROM [Order] ORDER BY ShippedDate DESC LIMIT 100",
37+
).run<OrderRow>();
38+
```
39+
40+
## API playground
41+
42+
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.
43+
44+
You can use this alongside the API documentation to better understand how each API works.
45+
46+
Follow the steps to setup your API playground.
47+
48+
### 1. Complete the Get started tutorial
49+
50+
Complete the [Get started](/d1/get-started/#write-queries-within-your-worker) tutorial. Ensure you use JavaScript instead of TypeScript.
51+
52+
### 2. Modify the content of `index.js`
53+
54+
Replace the contents of your `index.js` file with the below to view the effect of each API.
55+
56+
<Details header="index.js" open={false}>
57+
```js
58+
export default {
59+
async fetch(request, env) {
60+
const { pathname } = new URL(request.url);
61+
62+
const companyName1 = `Bs Beverages`;
63+
const companyName2 = `Around the Horn`;
64+
const stmt = env.DB.prepare(`SELECT * FROM Customers WHERE CompanyName = ?`);
65+
66+
if (pathname === `/RUN`){
67+
const returnValue = await stmt.bind(companyName1).run()
68+
return Response.json(returnValue);
69+
70+
} else if (pathname === `/RAW`){
71+
const returnValue = await stmt.bind(companyName1).raw();
72+
return Response.json(returnValue);
73+
74+
} else if (pathname === `/FIRST`){
75+
const returnValue = await stmt.bind(companyName1).first();
76+
return Response.json(returnValue);
77+
78+
} else if (pathname === `/BATCH`) {
79+
const batchResult = await env.DB.batch([
80+
stmt.bind(companyName1),
81+
stmt.bind(companyName2)
82+
]);
83+
// const returnValue = await stmt.run();
84+
return Response.json(batchResult);
85+
}
86+
87+
return new Response(
88+
`Welcome to the D1 API Playground!
89+
\nChange the URL to test the methods inside your index.js file.`,
90+
);
91+
},
92+
};
93+
94+
```
95+
</Details>
96+
97+
### 3. Deploy the Worker
98+
99+
<Steps>
100+
1. Navigate to your tutorial directory you created by following step 1.
101+
2. Run `npx wrangler dev`.
102+
```sh
103+
npx wrangler dev
104+
```
105+
```sh output
106+
⛅️ wrangler 3.85.0 (update available 3.86.1)
107+
-------------------------------------------------------
108+
109+
Your worker has access to the following bindings:
110+
- D1 Databases:
111+
- DB: <DATABASE_NAME> (DATABASE_ID) (local)
112+
⎔ Starting local server...
113+
[wrangler:inf] Ready on http://localhost:8787
114+
╭───────────────────────────╮
115+
│ [b] open a browser │
116+
│ [d] open devtools │
117+
│ [l] turn off local mode │
118+
│ [c] clear console │
119+
│ [x] to exit
120+
╰───────────────────────────╯
121+
```
122+
3. Open a browser at the specified address.
123+
</Steps>
124+
125+
### 4. Test the APIs
126+
127+
Change the URL to test the various D1 Worker Binding APIs.
11128

12-
<DirectoryListing />

src/content/docs/d1/worker-api/prepare-a-statement.mdx

Lines changed: 20 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,6 @@ sidebar:
77

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

10-
You can execute queries on your D1 database through SQL query statements. To do this, you need to follow these steps:
11-
12-
1. Prepare your query statement (including binding variables into the statement).
13-
2. Execute your query.
14-
1510
This chapter documents how to prepare a statement.
1611

1712
## Methods
@@ -20,30 +15,9 @@ This chapter documents how to prepare a statement.
2015

2116
Prepares a query statement to be later executed.
2217

23-
D1 API supports both prepared and static statements.
24-
25-
- Prepared statements are SQL statements where the variables are dynamically determined. When writing a prepared statement, you insert variables into placeholders within the statement string.
26-
- 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.
27-
28-
:::note
29-
The recommended approach is to use prepared statements (which are precompiled objects used by the database) to run the SQL. Prepared statements lead to faster overall execution and prevent SQL injection attacks.
30-
:::
31-
32-
Example of a prepared statement with dynamically bound value:
33-
3418
```js
3519
const someVariable = `Bs Beverages`;
3620
const stmt = env.DB.prepare("SELECT * FROM Customers WHERE CompanyName = ?").bind(someVariable);
37-
// A variable (someVariable) will replace the placeholder '?' in the query.
38-
// `stmt` is a prepared statement.
39-
```
40-
41-
Example of a static statement:
42-
43-
```js
44-
const stmt = env.DB.prepare("SELECT * FROM Customers WHERE CompanyName = Bs Beverages");
45-
// "Bs Beverages" is hard-coded into the query.
46-
// `stmt` is a static statement.
4721
```
4822

4923
#### Parameters
@@ -90,22 +64,27 @@ const stmt = env.DB.prepare("SELECT * FROM Customers WHERE CompanyName = Bs Beve
9064
.bind(1, "Alfreds Futterkiste");
9165
```
9266

93-
- D1 Worker Bindings API is fully-typed via the `@cloudflare/workers-types` 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.
67+
## Static statements
9468

95-
- When using the [query statement methods](#query-statement-methods) `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.
69+
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.
9670

97-
- 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:
71+
:::note
72+
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.
73+
:::
9874

99-
```ts
100-
// Row definition
101-
type OrderRow = {
102-
Id: string;
103-
CustomerName: string;
104-
OrderDate: number;
105-
};
75+
Example of a prepared statement with dynamically bound value:
10676

107-
// Elsewhere in your application
108-
const result = await env.MY_DB.prepare(
109-
"SELECT Id, CustomerName, OrderDate FROM [Order] ORDER BY ShippedDate DESC LIMIT 100",
110-
).run<OrderRow>();
111-
```
77+
```js
78+
const someVariable = `Bs Beverages`;
79+
const stmt = env.DB.prepare("SELECT * FROM Customers WHERE CompanyName = ?").bind(someVariable);
80+
// A variable (someVariable) will replace the placeholder '?' in the query.
81+
// `stmt` is a prepared statement.
82+
```
83+
84+
Example of a static statement:
85+
86+
```js
87+
const stmt = env.DB.prepare("SELECT * FROM Customers WHERE CompanyName = Bs Beverages");
88+
// "Bs Beverages" is hard-coded into the query.
89+
// `stmt` is a static statement.
90+
```

src/content/docs/d1/worker-api/run-a-statement.mdx

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,13 +7,6 @@ sidebar:
77

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

10-
## Description
11-
12-
You to execute queries on your D1 database through SQL query statements. To do this, you need to follow these steps:
13-
14-
1. Prepare your query statement (including binding variables into the statement).
15-
2. Execute your query.
16-
1710
This chapter documents the various ways you can run and retrieve the results of a query after you have [prepared your statement](/d1/worker-api/prepare-a-statement).
1811

1912
## Methods

0 commit comments

Comments
 (0)