From 193da3e6c7f5df590aeda8d3c94bfbe7324d98fd Mon Sep 17 00:00:00 2001 From: Linden <65407488+thelindat@users.noreply.github.com> Date: Fri, 10 Dec 2021 11:18:15 +1100 Subject: [PATCH] refactor(execute): execute queries after first tick Force queries to wait until the server has ticked before sending anything. --- src/execute.js | 24 +++++++++++++++++++++++- src/index.js | 12 +----------- 2 files changed, 24 insertions(+), 12 deletions(-) diff --git a/src/execute.js b/src/execute.js index edfc6cb..c984562 100644 --- a/src/execute.js +++ b/src/execute.js @@ -1,9 +1,30 @@ import { pool } from './pool'; import { parseParameters } from './parser'; -import { slowQueryWarning, debug, resourceName } from './config'; +import { slowQueryWarning, debug, resourceName, isolationLevel } from './config'; import { FormatError } from './errors'; +let isReady = false; + +const serverReady = () => { + return new Promise(() => { + setTimeout(() => { + return true; + }); + }); +}; + +setImmediate(async () => { + try { + await pool.query(isolationLevel); + isReady = true; + console.log(`^2Database server connection established!^0`); + } catch (error) { + console.log(`^3Unable to establish a connection to the database! [${error.code}]\n${error.message}^0`); + } +}); + const execute = async (query, parameters, resource) => { + if (!isReady) await serverReady(); try { [query, parameters] = parseParameters(query, parameters); @@ -45,6 +66,7 @@ const queryType = (query) => { }; const preparedStatement = async (query, parameters, resource) => { + if (!isReady) await serverReady(); ScheduleResourceTick(resourceName); const connection = await pool.getConnection(); try { diff --git a/src/index.js b/src/index.js index 9ccfbd6..84265ec 100644 --- a/src/index.js +++ b/src/index.js @@ -1,16 +1,6 @@ -import { pool } from './pool'; import { execute, preparedStatement } from './execute'; import { transaction } from './transaction'; -import { debug, isolationLevel } from './config'; - -setImmediate(async () => { - try { - await pool.query(isolationLevel); - console.log(`^2Database server connection established!^0`); - } catch (error) { - console.log(`^3Unable to establish a connection to the database! [${error.code}]\n${error.message}^0`); - } -}); +import { debug } from './config'; const safeCallback = (callback, result) => { if (typeof callback === 'function') callback(result);