Skip to content

Commit 1684e9c

Browse files
committed
Fleshing out API chapters.
1 parent ce19b83 commit 1684e9c

File tree

2 files changed

+65
-101
lines changed

2 files changed

+65
-101
lines changed

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

Lines changed: 34 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,14 +21,16 @@ Example of a prepared statement:
2121

2222
```js
2323
const stmt = db.prepare("SELECT * FROM users WHERE name = ?1").bind(someVariable);
24-
// someVariable will replace the placeholder '?1' in the query.
24+
// A variable (someVariable) will replace the placeholder '?1' in the query.
25+
// This is a prepared statement.
2526
```
2627

2728
Example of a static statement:
2829

2930
```js
3031
const stmt = db.prepare('SELECT * FROM users WHERE name = "John Doe"');
31-
// "John Doe" is hard-coded into the query. This is a static statement.
32+
// "John Doe" is hard-coded into the query.
33+
// This is a static statement.
3234
```
3335

3436
#### Parameters
@@ -49,6 +51,32 @@ const stmt = db.prepare('SELECT * FROM users WHERE name = "John Doe"');
4951
```js
5052
const stmt = db.prepare(`SELECT * FROM users WHERE name = "Anthony"; SELECT * FROM users WHERE name = ?1`).bind("Joe")
5153
```
54+
- 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.
55+
56+
| Syntax | Type | Description |
57+
| ------ | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
58+
| `?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` |
59+
| `?` | 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 |
60+
61+
To bind a parameter, use the `stmt.bind()` method.
62+
63+
Order and anonymous examples:
64+
65+
```js
66+
const stmt = db.prepare("SELECT * FROM users WHERE name = ?").bind("John Doe");
67+
```
68+
69+
```js
70+
const stmt = db
71+
.prepare("SELECT * FROM users WHERE name = ? AND age = ?")
72+
.bind("John Doe", 41);
73+
```
74+
75+
```js
76+
const stmt = db
77+
.prepare("SELECT * FROM users WHERE name = ?2 AND age = ?1")
78+
.bind(41, "John Doe");
79+
```
5280

5381
### `db.batch()`
5482

@@ -123,7 +151,7 @@ console.log(rows[1].results);
123151

124152
### `db.exec()`
125153

126-
Executes one or more queries directly without prepared statements or parameters binding. This method can have poorer performance (prepared statements can be reused in some cases) and, more importantly, is less safe. Only use this method for maintenance and one-shot tasks (for example, migration jobs). The input can be one or multiple queries separated by `\n`.
154+
Executes one or more queries directly without prepared statements or parameters binding.
127155

