Skip to content
Merged
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
10 changes: 8 additions & 2 deletions src/workerd/api/sql.c++
Original file line number Diff line number Diff line change
Expand Up @@ -309,6 +309,13 @@ jsg::JsValue SqlStorage::Cursor::one(jsg::Lock& js) {
return result;
}

void SqlStorage::Cursor::close() {
KJ_IF_SOME(s, state) {
endQuery(*s);
}
Comment thread
alsuren marked this conversation as resolved.
Resolved
KJ_DASSERT(state == kj::none);
}
Comment thread
alsuren marked this conversation as resolved.
Resolved

jsg::Ref<SqlStorage::Cursor::RowIterator> SqlStorage::Cursor::rows(jsg::Lock& js) {
return js.alloc<RowIterator>(IteratorState{.cursor = JSG_THIS});
}
Expand Down Expand Up @@ -408,8 +415,7 @@ kj::Maybe<v8::LocalVector<v8::Value>> SqlStorage::Cursor::iteratorImpl(jsg::Lock
// GC'ed, which might prevent the cache from being effective in the meantime.
//
// Unfortunately, this does not help with the case where the application stops iterating with
// results still available from the cursor. There's not much we can do about that case since
// there's no way to know if the app might come back and try to use the cursor again later.
// results still available from the cursor. Such applications need to call close().
query.nextRow();
if (query.isDone()) {
endQuery(stateRef);
Expand Down
8 changes: 7 additions & 1 deletion src/workerd/api/sql.h
Original file line number Diff line number Diff line change
Expand Up @@ -205,20 +205,25 @@ class SqlStorage::Cursor final: public jsg::Object {
JSG_METHOD(next);
JSG_METHOD(toArray);
JSG_METHOD(one);
JSG_METHOD(close);
JSG_DISPOSE(close);

JSG_ITERABLE(rows);
JSG_METHOD(raw);
JSG_READONLY_PROTOTYPE_PROPERTY(columnNames, getColumnNames);
JSG_READONLY_PROTOTYPE_PROPERTY(rowsRead, getRowsRead);
JSG_READONLY_PROTOTYPE_PROPERTY(rowsWritten, getRowsWritten);

JSG_TS_DEFINE(type SqlStorageValue = ArrayBuffer | string | number | null);
// Extends `Disposable` because TypeScript before 5.2 has no `Symbol.dispose`.
JSG_TS_DEFINE(type SqlStorageValue = ArrayBuffer | string | number | null;
interface SqlStorageCursor<T extends Record<string, SqlStorageValue>> extends Disposable {});
Comment thread
alsuren marked this conversation as resolved.
Resolved
JSG_TS_OVERRIDE(<T extends Record<string, SqlStorageValue>> {
[Symbol.iterator](): IterableIterator<T>;
raw<U extends SqlStorageValue[]>(): IterableIterator<U>;
next(): IteratorResult<T, undefined>;
toArray(): T[];
one(): T;
close(): void;
columnNames: string[];
});

Expand All @@ -244,6 +249,7 @@ class SqlStorage::Cursor final: public jsg::Object {
RowIterator::Next next(jsg::Lock& js);
jsg::JsArray toArray(jsg::Lock& js);
jsg::JsValue one(jsg::Lock& js);
void close();

void visitForMemoryInfo(jsg::MemoryTracker& tracker) const {
if (state != kj::none) {
Expand Down
14 changes: 9 additions & 5 deletions src/workerd/api/tests/sql-test-tail.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,20 +22,20 @@ export const test = {
return acc;
}, {});
assert.deepStrictEqual(reduced, {
durable_object_storage_exec: 294,
durable_object_storage_exec: 341,
durable_object_storage_ingest: 1030,
durable_object_storage_getDatabaseSize: 3,
durable_object_storage_put: 18,
durable_object_storage_get: 18,
durable_object_storage_transaction: 8,
durable_object_subrequest: 48,
durable_object_subrequest: 52,
// Inner spans nested under durable_object_subrequest: jsRpcSession for RPC
// dispatches (one per call, client-side only -- the server's jsrpc-typed
// onset is its equivalent), fetch for fetch dispatches.
jsRpcSession: 36,
jsRpcSession: 40,
fetch: 12,
// jsRpcCall: 36 client-side + 36 server-side.
jsRpcCall: 72,
// jsRpcCall: 40 client-side + 40 server-side.
jsRpcCall: 80,
durable_object_storage_deleteAll: 1,
createStringTable: 4,
runActorFunc: 4,
Expand All @@ -45,6 +45,10 @@ export const test = {
testRollbackKvInit: 1,
testRollbackAlarmInit: 1,
testCursorUaf: 1,
testCursorClose: 1,
stashCursor: 1,
closeOtherCursor: 1,
closeStashedCursor: 1,
durable_object_storage_setAlarm: 2,
durable_object_storage_getAlarm: 1,
testSessionsAPIBookmark: 20,
Expand Down
184 changes: 184 additions & 0 deletions src/workerd/api/tests/sql-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ import { DurableObject } from 'cloudflare:workers';
// it easier to keep the DO and test functions together in the test file:
let actorFuncs = {};

// Lets one Durable Object reach a cursor that another one created.
let stashedCursor;

async function test(state) {
const storage = state.storage;
const sql = storage.sql;
Expand Down Expand Up @@ -1499,6 +1502,170 @@ export class DurableObjectExample extends DurableObject {
const rows = cursor.toArray();
assert.deepEqual(rows, [{ value: 1 }, { value: 2 }, { value: 3 }]);
}

async testCursorClose() {
const sql = this.state.storage.sql;
sql.exec('CREATE TABLE close_big (id INTEGER PRIMARY KEY)');
sql.exec(`INSERT INTO close_big (id)
WITH RECURSIVE t(x) AS (SELECT 1 UNION ALL SELECT x+1 FROM t LIMIT 10) SELECT x FROM t`);
const selectBig = 'SELECT id FROM close_big ORDER BY id';

const createOther = () => {
sql.exec('CREATE TABLE close_other (v INTEGER)');
sql.exec('CREATE INDEX close_other_v ON close_other (v)');
};
const dropOther = () => {
sql.exec('DROP INDEX close_other_v');
sql.exec('DROP TABLE close_other');
};

// Without close(), the DROP fails.
{
createOther();
const cursor = sql.exec(selectBig);
cursor.next();
assert.throws(() => dropOther(), /SQLITE_LOCKED/);
cursor.close();
dropOther();
}

// close() after a partial for...of.
{
createOther();
const cursor = sql.exec(selectBig);
for (const row of cursor) {
if (row.id === 3) break;
}
cursor.close();
dropOther();
}

// `using` and break.
{
createOther();
{
using cursor = sql.exec(selectBig);
for (const row of cursor.raw()) {
if (row[0] === 3) break;
}
}
dropOther();
}

// `using` and throw.
{
createOther();
assert.throws(() => {
using cursor = sql.exec(selectBig);
cursor.next();
throw new Error('stop');
}, /^Error: stop$/);
dropOther();
}

// `using` in a generator whose consumer stops early.
{
createOther();
function* ids() {
using cursor = sql.exec(selectBig);
for (const row of cursor) yield row.id;
}
for (const id of ids()) {
if (id === 3) break;
}
dropOther();
}

{
createOther();
const cursor = sql.exec(selectBig);
cursor.next();
cursor[Symbol.dispose]();
dropOther();
}

{
const cursor = sql.exec(selectBig);
cursor.next();
cursor.next();
cursor.close();
assert.deepEqual(cursor.next(), { done: true });
assert.deepEqual(cursor.toArray(), []);
assert.deepEqual([...cursor.raw()], []);
assert.throws(() => cursor.one(), /got no results/);
assert.deepEqual(cursor.columnNames, ['id']);
// The second next() stepped to the third row.
assert.equal(cursor.rowsRead, 3);
assert.equal(cursor.rowsWritten, 0);

cursor.close();
cursor[Symbol.dispose]();
assert.equal(cursor.rowsRead, 3);
}

{
const cursor = sql.exec(selectBig);
assert.equal(cursor.toArray().length, 10);
cursor.close();
assert.equal(cursor.rowsRead, 10);
}

{
const cursor = sql.exec(selectBig);
cursor.next();
cursor.close();
using again = sql.exec(selectBig);
assert.equal(again.reusedCachedQueryForTest, true);
}

// close() after a failed step.
{
createOther();
const cursor = sql.exec(
`SELECT CASE WHEN id = 3 THEN json('not json') ELSE id END AS v FROM close_big ORDER BY id`
);
cursor.next();
// Reading the second row steps to the third, which fails.
assert.throws(() => cursor.next(), /malformed JSON/);
cursor.close();
assert.deepEqual(cursor.next(), { done: true });
dropOther();
}

sql.exec('DROP TABLE close_big');
}

async stashCursor() {
const sql = this.state.storage.sql;
sql.exec('CREATE TABLE close_stashed (id INTEGER PRIMARY KEY)');
sql.exec('INSERT INTO close_stashed VALUES (1), (2), (3)');
stashedCursor = sql.exec('SELECT id FROM close_stashed ORDER BY id');
stashedCursor.next();
}

// Like the cursor's other methods, close() throws in another Durable Object.
async closeOtherCursor() {
const differentDo = /different Durable Object/;
assert.throws(() => stashedCursor.next(), differentDo);
assert.throws(() => stashedCursor.close(), differentDo);
assert.throws(() => stashedCursor[Symbol.dispose](), differentDo);

const original = new Error('original');
try {
using _cursor = stashedCursor;
throw original;
} catch (e) {
assert.ok(e instanceof SuppressedError);
assert.match(e.error.message, differentDo);
assert.equal(e.suppressed, original);
}
}

async closeStashedCursor() {
stashedCursor.close();
stashedCursor = undefined;
this.state.storage.sql.exec('DROP TABLE close_stashed');
}
}

export default {
Expand Down Expand Up @@ -1814,3 +1981,20 @@ export let testCursorUaf = {
await stub.testCursorUaf();
},
};

export let testCursorClose = {
async test(ctrl, env, ctx) {
let stub = env.ns.get(env.ns.idFromName('cursor-close-test'));
await stub.testCursorClose();
},
};

export let testCursorCloseInOtherDurableObject = {
async test(ctrl, env, ctx) {
let owner = env.ns.get(env.ns.idFromName('cursor-close-owner'));
let other = env.ns.get(env.ns.idFromName('cursor-close-other'));
await owner.stashCursor();
await other.closeOtherCursor();
await owner.closeStashedCursor();
},
};
4 changes: 4 additions & 0 deletions types/generated-snapshot/experimental/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3624,12 +3624,16 @@ interface SqlStorage {
}
declare abstract class SqlStorageStatement {}
type SqlStorageValue = ArrayBuffer | string | number | null;
interface SqlStorageCursor<
T extends Record<string, SqlStorageValue>,
> extends Disposable {}
declare abstract class SqlStorageCursor<
T extends Record<string, SqlStorageValue>,
> {
next(): IteratorResult<T, undefined>;
toArray(): T[];
one(): T;
close(): void;
raw<U extends SqlStorageValue[]>(): IterableIterator<U>;
columnNames: string[];
get rowsRead(): number;
Expand Down
4 changes: 4 additions & 0 deletions types/generated-snapshot/experimental/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3630,12 +3630,16 @@ export interface SqlStorage {
}
export declare abstract class SqlStorageStatement {}
export type SqlStorageValue = ArrayBuffer | string | number | null;
export interface SqlStorageCursor<
T extends Record<string, SqlStorageValue>,
> extends Disposable {}
export declare abstract class SqlStorageCursor<
T extends Record<string, SqlStorageValue>,
> {
next(): IteratorResult<T, undefined>;
toArray(): T[];
one(): T;
close(): void;
raw<U extends SqlStorageValue[]>(): IterableIterator<U>;
columnNames: string[];
get rowsRead(): number;
Expand Down
4 changes: 4 additions & 0 deletions types/generated-snapshot/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3460,12 +3460,16 @@ interface SqlStorage {
}
declare abstract class SqlStorageStatement {}
type SqlStorageValue = ArrayBuffer | string | number | null;
interface SqlStorageCursor<
T extends Record<string, SqlStorageValue>,
> extends Disposable {}
declare abstract class SqlStorageCursor<
T extends Record<string, SqlStorageValue>,
> {
next(): IteratorResult<T, undefined>;
toArray(): T[];
one(): T;
close(): void;
raw<U extends SqlStorageValue[]>(): IterableIterator<U>;
columnNames: string[];
get rowsRead(): number;
Expand Down
4 changes: 4 additions & 0 deletions types/generated-snapshot/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3469,12 +3469,16 @@ export interface SqlStorage {
}
export declare abstract class SqlStorageStatement {}
export type SqlStorageValue = ArrayBuffer | string | number | null;
export interface SqlStorageCursor<
T extends Record<string, SqlStorageValue>,
> extends Disposable {}
export declare abstract class SqlStorageCursor<
T extends Record<string, SqlStorageValue>,
> {
next(): IteratorResult<T, undefined>;
toArray(): T[];
one(): T;
close(): void;
raw<U extends SqlStorageValue[]>(): IterableIterator<U>;
columnNames: string[];
get rowsRead(): number;
Expand Down
Loading