Skip to content
Closed
Show file tree
Hide file tree
Changes from 4 commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
97b15ab
sql: report affectedRows on PostgreSQL and SQLite query results
robobun Aug 25, 2026
891a9ff
sql(sqlite): report 0 affectedRows for EXPLAIN of a write
robobun Aug 25, 2026
a03af16
sql: shorten result metadata comments
robobun Aug 25, 2026
ee5f4b2
sql(sqlite): skip leading comments when classifying the statement
robobun Aug 25, 2026
f0b96a5
sql(sqlite): report null affectedRows for a CTE write without RETURNING
robobun Aug 25, 2026
0dd58e5
sql(sqlite): classify the write verb independently of the first token
robobun Aug 25, 2026
4a73dc5
sql: shorten a parser comment
robobun Aug 25, 2026
1f41110
[autofix.ci] apply automated fixes
autofix-ci[bot] Aug 25, 2026
287545f
sql(sqlite): only accept a write verb at parenthesis depth zero
robobun Aug 25, 2026
5c01aac
sql(sqlite): pin CTE UPDATE tests with WHERE, soften affectedRows docs
robobun Aug 25, 2026
da7328a
sql(sqlite): handle quoted identifiers in comment stripping, pin mult…
robobun Aug 25, 2026
3b5543a
sql: document that multi-result queries carry metadata on the inner a…
robobun Aug 25, 2026
8573e09
Restore the adapter changes lost in the previous commit
robobun Aug 25, 2026
9d8d428
sql: correct the SQLite count docs
robobun Aug 25, 2026
f6c2ed9
ci: retrigger
robobun Aug 25, 2026
611b33b
sql(sqlite): pin the upsert command value
robobun Aug 25, 2026
3977ddc
sql(sqlite): require INTO after REPLACE, reset scan state at statemen…
robobun Aug 25, 2026
57e6ecd
[autofix.ci] apply automated fixes
autofix-ci[bot] Aug 25, 2026
77e4213
sql: reset command at statement boundaries, accept quoted identifiers…
robobun Aug 25, 2026
f0797e6
sql(sqlite): track backtick and bracket identifier quotes in the toke…
robobun Aug 25, 2026
eb8455f
sql(sqlite): reset canReturnRows at statement boundaries
robobun Aug 25, 2026
d30940b
sql(sqlite): treat a quote opener as a token boundary
robobun Aug 25, 2026
3734e2b
sql: shorten a scanner comment
robobun Aug 25, 2026
069157a
sql(sqlite): classify tokens flushed at quote boundaries
robobun Aug 25, 2026
95a439f
sql(sqlite): classify tokens at the closing paren, accept a single-qu…
robobun Aug 25, 2026
4cec6e2
sql(sqlite): treat the opening paren as a token boundary
robobun Aug 25, 2026
ed3c09a
sql: shorten a scanner comment
robobun Aug 25, 2026
11b06ad
sql: drop an over-general claim from the multi-statement docs
robobun Aug 25, 2026
f973e33
sql(sqlite): gate canReturnRows on parenthesis depth
robobun Aug 25, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions docs/runtime/sql.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -1398,6 +1398,22 @@ We also haven't implemented some of the more uncommon features like:

## Common Patterns & Best Practices

### Result metadata

Every query resolves to an array of rows with four extra non-enumerable properties: `command`, `count`, `affectedRows`, and `lastInsertRowid`. `console.log` does not print them, but they are there.

To read how many rows a write changed, use `affectedRows`. It reports the same number on every adapter:

```ts
const result = await sql`UPDATE users SET active = ${false} WHERE age < ${18}`;
console.log(result.affectedRows); // rows updated, on every adapter
```

- `affectedRows`: the number of rows an `INSERT`, `UPDATE`, or `DELETE` changed. `0` for statements that do not write.
- `count`: the number of rows in the result set. On PostgreSQL and SQLite, a write without `RETURNING` reports the affected-row count here instead. On MySQL it is always the number of rows returned, so it is `0` for a plain write. On SQLite, a statement that neither returns rows nor writes (for example `CREATE TABLE`) can report the previous write's count here. Prefer `affectedRows` for portable code.
- `command`: the SQL command that produced the result, such as `"SELECT"` or `"UPDATE"`. `null` on MySQL, whose protocol does not report it.
- `lastInsertRowid`: the row id of the last inserted row on MySQL and SQLite. `null` on PostgreSQL; use `RETURNING` there.

### Working with MySQL Result Sets

