Skip to content

Commit 5fec8aa

Browse files
committed
Add docs for rowsRead and rowsWritten
1 parent e0dcc97 commit 5fec8aa

File tree

5 files changed

+135
-2
lines changed

5 files changed

+135
-2
lines changed

docs/databases/d1.md

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -166,3 +166,64 @@ export default {
166166
In this example, we create an array of `Query` objects using `getQueryAll()` from individual `insert` operations and then execute them all in a single batch using `qb.batchExecute()`. This is more efficient than executing each insert query separately.
167167

168168
**Note:** Batch operations in D1 have limitations. Refer to the Cloudflare D1 documentation for details on batch operation constraints.
169+
170+
## Execution Metrics
171+
172+
When you execute a query with `D1QB`, the returned result object contains metrics about the database operation. This includes `rowsRead` and `rowsWritten`, which provide insight into the impact of your query.
173+
174+
- `rowsRead`: The number of rows read from the database to execute the query.
175+
- `rowsWritten`: The number of rows written (inserted, updated, or deleted) to the database.
176+
177+
These metrics can be useful for monitoring and optimizing your database queries.
178+
179+
**Example: Accessing Execution Metrics**
180+
181+
```typescript
182+
import { D1QB } from 'workers-qb';
183+
184+
export interface Env {
185+
DB: D1Database;
186+
}
187+
188+
type User = {
189+
id: number;
190+
name: string;
191+
};
192+
193+
export default {
194+
async fetch(request: Request, env: Env, ctx: ExecutionCountext): Promise<Response> {
195+
const qb = new D1QB(env.DB);
196+
197+
// Example of an insert operation
198+
const insertResult = await qb.insert<User>({
199+
tableName: 'users',
200+
data: { name: 'John Doe' },
201+
returning: ['id', 'name'],
202+
}).execute();
203+
204+
console.log(`Rows written: ${insertResult.rowsWritten}`); // e.g., "Rows written: 1"
205+
206+
// Example of a select operation
207+
const selectResult = await qb.fetchAll<User>({
208+
tableName: 'users',
209+
}).execute();
210+
211+
console.log(`Rows read: ${selectResult.rowsRead}`); // e.g., "Rows read: 5"
212+
213+
return Response.json({
214+
insertedUser: insertResult.results,
215+
allUsers: selectResult.results,
216+
metrics: {
217+
insert: {
218+
rowsWritten: insertResult.rowsWritten,
219+
rowsRead: insertResult.rowsRead,
220+
},
221+
select: {
222+
rowsWritten: selectResult.rowsWritten,
223+
rowsRead: selectResult.rowsRead,
224+
},
225+
},
226+
});
227+
},
228+
};
229+
```

docs/databases/do.md

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -201,3 +201,66 @@ export class MyDurableObject extends DurableObject {
201201
In this example, `fetchAll` is called with `lazy: true` and the generic type specified as `<Item, true>`. The `execute()` method returns a result object where `results` is an `AsyncIterable<Item>`. You can then use an `for await...of` loop to iterate through the results asynchronously, processing items one by one as they are fetched from the database.
202202

203203
**Note:** Lazy queries are particularly useful in Durable Objects to avoid blocking the event loop for extended periods when dealing with large datasets. However, keep in mind that each iteration still involves synchronous storage operations. Optimize your processing logic within the loop to maintain responsiveness.
204+
205+
## Execution Metrics
206+
207+
When you execute a query with `DOQB`, the returned result object contains metrics about the database operation. This includes `rowsRead` and `rowsWritten`, which provide insight into the impact of your query.
208+
209+
- `rowsRead`: The number of rows read from the database to execute the query.
210+
- `rowsWritten`: The number of rows written (inserted, updated, or deleted) to the database.
211+
212+
These metrics can be useful for monitoring and optimizing your database queries within your Durable Object.
213+
214+
**Example: Accessing Execution Metrics**
215+
216+
```typescript
217+
import { DOQB } from 'workers-qb';
218+
219+
export class MyDurableObject extends DurableObject {
220+
#qb: DOQB;
221+
222+
constructor(state: DurableObjectState, env: Env) {
223+
super(state, env);
224+
this.#qb = new DOQB(this.storage.sql);
225+
// ... table creation ...
226+
}
227+
228+
async fetch(request: Request): Promise<Response> {
229+
type Item = {
230+
id: number;
231+
name: string;
232+
};
233+
234+
// Example of an insert operation
235+
const insertResult = this.#qb.insert<Item>({
236+
tableName: 'items',
237+
data: { name: 'Durable Item' },
238+
returning: ['id', 'name'],
239+
}).execute();
240+
241+
console.log(`Rows written: ${insertResult.rowsWritten}`); // e.g., "Rows written: 1"
242+
243+
// Example of a select operation
244+
const selectResult = this.#qb.fetchAll<Item>({
245+
tableName: 'items',
246+
}).execute();
247+
248+
console.log(`Rows read: ${selectResult.rowsRead}`); // e.g., "Rows read: 3"
249+
250+
return Response.json({
251+
insertedItem: insertResult.results,
252+
allItems: selectResult.results,
253+
metrics: {
254+
insert: {
255+
rowsWritten: insertResult.rowsWritten,
256+
rowsRead: insertResult.rowsRead,
257+
},
258+
select: {
259+
rowsWritten: selectResult.rowsWritten,
260+
rowsRead: selectResult.rowsRead,
261+
},
262+
},
263+
});
264+
}
265+
}
266+
```

src/databases/d1.ts

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,15 @@ import { D1Result, QueryBuilderOptions } from '../interfaces'
44
import { MigrationOptions, asyncMigrationsBuilder } from '../migrations'
55
import { Query } from '../tools'
66

7+
interface D1Database {
8+
prepare: any
9+
batch: any
10+
exec: any
11+
}
12+
713
export class D1QB extends QueryBuilder<D1Result> {
814
public db: any
9-
constructor(db: any, options?: QueryBuilderOptions) {
15+
constructor(db: D1Database, options?: QueryBuilderOptions) {
1016
super(options)
1117
this.db = db
1218
}

src/databases/do.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import { syncLoggerWrapper } from '../logger'
55
import { MigrationOptions, syncMigrationsBuilder } from '../migrations'
66
import { Query } from '../tools'
77

8-
export interface SqlStorage {
8+
interface SqlStorage {
99
exec: any
1010
prepare: any
1111
Cursor: any

tests/unit/batch.test.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,9 @@ describe('Batch Builder', () => {
1717
batch: (stmts: any) => {
1818
return Promise.resolve(stmts.map((stmt: any) => stmt.all()))
1919
},
20+
exec: () => {
21+
throw new Error('not implemented')
22+
},
2023
}
2124

2225
const qb = new D1QB(dbMock)

0 commit comments

Comments
 (0)