Skip to content

Commit

Permalink
Actioning PR feedback.
Browse files Browse the repository at this point in the history
  • Loading branch information
Oxyjun committed Nov 19, 2024
1 parent b7d850d commit cc0de6f
Show file tree
Hide file tree
Showing 5 changed files with 37 additions and 36 deletions.
2 changes: 1 addition & 1 deletion src/content/docs/d1/sql-api/sql-statements.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { Details, Render } from "~/components";

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.

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/d1-binding).
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/d1-database).

## Supported SQLite extensions

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
---
title: D1 binding
title: D1 Database
pcx_content_type: concept
sidebar:
order: 1
Expand All @@ -19,7 +19,7 @@ A D1 binding has the type `D1Database`, and supports a number of methods, as lis

## Methods

### `db.prepare()`
### `prepare()`

Prepares a query statement to be later executed.

Expand All @@ -30,7 +30,7 @@ const stmt = env.DB.prepare("SELECT * FROM Customers WHERE CompanyName = ?").bin

#### Parameters

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

#### Return values
Expand All @@ -46,7 +46,7 @@ const stmt = env.DB.prepare("SELECT * FROM Customers WHERE CompanyName = ?").bin
| `?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.
To bind a parameter, use the `D1PreparedStatement::bind` method.

Order and anonymous examples:

Expand Down Expand Up @@ -91,13 +91,13 @@ const stmt = env.DB.prepare("SELECT * FROM Customers WHERE CompanyName = Bs Beve
// `stmt` is a static statement.
```

### `db.batch()`
### `batch()`

Sends multiple SQL statements inside a single call to the database. This can have a huge performance impact as it reduces latency from network round trips to D1. D1 operates in auto-commit. Our implementation guarantees that each statement in the list will execute and commit, sequentially, non-concurrently.

