From 1ad2c8c1a036f83f2f00342cc69f7ab804cb88dc Mon Sep 17 00:00:00 2001 From: Wolvan Date: Mon, 10 Jan 2022 18:16:52 +0100 Subject: [PATCH] Fix SQL connection on wakeup in heroku When a heroku dyno goes into sleep mode it loses connection to the backend database. Once it is woken back up, no more reads or writes could be done anymore due to a dead connection. This change reinstates a new db connection when the connection is fatally terminated. --- src/MySQLStorage.ts | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/src/MySQLStorage.ts b/src/MySQLStorage.ts index 4eebccb..70b060a 100644 --- a/src/MySQLStorage.ts +++ b/src/MySQLStorage.ts @@ -7,14 +7,23 @@ import { BackendPoll as Poll } from "./Poll"; export default class MySQLStorage extends Storage { #db: mysql.Connection; + #options: mysql.ConnectionOptions; + #createConnection(mysqlInstance?: mysql.Connection): void { + if (!mysqlInstance) this.#db = mysql.createConnection(this.#options); + this.#db.on("error", (err: mysql.QueryError) => { + if (err.fatal) this.#createConnection(); + }); + } + constructor(options: mysql.ConnectionOptions) { super(); + this.#options = options; console.debug("Initiating MySQLStorage."); - this.#db = mysql.createConnection(options); + this.#db = mysql.createConnection(this.#options); + this.#createConnection(this.#db); } async init(): Promise { - await this.#db.promise().connect(); await this.#db.promise().query(` CREATE TABLE IF NOT EXISTS polls ( id INT AUTO_INCREMENT PRIMARY KEY,