Skip to content

Commit c89fc37

Browse files
committed
Updating the Return Object chapter. Testing more APIs.
1 parent 3d5cb99 commit c89fc37

File tree

3 files changed

+132
-60
lines changed

3 files changed

+132
-60
lines changed

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

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,19 @@
11
---
2-
title: D1 database
2+
title: Prepare a statement
33
pcx_content_type: concept
44
sidebar:
55
order: 1
66
---
77

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

10-
## Description
10+
You can execute queries on your D1 database through SQL query statements. To do this, you need to follow these steps:
1111

12-
You can execute queries on your D1 database through SQL statements.
12+
1. Prepare your query statement.
13+
2. If appliable, bind variables into your statement.
14+
3. Execute your query.
1315

14-
### TypeScript support
16+
## TypeScript support
1517

1618
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.
1719

@@ -37,12 +39,14 @@ const result = await env.MY_DB.prepare(
3739

3840
### `db.prepare()`
3941

40-
D1 API supports both prepared and static statements.
42+
Prepares a query statement statement. D1 API supports both prepared and static statements.
4143

4244
- 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.
4345
- 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.
4446

47+
:::note
4548
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.
49+
:::
4650

4751
Example of a prepared statement with dynamically bound value:
4852

src/content/docs/d1/worker-api/return-object.mdx

Lines changed: 35 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -7,40 +7,59 @@ sidebar:
77

88
The methods `stmt.run()` and `db.batch()` return a typed `D1Result` object for each query statement. This object contains:
99

10-
- The results (if applicable) as an array
1110
- The success status
1211
- A meta object with the internal duration of the operation in milliseconds
12+
- The results (if applicable) as an array
1313

1414
```js
1515
{
16-
results: array | null, // [] if empty, or null if it does not apply
1716
success: boolean, // true if the operation was successful, false otherwise
1817
meta: {
19-
duration: number, // duration of the operation in milliseconds
18+
served_by: string // the version of Cloudflare's backend Worker that returned the result
19+
duration: number, // the duration of the SQL query execution only, in milliseconds
20+
changes: number, // the number of changes made to the database
21+
last_row_id: number, // the last inserted row ID, only applies when the table is defined without the `WITHOUT ROWID` option
22+
changed_db: boolean, // true if something on the database was changed
23+
size_after: number, // the size of the database after the query is successfully applied
2024
rows_read: number, // the number of rows read (scanned) by this query
2125
rows_written: number // the number of rows written by this query
2226
}
27+
results: array | null, // [] if empty, or null if it does not apply
2328
}
2429
```
2530

2631
## Example:
2732

2833
```js
29-
const { duration } = (
30-
await db
31-
.prepare("INSERT INTO users (name, age) VALUES (?1, ?2)")
32-
.bind("John", 42)
33-
.run()
34-
).meta;
35-
36-
console.log(duration); // 0.172
34+
const someVariable = `Bs Beverages`;
35+
const stmt = env.DB.prepare("SELECT * FROM Customers WHERE CompanyName = ?").bind(someVariable);
36+
const returnValue = await stmt.run();
37+
return Response.json(result)
3738
```
38-
39-
The `db.exec()` method returns a `D1ExecResult` object:
40-
4139
```js
4240
{
43-
count: number, // the number of queries executed
44-
duration: number // duration of the operation in milliseconds
41+
"success": true,
42+
"meta": {
43+
"served_by": "miniflare.db",
44+
"duration": 1,
45+
"changes": 0,
46+
"last_row_id": 0,
47+
"changed_db": false,
48+
"size_after": 8192,
49+
"rows_read": 4,
50+
"rows_written": 0
51+
},
52+
"results": [
53+
{
54+
"CustomerId": 11,
55+
"CompanyName": "Bs Beverages",
56+
"ContactName": "Victoria Ashworth"
57+
},
58+
{
59+
"CustomerId": 13,
60+
"CompanyName": "Bs Beverages",
61+
"ContactName": "Random Name"
62+
}
63+
]
4564
}
4665
```

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

Lines changed: 88 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
---
2-
title: D1 prepared statement
2+
title: Run a prepared statement
33
pcx_content_type: concept
44
sidebar:
55
order: 2
@@ -9,16 +9,16 @@ import { Type, MetaInfo, Details } from "~/components";
99

1010
## Description
1111

12-
You can modify the query results which has been obtained after executing a `.db()` method.
12+
After preparing a query statement, you can run and retrieve the results of the query.
1313

1414
## Methods
1515

1616
### `stmt.run()`
1717

18-
Runs the prepared query (or queries) and returns results.
18+
Runs the prepared query (or queries) and returns results. The returned results includes metadata.
1919

2020
```js
21-
const { results } = await stmt.run();
21+
const returnValue = await stmt.run();
2222
```
2323

2424
#### Parameter
@@ -27,49 +27,83 @@ const { results } = await stmt.run();
2727

2828
#### Return value
2929

30-
- <code>results</code>: <Type text="Array"/>
31-
- An array of objects, where each object represents a row of the query result.
30+
- <code>returnValue</code>: <Type text="Object"/>
31+
- An object containing the success status, a meta object, and an array of objects containing the query results.
3232
- For more information on the returned object, refer to [Return objects](/d1/worker-api/return-object).
3333

3434
<Details header="Example of return values" open = {false}>
3535
```js
36-
const stmt = await db.prepare("SELECT name, age FROM users LIMIT 3");
37-
const { results } = await stmt.run();
38-
console.log(results);
36+
const someVariable = `Bs Beverages`;
37+
const stmt = env.DB.prepare("SELECT * FROM Customers WHERE CompanyName = ?").bind(someVariable);
38+
const returnValue = await stmt.run();
39+
```
40+
```js
41+
return Response.json(returnValue);
3942
```
4043
```js output
41-
[
42-
{
43-
name: "John",
44-
age: 42,
45-
},
46-
{
47-
name: "Anthony",
48-
age: 37,
44+
{
45+
"success": true,
46+
"meta": {
47+
"served_by": "miniflare.db",
48+
"duration": 1,
49+
"changes": 0,
50+
"last_row_id": 0,
51+
"changed_db": false,
52+
"size_after": 8192,
53+
"rows_read": 4,
54+
"rows_written": 0
4955
},
56+
"results": [
5057
{
51-
name: "Dave",
52-
age: 29,
53-
},
54-
]
58+
"CustomerId": 11,
59+
"CompanyName": "Bs Beverages",
60+
"ContactName": "Victoria Ashworth"
61+
},
62+
{
63+
"CustomerId": 13,
64+
"CompanyName": "Bs Beverages",
65+
"ContactName": "Random Name"
66+
}
67+
]
68+
}
5569
```
5670
</Details>
5771

5872
#### Guidance
5973

6074
- `results` is empty for write operations such as UPDATE, DELETE, or INSERT.
6175
- When using TypeScript, you can pass a [type parameter](/d1/build-with-d1/d1-client-api/#typescript-support) to `run()` to return a typed result object.
62-
- `stmt.run()` is functionally equivalent to `stmt.all()` and can be treated as an alias.
63-
-
76+
- `stmt.run()` is functionally equivalent to `stmt.all()`, and can be treated as an alias.
77+
- You can choose to extract only the results you expect from the statement by simply returning the `results` property of the return object.
78+
79+
<Details header="Example of returning only the `results`" open={false}>
80+
```js
81+
return Response.json(returnValue.results);
82+
```
83+
```js output
84+
[
85+
{
86+
"CustomerId": 11,
87+
"CompanyName": "Bs Beverages",
88+
"ContactName": "Victoria Ashworth"
89+
},
90+
{
91+
"CustomerId": 13,
92+
"CompanyName": "Bs Beverages",
93+
"ContactName": "Random Name"
94+
}
95+
]
96+
```
97+
</Details>
6498

6599
### `stmt.raw()`
66100

67-
Returns results as an array of arrays, with each row represented by an array. The return type is an array of arrays, and does not include query metadata.
101+
Runs the prepared query (or queries), and returns the results as an array of arrays. The returned results do not include metadata.
68102

69103
Column names are not included in the result set by default. To include column names as the first row of the result array, set `.raw({columnNames: true})`.
70104

71105
```js
72-
const rows = await stmt.raw();
106+
const returnValue = await stmt.raw();
73107
```
74108

75109
#### Parameters
@@ -80,31 +114,47 @@ const rows = await stmt.raw();
80114
#### Return values
81115

82116
- <code>Array</code>: <Type text="Array"/>
83-
- An array of arrays.
84-
- Each array represents a row.
117+
- An array of arrays. Each sub-array represents a row.
85118

86119
<Details header="Example of return values" open = {false}>
87120
```js
88-
const stmt = db.prepare("SELECT name, age FROM users LIMIT 3");
89-
const rows = await stmt.raw();
90-
console.log(rows);
121+
const someVariable = `Bs Beverages`;
122+
const stmt = env.DB.prepare("SELECT * FROM Customers WHERE CompanyName = ?").bind(someVariable);
123+
const returnValue = await stmt.raw(); // columnName not specified
124+
return Response.json(returnValue);
91125
```
92126
```js output
93127
[
94-
[ "John", 42 ],
95-
[ "Anthony", 37 ],
96-
[ "Dave", 29 ],
128+
[11, "Bs Beverages",
129+
"Victoria Ashworth"
130+
],
131+
[13, "Bs Beverages",
132+
"Random Name"
133+
]
97134
]
98135
```
99136

100137
With parameter `columnNames: true`:
101138
```js
102-
const stmt = db.prepare("SELECT name, age FROM users LIMIT 3");
103-
const [columns, ...rows] = await stmt.raw({ columnNames: true });
104-
console.log(columns);
139+
const someVariable = `Bs Beverages`;
140+
const stmt = env.DB.prepare("SELECT * FROM Customers WHERE CompanyName = ?").bind(someVariable);
141+
const returnValue = await stmt.raw({columnNames:true});
142+
return Response.json(returnValue)
105143
```
106144
```js output
107-
[ "name", age ], // The first result array includes the column names
145+
[
146+
[
147+
"CustomerId",
148+
"CompanyName",
149+
"ContactName"
150+
],
151+
[11, "Bs Beverages",
152+
"Victoria Ashworth"
153+
],
154+
[13, "Bs Beverages",
155+
"Random Name"
156+
]
157+
]
108158
```
109159
</Details>
110160

@@ -114,11 +164,10 @@ console.log(columns);
114164

115165
### `stmt.first()`
116166

117-
Returns the first row of the query result. This does not return metadata like the other methods. Instead, it directly returns the object.
167+
Runs the prepared query (or queries), and returns the first row of the query result as an object. This does not return any metadata. Instead, it directly returns the object.
118168

119169
```js
120170
const values = await stmt.first();
121-
const total = await stmt.first("columnName");
122171
```
123172

124173
#### Parameters

0 commit comments

Comments
 (0)