```ts
Expand Down
37 changes: 35 additions & 2 deletions packages/bun-types/sql.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -448,11 +448,44 @@ declare module "bun" {
unlisten(): Promise<void>;
}

/**
* Metadata properties present on the array a query resolves to. They are
* non-enumerable, so `console.log` does not print them.
*/
interface ResultMetadata {
/**
* The number of rows in the result set. On PostgreSQL and SQLite, a
* write without `RETURNING` reports the number of affected rows here
* instead. On MySQL it is always the number of rows returned, so it is
* `0` for a plain `INSERT`, `UPDATE`, or `DELETE`. On SQLite, a
* statement that neither returns rows nor writes (for example
* `CREATE TABLE`) can report the previous write's count here.
*/
count: number | null;
Comment thread
robobun marked this conversation as resolved.
Resolved
/**
* The SQL command that produced this result, such as `"SELECT"` or
* `"UPDATE"`. `null` on MySQL, whose protocol does not report it.
*/
command: string | null;
/**
* The number of rows an `INSERT`, `UPDATE`, or `DELETE` changed. `0`
* for statements that do not write. This is the portable way to read
* the affected-row count on every adapter.
*/
affectedRows: number | bigint | null;
/**
* The row id of the last inserted row on MySQL and SQLite. `null` on
* PostgreSQL; use `RETURNING` there.
*/
lastInsertRowid: number | bigint | null;
}

/**
* A pending SQL query. Extends `Promise`, so it can be awaited, and adds
* methods to control how it runs.
* methods to control how it runs. The resolved array also carries
* {@link ResultMetadata}.
*/
interface Query<T> extends Promise<T> {
interface Query<T> extends Promise<T & ResultMetadata> {
/**
* True while the query is executing
*/
Expand Down
12 changes: 12 additions & 0 deletions src/js/internal/sql/postgres.ts
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,18 @@ initPostgres(
}

result.count = count || 0;
// For writes the tag count is rows changed; affectedRows is the adapter-portable field.
switch (result.command) {
case "INSERT":
case "UPDATE":
case "DELETE":
case "MERGE":
result.affectedRows = result.count;
break;
default:
result.affectedRows = 0;
break;
}
Comment thread
robobun marked this conversation as resolved.
Resolved
const last_result = query[_results];

if (!last_result) {
Expand Down
64 changes: 61 additions & 3 deletions src/js/internal/sql/sqlite.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,14 +53,66 @@
}
}

function affectedRowsForCommand(commandString: string, count: number | bigint): number | bigint {
switch (commandString) {
case "INSERT":
case "UPDATE":
case "DELETE":
case "REPLACE":
return count;
default:
// sqlite3_changes() still reports the previous write after e.g. CREATE TABLE.
return 0;
}
}

Check warning on line 67 in src/js/internal/sql/sqlite.ts

View check run for this annotation

Claude / Claude Code Review

SQLite affectedRows is 0 for WITH-prefixed (CTE) writes

`affectedRowsForCommand` gates on `commandString`, which for `WITH cte AS (...) DELETE FROM t ...` resolves to `"WITH"` (parseSQLQuery's after-loop `WITH` case sets `canReturnRows = true` and `lastToken = "WITH"` without changing `command`), so a CTE-prefixed write reports `affectedRows: 0` on SQLite while the same statement on PostgreSQL gets server tag `DELETE N` → `affectedRows = N`. This is the same bug class as the leading-comment and `EXPLAIN` prefixes this PR already fixed — consider
Comment thread
robobun marked this conversation as resolved.
Resolved

/** Skips leading whitespace and SQL comments so the scan sees the statement's first keyword. */
function skipLeadingComments(text: string): string {
let i = 0;
const len = text.length;
while (i < len) {
switch (text[i]) {
case " ":
case "\n":
case "\t":
case "\r":
case "\f":
case "\v":
i++;
continue;
case "-": {
if (text[i + 1] !== "-") {
return text.slice(i);
}
const newline = text.indexOf("\n", i + 2);
if (newline === -1) return "";
i = newline + 1;
continue;
}
case "/": {
if (text[i + 1] !== "*") {
return text.slice(i);
}
const end = text.indexOf("*/", i + 2);
if (end === -1) return "";
i = end + 2;
continue;
}
default:
return i === 0 ? text : text.slice(i);
}
}
return "";
}

/**
* Parse the SQL query and return the command and the last token
* @param query - The SQL query to parse
* @param partial - Whether to stop on the first command we find
* @returns The command, the last token, and whether it can return rows
*/
function parseSQLQuery(query: string, partial: boolean = false): SQLParsedInfo {
const text = query.toUpperCase().trim();
const text = skipLeadingComments(query.toUpperCase().trim());
const text_len = text.length;

let token = "";
Expand Down Expand Up @@ -260,18 +312,24 @@

const sqlResult = $isArray(result) ? new SQLResultArray(result) : new SQLResultArray([result]);

const count = $isArray(result) ? result.length : 1;
sqlResult.command = commandToString(command, parsedInfo.lastToken);
sqlResult.count = $isArray(result) ? result.length : 1;
sqlResult.count = count;
// RETURNING emits one row per affected row; EXPLAIN <write> (lastToken = first token) changes nothing.
sqlResult.affectedRows =
parsedInfo.lastToken === "EXPLAIN" ? 0 : affectedRowsForCommand(sqlResult.command, count);

query.resolve(sqlResult);
} else {
// For INSERT/UPDATE/DELETE/CREATE etc., use db.run() which handles multiple statements natively
const changes = db.run.$call(db, sql, values);
const sqlResult = new SQLResultArray();

sqlResult.command = commandToString(command, parsedInfo.lastToken);
const commandString = commandToString(command, parsedInfo.lastToken);
sqlResult.command = commandString;
sqlResult.count = changes.changes;
sqlResult.lastInsertRowid = changes.lastInsertRowid;
sqlResult.affectedRows = affectedRowsForCommand(commandString, changes.changes);

query.resolve(sqlResult);
}
Expand Down
20 changes: 10 additions & 10 deletions test/integration/bun-types/fixture/sql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,23 +92,23 @@ expectType(
return [await txn<[9]>`SELECT 9`, await txn<[10]>`SELECT 10`];
});

expectType(tx).is<readonly [[9], [10]]>();
expectType(tx).is<readonly [[9] & Bun.SQL.ResultMetadata, [10] & Bun.SQL.ResultMetadata]>();
}

{
const tx = await sql1.begin(async txn => {
return [await txn<[9]>`SELECT 9`, await txn<[10]>`SELECT 10`];
});

expectType(tx).is<readonly [[9], [10]]>();
expectType(tx).is<readonly [[9] & Bun.SQL.ResultMetadata, [10] & Bun.SQL.ResultMetadata]>();
}

{
const tx = await sql1.distributed("name", async txn => {
return [await txn<[9]>`SELECT 9`, await txn<[10]>`SELECT 10`];
});

expectType(tx).is<readonly [[9], [10]]>();
expectType(tx).is<readonly [[9] & Bun.SQL.ResultMetadata, [10] & Bun.SQL.ResultMetadata]>();
}

expectType(sql1.unsafe("SELECT * FROM users")).is<Bun.SQL.Query<any>>();
Expand Down Expand Up @@ -178,8 +178,8 @@ expectType(opts2).extends<Bun.SQL.Options>();
const txCb = (async sql => [sql<[1]>`SELECT 1`]) satisfies Bun.SQL.TransactionContextCallback<unknown>;
const spCb = (async sql => [sql<[2]>`SELECT 2`]) satisfies Bun.SQL.SavepointContextCallback<unknown>;

expectType(await sql.begin(txCb)).is<[1][]>();
expectType(await sql.begin(spCb)).is<[2][]>();
expectType(await sql.begin(txCb)).is<([1] & Bun.SQL.ResultMetadata)[]>();
expectType(await sql.begin(spCb)).is<([2] & Bun.SQL.ResultMetadata)[]>();

expectType(queryA.cancel()).is<Bun.SQL.Query<any>>();
expectType(queryA.simple()).is<Bun.SQL.Query<any>>();
Expand All @@ -194,11 +194,11 @@ expectType(queryNum.execute()).is<Bun.SQL.Query<number>>();
expectType(queryNum.raw()).is<Bun.SQL.Query<number>>();
expectType(queryNum.values()).is<Bun.SQL.Query<number>>();

expectType(await queryNum.cancel()).is<number>();
expectType(await queryNum.simple()).is<number>();
expectType(await queryNum.execute()).is<number>();
expectType(await queryNum.raw()).is<number>();
expectType(await queryNum.values()).is<number>();
expectType(await queryNum.cancel()).is<number & Bun.SQL.ResultMetadata>();
expectType(await queryNum.simple()).is<number & Bun.SQL.ResultMetadata>();
expectType(await queryNum.execute()).is<number & Bun.SQL.ResultMetadata>();
expectType(await queryNum.raw()).is<number & Bun.SQL.ResultMetadata>();
expectType(await queryNum.values()).is<number & Bun.SQL.ResultMetadata>();
Comment thread
claude[bot] marked this conversation as resolved.
Resolved

expectType<Bun.SQL.Options>({
password: () => "hey",
Expand Down
39 changes: 39 additions & 0 deletions test/js/sql/sql-affected-rows.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
// `affectedRows` is the portable affected-row count for writes. MySQL has
// always reported it (from the OK packet, covered in sql-mysql.test.ts).
// PostgreSQL and SQLite used to leave it null and report the count only in
// `count`, so there was no single property that worked on every adapter
// (issue #40432). The SQLite coverage lives in sqlite-sql.test.ts.
import { randomUUIDv7, SQL } from "bun";
import { expect, test } from "bun:test";
import { describeWithContainer } from "harness";

describeWithContainer("postgres", { image: "postgres_plain" }, container => {
const url = () => `postgres://bun_sql_test@${container.host}:${container.port}/bun_sql_test`;

