Skip to content

Commit 8d13b91

Browse files
committed
Offloading some content to Workers API page.
Simplifying RR Sessions sections
1 parent a497e67 commit 8d13b91

File tree

2 files changed

+78
-39
lines changed

2 files changed

+78
-39
lines changed

src/content/docs/d1/features/read-replication.mdx

Lines changed: 70 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -56,35 +56,45 @@ D1 read replication achieves this by attaching a <GlossaryTooltip term="bookmark
5656

5757
Use REST API to enable read replication on your D1 database.
5858

59-
```curl
60-
fetch -X PUT "https://api.cloudflare.com/client/v4/accounts/<accountid>/d1/database/<databaseId>" \
61-
-H "Authorization: Bearer $TOKEN" \
62-
-H "Content-Type:application/json" --data '{ "read_replication": { "mode": "auto" } }'
59+
```ts
60+
const headers = new Headers({
61+
"Authorization": `Bearer ${TOKEN}`
62+
});
63+
64+
await fetch ("/v4/accounts/{account_id}/d1/database/{database_id}", {
65+
method: "PUT",
66+
headers: headers,
67+
body: JSON.stringify(
68+
{ "read_replication": { "mode": "auto" } }
69+
)
70+
}
71+
)
6372
```
6473

6574
If this is your first time using REST API, create an API token. Refer to [Create API token](/fundamentals/api/get-started/create-token/).
6675

6776
### Start a D1 Session without constraints
6877

69-
To start a new D1 Session without any constraints, pass the parameter `first-unconstrained` to `.withSession()`. This is also the default behavior when no parameters are specified.
78+
You can start a new D1 Session without constraints. D1 will route the first read query in the Session to any database instance, which could be either the primary database instance or a read replica.
79+
80+
Use this option if you do not need to read the latest version of the database in the primary database instance.
81+
82+
To do this, do not pass any parameters to `withSession()`.
7083

7184
```ts
7285
// synchronous
73-
let session = env.DB_D1.withSession('first-unconstrained')
74-
const stmt = session.prepare(`SELECT * FROM Customers WHERE CompanyName = 'Bs Beverages'`)
86+
let session = env.DB_D1.withSession()
87+
const stmt = session
88+
.prepare(`SELECT * FROM Customers WHERE CompanyName = 'Bs Beverages'`)
7589
// wait for Session condition, queries within batch have casual consistency
7690
const result = await session.run()
7791
```
7892

79-
`.withSession('first-unconstrained')` directs the first query in the Session (whether read or write) to any database instance. This could be either the primary database instance or a read replica (note that write queries will be forwarded to the primary database instance). This means that:
80-
81-
- The Session may immediately start using read replicas.
82-
- D1 serves the first read query with a version of the database that is as up-to-date as the query needs it to be.
83-
- Subsequent queries in the Session have sequential consistency.
84-
85-
A possible use-case may be displaying blog articles on a website. It is not crucial to display the latest blog article, and therefore the user can start the Session by reading from a read replica. Subsequent queries can also go to the read replica.
93+
- D1 serves the first read query may immediately start using read replicas. This will be a version of the database that is as up-to-date as the query needs it to be.
94+
- Possible use-case: Displaying blog articles on a website. It is not crucial to display the latest blog article, and therefore the user can start the Session by reading from a read replica. Subsequent queries can also go to the read replica.
95+
- Refer to the [D1 Workers Binding API documentation](/d1/worker-api/d1-database#withsession).
8696

87-
#### Example of using `first-unconstrained`
97+
#### Example of a D1 Session without constraints
8898

8999
Suppose you want to develop a feature for displaying “likes” on a social network application.
90100

@@ -97,30 +107,35 @@ async function getLikes(postId: string, db: D1Database, bookmark: string | null)
97107
// NOTE: Achieve sequential consistency with given bookmark,
98108
// or start a new session that can be served by any replica.
99109
const session = db.withSession(bookmark ?? "first-unconstrained");
100-
const { results } = session.prepare("SELECT * FROM likes WHERE postId = ?").bind(postId).run();
110+
const { results } = session
111+
.prepare("SELECT * FROM likes WHERE postId = ?")
112+
.bind(postId)
113+
.run();
101114
return { bookmark: session.getBookmark(), likes: results };
102115
}
103116
```
104117
105118
### Start a D1 Session with a constraint
106119
107-
To start a new D1 Session with the first query reading from the primary database instance, pass the parameter `first-primary` to `.withSession()`.
120+
You can start a new D1 Session by forcing the first read query to go to the primary database instance. Subsequent read queries may read from the read replica.
121+
122+
Use this option if you need to first read from the latest version of the database in the primary database instance.
123+
124+
To do this, pass the parameter `first-primary` to `withSession()`.
108125
109126
```ts
110127
// synchronous
111-
let sess = env.DB_D1.withSession('first-primary')
112-
const stmt = sess.prepare(`SELECT * FROM Customers WHERE CompanyName = 'Bs Beverages'`)
128+
let session = env.DB_D1.withSession('first-primary')
129+
const stmt = session
130+
.prepare(`SELECT * FROM Customers WHERE CompanyName = 'Bs Beverages'`)
113131
// wait for Session condition, queries within batch have casual consistency
114-
const result = await sess.run()
132+
const result = await session.run()
115133
```
116134
117-
`.withSession('first-primary')` directs the first query in the Session (whether read or write) to the primary database instance. This means that:
118-
119135
- D1 serves the first read query of the Session with the latest version of the database, which is the primary database instance.
120136
- Subsequent queries in the Session may use read replicas.
121-
- Subsequent queries in the Session have sequential consistency.
122-
123-
A possible use-case may be reading the score-table of an ongoing sports tournament. It is important for the first read to read the latest data from the primary database instance, but may not need to display subsequent score updates immediately (and therefore suitable to use read replicas for subsequent queries within the same Session).
137+
- Possible use-case: Reading the score-table of an ongoing sports tournament. It is important for the first read to read the latest data from the primary database instance, but may not need to display subsequent score updates immediately (and therefore suitable to use read replicas for subsequent queries within the same Session).
138+
- Refer to the [D1 Workers Binding API documentation](/d1/worker-api/d1-database#withsession).
124139
125140
#### Example of using `first-primary`
126141
@@ -133,38 +148,58 @@ Then, when opening an individual electricity bill statement, we can continue usi
133148
```ts
134149
async function listBillStatements(accountId: string, db: D1Database): ListBillStatementsResult {
135150
const session = db.withSession("first-primary");
136-
const { results } = session.prepare("SELECT * FROM bills WHERE accountId = ?").bind(accountId).run();
151+
const { results } = session
152+
.prepare("SELECT * FROM bills WHERE accountId = ?")
153+
.bind(accountId)
154+
.run();
137155
return { bookmark: session.getBookmark(), bills: results };
138156
}
139157

140158
async function getBillStatement(accountId: string, billId: string, bookmark: string): GetBillStatementResult {
141159
// NOTE: We achieve sequential consistency with the given `bookmark`.
142160
const session = db.withSession(bookmark);
143-
const { results } = session.prepare("SELECT * FROM bills WHERE accountId = ? AND billId = ? LIMIT 1").bind(accountId, billId).first();
161+
const { results } = session
162+
.prepare("SELECT * FROM bills WHERE accountId = ? AND billId = ? LIMIT 1")
163+
.bind(accountId, billId)
164+
.first();
144165
return { bookmark: session.getBookmark(), bill: results };
145166
}
146167
```
147168
148169
### Continue a D1 Session with a bookmark
149170
150-
When continuing an existing Session started with `withSession`, you can provide a `bookmark` parameter from an existing Session.
171+
You can continue an existing Session from a previous Session.
172+
173+
Use this option if you need to read from the specific version of the database which you last read from your previous Session.
174+
175+
To do this, pass the `bookmark` string to `withSession()`.
151176
152177
```ts
153178
// synchronous
154-
let session = env.DB_D1.withSession('00000004-00000002-00004ec6-242180193730387d6b7156959e056db7')
155-
const stmt = session.prepare(`SELECT * FROM Customers WHERE CompanyName = 'Bs Beverages'`)
179+
let session = env.DB_D1.withSession('bookmark_string')
180+
const stmt = session
181+
.prepare(`SELECT * FROM Customers WHERE CompanyName = 'Bs Beverages'`)
156182
// wait for Session condition, queries within batch have casual consistency
157183
const result = await session.run()
158184
```
159185
160-
Starting a Session with a `bookmark` continues an existing Session using the `bookmark` as the reference point. This ensures you read from a version of the database which is at least as up-to-date as the provided `bookmark`.
186+
- Starting a Session with a `bookmark` continues an existing Session using the `bookmark` as the reference point. This ensures you read from a version of the database which is at least as up-to-date as the provided `bookmark`.
187+
- Possible use-case: Reading the score-table of an ongoing sports tournament (a continuation of the example from [Start a D1 Session with a constraint](/d1/features/read-replication/#start-a-d1-session-with-a-constraint)). A user may have started a web browser session and already has a `bookmark`. D1 can serve subsequent read queries within the same Session which is logically consistent, by using the `bookmark`.
188+
- Refer to the [D1 Workers Binding API documentation](/d1/worker-api/d1-database#withsession).
189+
190+
#### Example of using `bookmark`
191+
192+
193+
194+
```ts
195+
//TBC
196+
```
197+
198+
### Check if read replication is enabled
161199
162-
- Subsequent queries in the Session have sequential consistency.
163-
- You can return the last encountered `bookmark` for a given Session using `session.getBookmark()`.
200+
### Disable read replication
164201
165-
A potential use-case may be reading the score-table of an ongoing sports tournament (a continuation of the example from [Start a D1 Session with a constraint](/d1/features/read-replication/#start-a-d1-session-with-a-constraint)). A user may have started a web browser session and already has a `bookmark`. D1 can serve subsequent read queries within the same Session which is logically consistent, by using the `bookmark`.
166202
167-
For more information on Sessions API, refer to the [D1 Workers Binding API documentation](/d1/worker-api/d1-database#withsession).
168203
169204
## Read replica locations
170205

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

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -254,15 +254,19 @@ const session = env.DB.withSession("<parameter>");
254254
#### Parameters
255255

256256
- <code>first-primary</code>: <Type text="String"/><MetaInfo text="Optional"/>
257-
- Directs the first query in the Session (whether read or write) to the primary database instance. Use this option if you need to start the Session with the most up-to-date data from the primary database instance.
257+
- Directs the first query in the Session (whether read or write) to the primary database instance. Use this option if you need to start the Session with the most up-to-date data from the primary database instance.
258+
- Subsequent queries in the Session may use read replicas.
259+
- Subsequent queries in the Session have sequential consistency.
258260

259261
- <code>first-unconstrained</code>: <Type text="String"/><MetaInfo text="Optional"/>
260-
- Directs the first query in the Session (whether read or write) to any database instance. Use this option if you do not need to start the Session with the most up-to-date data, and wish to prioritize minimizing query latency from the very start of the Session.
262+
- Directs the first query in the Session (whether read or write) to any database instance. Use this option if you do not need to start the Session with the most up-to-date data, and wish to prioritize minimizing query latency from the very start of the Session.
263+
- Subsequent queries in the Session have sequential consistency.
264+
- This is the default behavior when no parameters are provided.
261265

262266
- <code>bookmark</code>: <Type text="String"/><MetaInfo text="Optional"/>
263267
- A [`bookmark`](/d1/reference/time-travel/#bookmarks) from an existing D1 Session. This allows you to continue the existing Session using the `bookmark` as a reference point.
264-
265-
- If no parameters are provided, `withSession` defaults to using the `first-unconstrained` parameter.
268+
- Subsequent queries in the Session have sequential consistency.
269+
- You can return the last encountered `bookmark` for a given Session using [`session.getBookmark()`](/d1/worker-api/d1-database/#getbookmark).
266270

267271
#### Return values
268272

0 commit comments

Comments
 (0)