Batched statements are [SQL transactions](https://www.sqlite.org/lang_transaction.html). If a statement in the sequence fails, then an error is returned for that specific statement, and it aborts or rolls back the entire sequence.

To send batch statements, provide `.batch()` a list of prepared statements and get the results in the same order.
To send batch statements, provide `D1Database::batch` a list of prepared statements and get the results in the same order.

```js
const companyName1 = `Bs Beverages`;
Expand All @@ -112,12 +112,12 @@ const batchResult = await env.DB.batch([
#### Parameters

- <code>statements</code>: <Type text="Array"/>
- An array of `db.prepare()` statements.
- An array of [`D1PreparedStatement`](#prepare)s.

#### Return values

- <code>results</code>: <Type text="Array"/>
- An array of `D1Result` objects containing the results of the `.db.prepare()` statements. Each object is in the array position corresponding to the array position of the initial `db.prepare()` statement within the `statementArray`.
- An array of `D1Result` objects containing the results of the `D1Database::prepare` statements. Each object is in the array position corresponding to the array position of the initial `D1Database::prepare` statement within the `statements`.
- Refer to [`D1Result`](/d1/worker-api/return-object/#d1result) for more information about this object.

<Details header="Example of return values" open={false}>
Expand Down Expand Up @@ -209,7 +209,7 @@ console.log(stmt[1].results);
return Response.json(batchResult);
```

### `db.exec()`
### `exec()`

Executes one or more queries directly without prepared statements or parameter bindings.

Expand All @@ -219,7 +219,7 @@ const returnValue = await env.DB.exec(`SELECT * FROM Customers WHERE CompanyName

#### Parameters

- <code>queryString</code>: <Type text="String"/> <MetaInfo text="Required"/>
- <code>query</code>: <Type text="String"/> <MetaInfo text="Required"/>
- The SQL query statement without parameter binding.

#### Return values
Expand Down Expand Up @@ -249,7 +249,7 @@ return Response.json(returnValue);
- 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`.

### `db.dump`
### `dump`

:::caution
This API only works on databases created during D1's alpha period. Check which version your database uses with `wrangler d1 info <DATABASE_NAME>`.
Expand Down
8 changes: 4 additions & 4 deletions src/content/docs/d1/worker-api/index.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ 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. [Bind the D1 Database](/d1/worker-api/d1-binding).
2. [Prepare a statement](/d1/worker-api/d1-binding/#dbprepare).
1. [Bind the D1 Database](/d1/worker-api/d1-database).
2. [Prepare a statement](/d1/worker-api/d1-database/#dbprepare).
3. [Run the prepared statement](/d1/worker-api/prepared-statements).
4. Analyze the [return object](/d1/worker-api/return-object) (if necessary).

Expand All @@ -20,9 +20,9 @@ Refer to the relevant sections for the API documentation.

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/prepared-statements) `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.
When using the [query statement methods](/d1/worker-api/prepared-statements) `D1PreparedStatement::run`, `D1PreparedStatement::raw` and `D1PreparedStatement::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:
For example, providing an `OrderRow` type as a type parameter to `D1PreparedStatement::run` will return a typed `Array<OrderRow>` object instead of the default `Record<string, unknown>` type:

```ts
// Row definition
Expand Down
29 changes: 15 additions & 14 deletions src/content/docs/d1/worker-api/prepared-statements.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,11 @@ sidebar:

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

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/d1-binding/#dbprepare).
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/d1-database/#dbprepare).

## Methods

### `stmt.run()`
### `run()`

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

Expand Down Expand Up @@ -70,8 +70,8 @@ return Response.json(returnValue);
#### Guidance

- `results` is empty for write operations such as `UPDATE`, `DELETE`, or `INSERT`.
- 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.
- `stmt.run()` is functionally equivalent to `stmt.all()`, and can be treated as an alias.
- When using TypeScript, you can pass a [type parameter](/d1/build-with-d1/d1-client-api/#typescript-support) to `D1PreparedStatement::run` to return a typed result object.
- `D1PreparedStatement::run` is functionally equivalent to `D1PreparedStatement::all`, and can be treated as an alias.
- You can choose to extract only the results you expect from the statement by simply returning the `results` property of the return object.

<Details header="Example of returning only the `results`" open={false}>
Expand All @@ -94,7 +94,7 @@ return Response.json(returnValue.results);
```
</Details>

### `stmt.raw()`
### `raw()`

Runs the prepared query (or queries), and returns the results as an array of arrays. The returned results do not include metadata.

Expand All @@ -106,8 +106,8 @@ const returnValue = await stmt.raw();

#### Parameters

- <code>columnNames</code>: <Type text="Boolean"/> <MetaInfo text="Optional"/>
- A boolean flag which includes column names as the first row of the result array.
- <code>columnNames</code>: <Type text="Object"/> <MetaInfo text="Optional"/>
- A boolean object which includes column names as the first row of the result array.

#### Return values

Expand All @@ -118,7 +118,7 @@ const returnValue = await stmt.raw();
```js
const someVariable = `Bs Beverages`;
const stmt = env.DB.prepare("SELECT * FROM Customers WHERE CompanyName = ?").bind(someVariable);
const returnValue = await stmt.raw(); // columnName not specified
const returnValue = await stmt.raw();
return Response.json(returnValue);
```
```js output
Expand Down Expand Up @@ -158,9 +158,9 @@ return Response.json(returnValue)

#### Guidance

- 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.
- When using TypeScript, you can pass a [type parameter](/d1/build-with-d1/d1-client-api/#typescript-support) to `D1PreparedStatement::raw` to return a typed result array.

### `stmt.first()`
### `first()`

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.

Expand All @@ -177,8 +177,9 @@ const values = await stmt.first();

#### Return values

- <code>firstRow</code>: <Type text="Object"/>
- <code>firstRow</code>: <Type text="Object"/> <MetaInfo text="Optional"/>
- An object containing the first row of the query result.
- The return value will be further filtered to a specific attribute if `columnName` was specified.

- `null`: <Type text="null"/>
- If the query returns no rows.
Expand Down Expand Up @@ -216,7 +217,7 @@ return Response.json(returnValue)

#### Guidance

- If the query returns rows but `column` does not exist, then `first()` throws the `D1_ERROR` exception.
- `stmt.first()` does not alter the SQL query. To improve performance, consider appending `LIMIT 1` to your statement.
- 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.
- If the query returns rows but `column` does not exist, then `D1PreparedStatement::first` throws the `D1_ERROR` exception.
- `D1PreparedStatement::first` does not alter the SQL query. To improve performance, consider appending `LIMIT 1` to your statement.
- When using TypeScript, you can pass a [type parameter](/d1/build-with-d1/d1-client-api/#typescript-support) to `D1PreparedStatement::first` to return a typed result object.

12 changes: 6 additions & 6 deletions src/content/docs/d1/worker-api/return-object.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,14 @@ sidebar:

Some D1 Worker Binding APIs return a typed object.

| D1 Worker Binding API | Return object |
| ------------------------- | ------------- |
| `stmt.run()`, `db.batch()`| `D1Result` |
| `db.exec()` | `D1ExecResult`|
| D1 Worker Binding API | Return object |
| ---------------------------------------------- | ------------- |
| `D1PreparedStatement::run`, `D1Database::batch`| `D1Result` |
| `D1Database::exec` | `D1ExecResult`|

## D1Result

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

- The success status
- A meta object with the internal duration of the operation in milliseconds
Expand Down Expand Up @@ -75,7 +75,7 @@ return Response.json(result)

## D1ExecResult

The method `db.exec()` returns a typed `D1ExecResult` object for each query statement. This object contains:
The method `D1Database::exec` returns a typed `D1ExecResult` object for each query statement. This object contains:

- The number of executed queries
- The duration of the operation in milliseconds
Expand Down

0 comments on commit cc0de6f

Please sign in to comment.