test("affectedRows reports rows changed by writes", async () => {
await container.ready;
await using sql = new SQL({ url: url(), max: 1, idleTimeout: 5, connectionTimeout: 5 });
const table = sql("t_" + randomUUIDv7("hex").replaceAll("-", ""));

const created = await sql`CREATE TEMPORARY TABLE ${table} (id int, price int)`;
expect(created.affectedRows).toBe(0);

const inserted = await sql`INSERT INTO ${table} VALUES (1, 10), (2, 20), (3, 30)`;
expect(inserted.affectedRows).toBe(3);
expect(inserted.count).toBe(3);

const updated = await sql`UPDATE ${table} SET price = price + 1 WHERE price < 25`;
expect(updated.affectedRows).toBe(2);

const returning = await sql`UPDATE ${table} SET price = 0 WHERE id IN (1, 2) RETURNING id`;
expect(returning).toHaveLength(2);
expect(returning.affectedRows).toBe(2);

const selected = await sql`SELECT * FROM ${table}`;
expect(selected.affectedRows).toBe(0);
expect(selected.count).toBe(3);

const deleted = await sql`DELETE FROM ${table} WHERE id > 1`;
expect(deleted.affectedRows).toBe(2);
});
Comment thread
robobun marked this conversation as resolved.
Resolved
});
41 changes: 41 additions & 0 deletions test/js/sql/sqlite-sql.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -872,6 +872,47 @@ describe("Query Execution", () => {
expect(result.command).toBe("DELETE");
});

