Skip to content

Commit

Permalink
fix(db/execute): Parse responses during prepare
Browse files Browse the repository at this point in the history
Prepare should return the most appropriate result type (scalar, single, query, update, etc.)
  • Loading branch information
thelindat committed Feb 10, 2022
1 parent 553775c commit 4975a17
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 11 deletions.
17 changes: 7 additions & 10 deletions src/database/rawExecute.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { QueryError } from 'mysql2';
import { QueryError, ResultSetHeader, RowDataPacket } from 'mysql2';
import { pool } from '.';
import { scheduleTick } from '../config';
import { logQuery } from '../logger';
import { CFXCallback, CFXParameters, QueryResponse } from '../types';
import { parseResponse } from '../utils/parseResponse';
import { parseExecute } from '../utils/parseExecute';

export const rawExecute = async (
Expand All @@ -24,26 +25,22 @@ export const rawExecute = async (
let result: QueryResponse;

try {
const executionTime = process.hrtime();

if (!parameters.every(Array.isArray)) parameters = [[...parameters]];

const results = [];
const results = [] as RowDataPacket;
const executionTime = process.hrtime();

for (const params of parameters) {
results.push((await connection.execute(query, params))[0]);

results.push(parseResponse(type, (await connection.execute(query, params))[0]));
logQuery(invokingResource, query, process.hrtime(executionTime)[1] / 1e6, params as typeof parameters);
}

result = results;

//TODO any giggle
if (results.length === 1) {
if (type === 'execute') {
if ((results as any)[0][0] && Object.keys((results as any)[0][0]).length === 1)
result = Object.values((results as any)[0][0])[0] as any;
else result = (results as any)[0][0];
if (results[0][0] && Object.keys(results[0][0]).length === 1) result = Object.values(results[0][0])[0] as any;
else result = results[0][0];
} else {
result = results[0];
}
Expand Down
2 changes: 1 addition & 1 deletion src/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ type SQLResponse = RowDataPacket[][] | RowDataPacket[] | OkPacket | OkPacket[] |

export type QueryResponse = SQLResponse | SQLResponse[] | RowDataPacket;

export type QueryType = 'insert' | 'update' | 'scalar' | 'single' | null;
export type QueryType = 'execute' | 'insert' | 'update' | 'scalar' | 'single' | null;

export type TransactionQuery = {
query: string;
Expand Down

0 comments on commit 4975a17

Please sign in to comment.