From f424308a316123359f3937d20fb122ec3b4e5b6b Mon Sep 17 00:00:00 2001 From: Ciro Spaciari Date: Tue, 9 Sep 2025 13:49:39 -0700 Subject: [PATCH] fix disconnect inside finalie --- src/sql/mysql/MySQLConnection.zig | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/src/sql/mysql/MySQLConnection.zig b/src/sql/mysql/MySQLConnection.zig index 094fe9411a..8753fec3fc 100644 --- a/src/sql/mysql/MySQLConnection.zig +++ b/src/sql/mysql/MySQLConnection.zig @@ -264,13 +264,37 @@ fn drainInternal(this: *@This()) void { } } } + pub fn finalize(this: *MySQLConnection) void { this.stopTimers(); debug("MySQLConnection finalize", .{}); // Ensure we disconnect before finalizing if (this.status != .disconnected) { - this.disconnect(); + // delay disconnecting to avoid calling JS code inside the finalizer + const DisconnectTask = struct { + connection: *MySQLConnection, + task: jsc.AnyTask, + + fn run(ctx: *@This()) void { + ctx.connection.disconnect(); + + ctx.connection.deref(); + bun.default_allocator.destroy(ctx); + } + + pub fn enqueue(connection: *MySQLConnection) void { + const holder = bun.handleOom(bun.default_allocator.create(@This())); + holder.* = .{ + .connection = connection, + .task = jsc.AnyTask.New(@This(), @This().run).init(holder), + }; + connection.ref(); + connection.vm.enqueueTask(jsc.Task.init(&holder.task)); + } + }; + + DisconnectTask.enqueue(this); } this.js_value = .zero;