test("affectedRows reports rows changed by writes", async () => {
const result = await sql`CREATE TABLE gadgets (id INTEGER PRIMARY KEY, price REAL)`;
expect(result.affectedRows).toBe(0);

const inserted = await sql`INSERT INTO gadgets VALUES (1, 10.0), (2, 20.0), (3, 30.0)`;
expect(inserted.affectedRows).toBe(3);

const updated = await sql`UPDATE gadgets SET price = price * 1.1 WHERE price < 25`;
expect(updated.affectedRows).toBe(2);

const returning = await sql`UPDATE gadgets SET price = 0 WHERE id IN (1, 2) RETURNING id`;
expect(returning).toHaveLength(2);
expect(returning.affectedRows).toBe(2);

const selected = await sql`SELECT * FROM gadgets`;
expect(selected.affectedRows).toBe(0);

const deleted = await sql`DELETE FROM gadgets WHERE id > 1`;
expect(deleted.affectedRows).toBe(2);

// CREATE does not inherit the previous write's sqlite3_changes()
const create = await sql`CREATE TABLE gadgets2 (id INTEGER)`;
expect(create.affectedRows).toBe(0);

// EXPLAIN of a write returns plan rows and changes nothing
const explained = await sql`EXPLAIN UPDATE gadgets SET price = 1`;
expect(explained.length).toBeGreaterThan(0);
expect(explained.affectedRows).toBe(0);

// leading comments do not hide the write command
const lineComment = await sql`
-- remove the remaining row
DELETE FROM gadgets WHERE id = 1`;
expect(lineComment.command).toBe("DELETE");
expect(lineComment.affectedRows).toBe(1);

const blockComment = await sql`/* seed */ INSERT INTO gadgets2 VALUES (1), (2)`;
expect(blockComment.command).toBe("INSERT");
expect(blockComment.affectedRows).toBe(2);
});

test("SELECT with various clauses", async () => {
await sql`CREATE TABLE scores (id INTEGER, player TEXT, score INTEGER, team TEXT)`;
await sql`INSERT INTO scores VALUES
Expand Down