Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
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
4 changes: 2 additions & 2 deletions src/js/bun/sql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ interface PooledConnection {
close(): void;
}

const { Query, SQLQueryFlags } = require("internal/sql/query");
const { Query, SQLQueryFlags, onQuerySettled } = require("internal/sql/query");
const { PostgresAdapter } = require("internal/sql/postgres");
const { MySQLAdapter } = require("internal/sql/mysql");
const { SQLiteAdapter } = require("internal/sql/sqlite");
Expand Down Expand Up @@ -192,7 +192,7 @@ const SQL = function SQL(
return query.reject(pool.queryCancelledError());
}

query.finally(onTransactionQueryDisconnected.bind(transactionQueries, query));
onQuerySettled(query, onTransactionQueryDisconnected.bind(transactionQueries, query));
Comment thread
robobun marked this conversation as resolved.
Resolved

try {
// Use adapter method to get the actual connection
Expand Down
6 changes: 6 additions & 0 deletions src/js/internal/sql/query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -324,6 +324,11 @@ class Query<T, Handle extends BaseQueryHandle<any>> extends PublicPromise<T> {
}
}

// Not `query.finally()`: it calls the replaceable `then()` of `Query`, which starts an async function for each query.
function onQuerySettled(query: Query<any, any>, callback: () => void) {
$pokePromiseAsHandled(query.$then(callback, callback));
}
Comment thread
robobun marked this conversation as resolved.
Resolved

Object.defineProperty(Query, Symbol.species, { value: PublicPromise });
Object.defineProperty(Query, Symbol.toStringTag, { value: "Query" });

Expand Down Expand Up @@ -353,6 +358,7 @@ const enum SQLQueryStatus {

export default {
Query,
onQuerySettled,
SQLQueryFlags,
SQLQueryResultMode,

Expand Down
3 changes: 2 additions & 1 deletion src/js/internal/sql/shared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ const PublicArray = globalThis.Array;
const {
Query,
SQLQueryFlags,
onQuerySettled,
symbols: { _strings, _values },
} = require("internal/sql/query");
const AsyncContextFrame = require("internal/async_context_frame");
Expand Down Expand Up @@ -804,7 +805,7 @@ abstract class BasePooledConnection<ConnectionHandle extends { close(): void; fl

bindQuery(query: QueryType<any, any>, onClose: (err: Error) => void) {
this.queries.add(onClose);
query.finally(onQueryFinish.bind(this, onClose));
onQuerySettled(query, onQueryFinish.bind(this, onClose));
}

protected doRetry() {
Expand Down
99 changes: 99 additions & 0 deletions test/js/sql/sql-pool-transaction-isolation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,19 @@ function firstInterleaving(received: Received[]): string | null {
return null;
}

// Counts the then(), catch() and finally() calls on one query: the client must not call them to learn that it settled.
function countReactionCalls(query: any) {
const calls = { then: 0, catch: 0, finally: 0 };
for (const name of ["then", "catch", "finally"] as const) {
const original = query[name];
query[name] = function (this: unknown, ...args: unknown[]) {
calls[name]++;
return original.apply(this, args);
};
}
return calls;
}

const adapters: Array<{ adapter: "postgres" | "mysql"; mockServer: MockServer; beginCommand: string }> = [
{ adapter: "postgres", mockServer: pgMockServer, beginCommand: "BEGIN" },
{ adapter: "mysql", mockServer: mysqlMockServer, beginCommand: "START TRANSACTION" },
Expand Down Expand Up @@ -439,4 +452,90 @@ describe.each(adapters)("$adapter", ({ adapter, mockServer, beginCommand }) => {
await new Promise<void>(r => server.close(() => r()));
}
});

test("the client does not call then(), catch() or finally() of a query that it runs", async () => {
const received: Received[] = [];
const { port, server } = await mockServer(received);
const sql = new SQL(options(port));
try {
const onPool = sql.unsafe("SELECT 'pool'");
const pool = countReactionCalls(onPool);
await onPool;

// The pool has one connection, so reserve() and begin() show that the connection went back.
const reserved = await sql.reserve();
const onReservation = reserved.unsafe("SELECT 'reservation'");
const reservation = countReactionCalls(onReservation);
await onReservation;
reserved.release();

let transaction: ReturnType<typeof countReactionCalls> | undefined;
await sql.begin(async tx => {
const inTransaction = tx.unsafe("SELECT 'transaction'");
transaction = countReactionCalls(inTransaction);
await inTransaction;
});

// The one call is the `await` of this test.
expect({ pool, reservation, transaction }).toEqual({
pool: { then: 1, catch: 0, finally: 0 },
reservation: { then: 1, catch: 0, finally: 0 },
transaction: { then: 1, catch: 0, finally: 0 },
});
expect(received.map(({ sql }) => sql)).toEqual([
"SELECT 'pool'",
"SELECT 'reservation'",
beginCommand,
"SELECT 'transaction'",
"COMMIT",
]);
} finally {
await sql.close({ timeout: 0 }).catch(() => {});
await new Promise<void>(r => server.close(() => r()));
}
});

test("a query that the client rejects before it sends it gives its connection back", async () => {
const received: Received[] = [];
const { port, server } = await mockServer(received);
const sql = new SQL(options(port));
try {
await sql.unsafe("SELECT 'warm'");
const values: unknown[] = [1];
Object.defineProperty(values, 0, {
enumerable: true,
get() {
throw new Error("thrown by a parameter");
},
});
const error = await sql.unsafe("SELECT 'never sent'", values).then(
() => null,
e => e,
);
expect(error?.message).toBe("thrown by a parameter");

// begin() needs the one connection of the pool with no query on it.
const transaction = await sql.begin(async tx => {
await tx.unsafe("SELECT 'transaction'");
return "committed";
});
expect(transaction).toBe("committed");
expect(received.map(({ sql }) => sql)).toEqual(["SELECT 'warm'", beginCommand, "SELECT 'transaction'", "COMMIT"]);
} finally {
await sql.close({ timeout: 0 }).catch(() => {});
await new Promise<void>(r => server.close(() => r()));
}
});
});

test("sqlite: the client does not call then(), catch() or finally() of a query of a transaction", async () => {
await using sql = new SQL(":memory:");
let calls: ReturnType<typeof countReactionCalls> | undefined;
await sql.begin(async tx => {
const query = tx`SELECT 1`;
calls = countReactionCalls(query);
await query;
});
// The one call is the `await` of this test.
expect(calls).toEqual({ then: 1, catch: 0, finally: 0 });
});
Loading