Skip to content

Commit

Permalink
[adapter-mysql] client connection support and release pool (#1126)
Browse files Browse the repository at this point in the history
Co-authored-by: pilcrowOnPaper <[email protected]>
  • Loading branch information
jonathanharg and pilcrowonpaper authored Sep 16, 2023
1 parent 1983a8d commit fd595f3
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 20 deletions.
6 changes: 6 additions & 0 deletions .auri/$oex8k1h4.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
package: "@lucia-auth/adapter-mysql"
type: "minor"
---

Added support for client Connection and fixed a bug in Pool connections.
58 changes: 38 additions & 20 deletions packages/adapter-mysql/src/drivers/mysql2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,12 @@ import type {
RowDataPacket,
OkPacket,
ResultSetHeader,
PoolConnection
PoolConnection,
Connection
} from "mysql2/promise";

export const mysql2Adapter = (
db: Pool,
db: Pool | Connection,
tables: {
user: string;
session: string | null;
Expand All @@ -29,23 +30,6 @@ export const mysql2Adapter = (
? escapeName(tables.session)
: null;
const ESCAPED_KEY_TABLE_NAME = escapeName(tables.key);

const transaction = async <
_Execute extends (connection: PoolConnection) => Promise<void>
>(
execute: _Execute
) => {
const connection = await db.getConnection();
try {
await connection.beginTransaction();
await execute(connection);
await connection.commit();
return;
} catch (e) {
await connection.rollback();
throw e;
}
};
return (LuciaError) => {
return {
getUser: async (userId) => {
Expand All @@ -66,7 +50,7 @@ export const mysql2Adapter = (
return;
}
try {
await transaction(async (connection) => {
await transaction(db, async (connection) => {
const [userFields, userValues, userArgs] = helper(user);
await connection.execute(
`INSERT INTO ${ESCAPED_USER_TABLE_NAME} ( ${userFields} ) VALUES ( ${userValues} )`,
Expand Down Expand Up @@ -319,3 +303,37 @@ export const getAll = async <Schema>(
if (!isPacketArray(rows)) return [];
return rows as any;
};

const transaction = async <
_Execute extends (connection: Connection | PoolConnection) => Promise<void>
>(
db: Pool | Connection,
execute: _Execute
) => {
if (isPool(db)) {
const connection = await db.getConnection();
try {
await connection.beginTransaction();
await execute(connection);
await connection.commit();
connection.release();
} catch (e) {
await connection.rollback();
connection.release();
throw e;
}
} else {
try {
await db.beginTransaction();
await execute(db);
await db.commit();
} catch (e) {
await db.rollback();
throw e;
}
}
};

const isPool = (db: Pool | Connection): db is Pool => {
return "getConnection" in db;
};

0 comments on commit fd595f3

Please sign in to comment.