From 198aa545ebd4d3937ae34a8a99139c2e323b5c3f Mon Sep 17 00:00:00 2001 From: Joakim Carlstein Date: Fri, 9 Feb 2024 13:10:02 +0100 Subject: [PATCH] fix(mysql): unreference all connections so that the process can exit cleanly In a NodeJS environment it will just work as before, but in a Bun environment it will make the "forced exit" error message disappear and remove the 10 s waiting period when migrations are done. --- .changeset/spotty-singers-shake.md | 5 +++++ packages/mysql/src/index.ts | 10 ++++++++++ 2 files changed, 15 insertions(+) create mode 100644 .changeset/spotty-singers-shake.md diff --git a/.changeset/spotty-singers-shake.md b/.changeset/spotty-singers-shake.md new file mode 100644 index 0000000..6fe0f77 --- /dev/null +++ b/.changeset/spotty-singers-shake.md @@ -0,0 +1,5 @@ +--- +'@emigrate/mysql': patch +--- + +Unreference all connections automatically so that they don't hinder the process from exiting. This is especially needed in Bun environments as it seems to handle sockets differently regarding this matter than NodeJS. diff --git a/packages/mysql/src/index.ts b/packages/mysql/src/index.ts index de253c9..6c009e9 100644 --- a/packages/mysql/src/index.ts +++ b/packages/mysql/src/index.ts @@ -171,6 +171,12 @@ export const createMysqlStorage = ({ table = defaultTable, connection }: MysqlSt async initializeStorage() { const pool = getPool(connection); + pool.on('connection', (connection) => { + // @ts-expect-error stream is not in the types but it's there + // eslint-disable-next-line @typescript-eslint/no-unsafe-call + connection.stream.unref(); + }); + await pool.query('SELECT 1'); try { @@ -268,6 +274,10 @@ export const createMysqlLoader = ({ connection }: MysqlLoaderOptions): LoaderPlu const contents = await fs.readFile(migration.filePath, 'utf8'); const conn = await getConnection(connection); + // @ts-expect-error the connection is not in the types but it's there + // eslint-disable-next-line @typescript-eslint/no-unsafe-call + conn.connection.stream.unref(); + try { await conn.query(contents); } finally {