From a9615553221706967527ee51e5387b16cf12cd12 Mon Sep 17 00:00:00 2001 From: Marvin Borner Date: Sat, 18 Jul 2020 14:54:20 +0200 Subject: DATABASE MAGIC --- src/db/DBController.ts | 51 ++++++++++++++++++++++++++------------------------ src/db/tables.sql | 5 +++++ src/db/tables.ts | 1 - 3 files changed, 32 insertions(+), 25 deletions(-) create mode 100644 src/db/tables.sql delete mode 100644 src/db/tables.ts (limited to 'src/db') diff --git a/src/db/DBController.ts b/src/db/DBController.ts index 67c6afc..57c640b 100644 --- a/src/db/DBController.ts +++ b/src/db/DBController.ts @@ -1,31 +1,34 @@ import { Client } from "https://deno.land/x/mysql/mod.ts"; -import tables from "./tables.ts"; +import { readFileStr } from "https://deno.land/std/fs/mod.ts"; export default class DBController { - async init() { - const conn = await this.connect(); - try { - tables.forEach((table) => conn.execute(table)); - console.log("Tables created"); - } catch (e) { - console.error("Could not create tables"); - throw e; - } finally { - conn.close(); + async init() { + const conn = await this.connect(); + try { + const sql = await readFileStr("./src/db/tables.sql"); + const queries = sql.split(";"); + queries.pop(); + queries.forEach((query) => conn.execute(query)); + console.log("Tables created"); + } catch (e) { + console.error("Could not create tables"); + throw e; + } finally { + conn.close(); + } } - } - async connect(): Promise { - try { - return await new Client().connect({ - hostname: Deno.env.get("DBHost"), - username: Deno.env.get("DBUser"), - db: Deno.env.get("DBName"), - password: Deno.env.get("DBPassword"), - }); - } catch (e) { - console.error("Could not connect to database"); - throw e; + async connect(): Promise { + try { + return await new Client().connect({ + hostname: Deno.env.get("DBHost"), + username: Deno.env.get("DBUser"), + db: Deno.env.get("DBName"), + password: Deno.env.get("DBPassword"), + }); + } catch (e) { + console.error("Could not connect to database"); + throw e; + } } - } } diff --git a/src/db/tables.sql b/src/db/tables.sql new file mode 100644 index 0000000..4523522 --- /dev/null +++ b/src/db/tables.sql @@ -0,0 +1,5 @@ +DROP TABLE IF EXISTS test; + +CREATE TABLE IF NOT EXISTS test ( + id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY +) ENGINE=InnoDB DEFAULT CHARSET=utf8; diff --git a/src/db/tables.ts b/src/db/tables.ts deleted file mode 100644 index d6d1738..0000000 --- a/src/db/tables.ts +++ /dev/null @@ -1 +0,0 @@ -export default []; -- cgit v1.2.3