Skip to content

Commit

Permalink
fix(database/connection): disable typecasting for execute method
Browse files Browse the repository at this point in the history
  • Loading branch information
thelindat committed Jun 17, 2024
1 parent 0f38590 commit 0691160
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 14 deletions.
9 changes: 7 additions & 2 deletions src/database/connection.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import type { Connection, PoolConnection } from 'mysql2/promise';
import type { Connection, PoolConnection, TypeCast } from 'mysql2/promise';
import { scheduleTick } from '../utils/scheduleTick';
import { sleep } from '../utils/sleep';
import { pool } from './pool';
import type { CFXParameters } from 'types';
import { typeCastExecute } from 'utils/typeCast';

(Symbol as any).dispose ??= Symbol('Symbol.dispose');

Expand Down Expand Up @@ -34,7 +35,11 @@ export class MySql {
async execute(query: string, values: CFXParameters = []) {
scheduleTick();

const [result] = await this.connection.execute(query, values);
const [result] = await this.connection.execute({
sql: query,
values: values,
typeCast: typeCastExecute as TypeCast,
});
return result;
}

Expand Down
29 changes: 17 additions & 12 deletions src/utils/typeCast.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,35 @@
import { FieldPacket } from 'mysql2';
import type { TypeCastField, TypeCastNext } from 'mysql2/promise';

const BINARY_CHARSET = 63;

type Field = {
type: string;
length: number;
packet: FieldPacket;
interface Field extends TypeCastField {
charset: number;
string: () => string;
buffer: () => number[];
};
}

export const typeCast = (field: Field, next: () => void) => {
/**
* node-mysql2 v3.9.0 introduced (breaking) typecasting for execute methods.
*/
export function typeCastExecute(field: Field, next: TypeCastNext) {
return next();
}

/**
* mysql-async compatible typecasting.
*/
export function typeCast(field: Field, next: TypeCastNext) {
switch (field.type) {
case 'DATETIME':
case 'DATETIME2':
case 'TIMESTAMP':
case 'TIMESTAMP2':
case 'NEWDATE':
return new Date(field.string()).getTime();
return new Date(field.string() || '').getTime();
case 'DATE':
return new Date(field.string() + ' 00:00:00').getTime();
case 'TINY':
return field.length === 1 ? field.string() === '1' : next();
case 'BIT':
return field.length === 1 ? field.buffer()[0] === 1 : field.buffer()[0];
return field.length === 1 ? field.buffer()?.[0] === 1 : field.buffer()?.[0];
case 'TINY_BLOB':
case 'MEDIUM_BLOB':
case 'LONG_BLOB':
Expand All @@ -38,4 +43,4 @@ export const typeCast = (field: Field, next: () => void) => {
default:
return next();
}
};
}

0 comments on commit 0691160

Please sign in to comment.