128156
```js
129157
const migration = await fetch("/migration.sql");
@@ -156,6 +184,9 @@ console.log(out);
156184
#### Guidance
157185

158186
- If an error occurs, an exception is thrown with the query and error messages, execution stops and further statements are not executed. Refer to [Errors](/d1/build-with-d1/d1-client-api/#errors) to learn more.
187+
- This method can have poorer performance (prepared statements can be reused in some cases) and, more importantly, is less safe.
188+
- Only use this method for maintenance and one-shot tasks (for example, migration jobs).
189+
- The input can be one or multiple queries separated by `\n`.
159190

160191
### `db.dump`
161192

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

Lines changed: 31 additions & 98 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
---
2-
title: D1 Query
2+
title: D1 query
33
pcx_content_type: concept
44
sidebar:
55
order: 2
@@ -13,32 +13,30 @@ You can modify the query results which has been obtained after executing a `.db(
1313

1414
## Methods
1515

16-
### await stmt.all()
16+
### `await stmt.run()`
1717

18-
Returns all rows as an array of objects, with each result row represented as an object on the `results` property of the `D1Result` type.
18+
Runs the query (or queries) and returns results.
1919

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

24-
#### Parameters
24+
#### Parameter
2525

2626
- None.
2727

28-
#### Return values
28+
#### Return value
2929

30-
- <code>Array</code>: <Type text="Array"/>
31-
- An array of objects.
32-
- Each row represents a row.
33-
- Each object is created on the `results` property of the `D1Result` type.
30+
- <code>results</code>: <Type text="Array"/>
31+
- An array of objects, where each object represents a row of the query result.
32+
- Each object is created on the `results` property of the `D1Result` type. {/*What does it return when `results` is actually empty?*/}
3433

3534
<Details header="Example of return values" open = {false}>
3635
```js
37-
const stmt = db.prepare("SELECT name, age FROM users LIMIT 3");
38-
const { results } = await stmt.all();
36+
const stmt = await db.prepare("SELECT name, age FROM users LIMIT 3");
37+
const { results } = await stmt.run();
3938
console.log(results);
4039
```
41-
4240
```js output
4341
[
4442
{
@@ -59,10 +57,12 @@ console.log(results);
5957

6058
#### Guidance
6159

62-
- When joining tables with identical column names, only the leftmost column will be included in the row object. Use [`stmt.raw()`](#await-stmtraw) to return all rows as an array of arrays.
63-
- When using TypeScript, you can pass a [type parameter](/d1/build-with-d1/d1-client-api/#typescript-support) to `all()` to return a typed result object.
60+
- `results` is empty for write operations such as UPDATE, DELETE, or INSERT.
61+
- 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+
-
6464

65-
### await stmt.raw()
65+
### `await stmt.raw()`
6666

6767
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.
6868

@@ -112,7 +112,7 @@ console.log(columns);
112112

113113
- When using TypeScript, you can pass a [type parameter](/d1/build-with-d1/d1-client-api/#typescript-support) to `raw()` to return a typed result array.
114114

115-
### await stmt.first()
115+
### `await stmt.first()`
116116

117117
Returns the first row of the query result. This does not return metadata like the other methods. Instead, it directly returns the object.
118118

@@ -167,30 +167,32 @@ console.log(total);
167167
- `stmt.first()` does not alter the SQL query. To improve performance, consider appending `LIMIT 1` to your statement.
168168
- When using TypeScript, you can pass a [type parameter](/d1/build-with-d1/d1-client-api/#typescript-support) to `first()` to return a typed result object.
169169

170-
### await stmt.run()
170+
{/* ### `stmt.all()`
171171
172-
Runs the query (or queries) and returns results.
172+
Returns all rows as an array of objects, with each result row represented as an object on the `results` property of the `D1Result` type.
173173
174174
```js
175-
const { results } = await stmt.run();
175+
const { results } = await stmt.all();
176176
```
177177
178-
#### Parameter
178+
#### Parameters
179179
180180
- None.
181181
182-
#### Return value
182+
#### Return values
183183
184-
- <code>results</code>: <Type text="Array"/>
185-
- An array of objects, where each object represents a row of the query result.
186-
- Each object is created on the `results` property of the `D1Result` type. {/*What does it return when `results` is actually empty?*/}
184+
- <code>Array</code>: <Type text="Array"/>
185+
- An array of objects.
186+
- Each row represents a row.
187+
- Each object is created on the `results` property of the `D1Result` type.
187188
188189
<Details header="Example of return values" open = {false}>
189190
```js
190-
const stmt = await db.prepare("SELECT name, age FROM users LIMIT 3");
191-
const { results } = await stmt.run();
191+
const stmt = db.prepare("SELECT name, age FROM users LIMIT 3");
192+
const { results } = await stmt.all();
192193
console.log(results);
193194
```
195+
194196
```js output
195197
[
196198
{
@@ -211,74 +213,5 @@ console.log(results);
211213
212214
#### Guidance
213215
214-
- `results` is empty for write operations such as UPDATE, DELETE, or INSERT.
215-
- Run is functionally equivalent to `stmt.all()` and can be treated as an alias.
216-
- 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.
217-
218-
### await db.dump()
219-
220-
:::caution
221-
This API only works on databases created during D1's alpha period. Check which version your database uses with `wrangler d1 info <DATABASE_NAME>`.
222-
:::
223-
224-
Dumps the entire D1 database to an SQLite compatible file inside an ArrayBuffer.
225-
226-
```js
227-
const dump = await db.dump();
228-
return new Response(dump, {
229-
status: 200,
230-
headers: {
231-
"Content-Type": "application/octet-stream",
232-
},
233-
});
234-
```
235-
236-
#### Parameters
237-
238-
- None.
239-
240-
#### Return values
241-
242-
- ???
243-
244-
#### Guidance
245-
246-
- ???
247-
248-
### await db.exec()
249-
250-
Executes one or more queries directly without prepared statements or parameters binding.
251-
252-
```js
253-
const out = await db.exec();
254-
```
255-
256-
#### Parameters
257-
258-
- ???
259-
260-
#### Return values
261-
262-
- ???
263-
264-
<Details header="Example of return values" open={false}>
265-
```js
266-
const migration = await fetch("/migration.sql");
267-
const out = await db.exec(migration.text());
268-
console.log(out);
269-
```
270-
```js output
271-
{
272-
count: 80,
273-
duration: 76
274-
}
275-
```
276-
</Details>
277-
278-
#### Guidance
279-
280-
- This method can have poorer performance (prepared statements can be reused in some cases) and, more importantly, is less safe.
281-
- Only use this method for maintenance and one-shot tasks (for example, migration jobs).
282-
- The input can be one or multiple queries separated by `\n`.
283-
- If an error occurs, an exception is thrown with the query and error messages, execution stops and further statements are not executed. Refer to [Errors](/d1/build-with-d1/d1-client-api/#errors) to learn more.
284-
216+
- When joining tables with identical column names, only the leftmost column will be included in the row object. Use [`stmt.raw()`](#await-stmtraw) to return all rows as an array of arrays.
217+
- When using TypeScript, you can pass a [type parameter](/d1/build-with-d1/d1-client-api/#typescript-support) to `all()` to return a typed result object. */}

0 commit comments

Comments
 (0)