diff options
author | TheArcaneBrony <myrainbowdash949@gmail.com> | 2022-08-05 23:41:45 +0200 |
---|---|---|
committer | TheArcaneBrony <myrainbowdash949@gmail.com> | 2022-08-09 23:28:27 +0200 |
commit | 01da7dc4c22b4c69000df2a99aa42feabf29c816 (patch) | |
tree | b75c127e0a6d9ad161df41ce2ce10aab6557448f | |
parent | Fix ESM error caused by file-type (diff) | |
download | server-01da7dc4c22b4c69000df2a99aa42feabf29c816.tar.xz |
migrate to DataSource
-rw-r--r-- | util/src/util/Database.ts | 60 | ||||
-rw-r--r-- | util/src/util/Database.ts.torm2 | 72 |
2 files changed, 102 insertions, 30 deletions
diff --git a/util/src/util/Database.ts b/util/src/util/Database.ts index f0540bdf..31a30561 100644 --- a/util/src/util/Database.ts +++ b/util/src/util/Database.ts @@ -1,6 +1,6 @@ import path from "path"; import "reflect-metadata"; -import { Connection, createConnection } from "typeorm"; +import { DataSource, createConnection } from "typeorm"; import * as Models from "../entities"; import { Migration } from "../entities/Migration"; import { yellow, green, red } from "picocolors"; @@ -9,21 +9,24 @@ import { yellow, green, red } from "picocolors"; // We want to generate all id's with Snowflakes that's why we have our own BaseEntity class let promise: Promise<any>; -let dbConnection: Connection | undefined; +let dataSource: DataSource | undefined; let dbConnectionString = process.env.DATABASE || path.join(process.cwd(), "database.db"); +let verbose_db = false; -export function initDatabase(): Promise<Connection> { - if (promise) return promise; // prevent initalizing multiple times +export async function initDatabase(): Promise<DataSource> { + if (dataSource) return dataSource; // prevent initalizing multiple times - const type = dbConnectionString.includes("://") ? dbConnectionString.split(":")[0]?.replace("+srv", "") : "sqlite"; + const type = dbConnectionString.includes("://") ? dbConnectionString.split(":")[0]?.replace("+srv", "") : "sqlite" as any; const isSqlite = type.includes("sqlite"); + if(process.env.DB_VERBOSE) verbose_db = true; console.log(`[Database] ${yellow(`connecting to ${type} db`)}`); - if(isSqlite) { + if(isSqlite) console.log(`[Database] ${red(`You are running sqlite! Please keep in mind that we recommend setting up a dedicated database!`)}`); - } + if(verbose_db) + console.log(`[Database] ${red(`Verbose database logging is enabled, this might impact performance! Unset VERBOSE_DB to disable.`)}`); // @ts-ignore - promise = createConnection({ + dataSource = new DataSource({ type, charset: 'utf8mb4', url: isSqlite ? undefined : dbConnectionString, @@ -31,7 +34,7 @@ export function initDatabase(): Promise<Connection> { // @ts-ignore entities: Object.values(Models).filter((x) => x.constructor.name !== "Object" && x.name), synchronize: type !== "mongodb", - logging: false, + logging: verbose_db, cache: { duration: 1000 * 3, // cache all find queries for 3 seconds }, @@ -40,33 +43,30 @@ export function initDatabase(): Promise<Connection> { name: "default", migrations: [path.join(__dirname, "..", "migrations", "*.js")], }); + promise = dataSource.initialize(); + await promise; + // run migrations, and if it is a new fresh database, set it to the last migration + if (dataSource.migrations.length) { + if (!(await Migration.findOne({}))) { + let i = 0; - promise.then(async (connection: Connection) => { - dbConnection = connection; - - // run migrations, and if it is a new fresh database, set it to the last migration - if (connection.migrations.length) { - if (!(await Migration.findOne({}))) { - let i = 0; - - await Migration.insert( - connection.migrations.map((x) => ({ - id: i++, - name: x.name, - timestamp: Date.now(), - })) - ); - } + await Migration.insert( + dataSource.migrations.map((x) => ({ + id: i++, + name: x.name, + timestamp: Date.now(), + })) + ); } - await connection.runMigrations(); - console.log(`[Database] ${green("connected")}`); - }); + } + await dataSource.runMigrations(); + console.log(`[Database] ${green("connected")}`); return promise; } -export { dbConnection }; +export { dataSource }; export function closeDatabase() { - dbConnection?.close(); + dataSource?.destroy(); } diff --git a/util/src/util/Database.ts.torm2 b/util/src/util/Database.ts.torm2 new file mode 100644 index 00000000..f0540bdf --- /dev/null +++ b/util/src/util/Database.ts.torm2 @@ -0,0 +1,72 @@ +import path from "path"; +import "reflect-metadata"; +import { Connection, createConnection } from "typeorm"; +import * as Models from "../entities"; +import { Migration } from "../entities/Migration"; +import { yellow, green, red } from "picocolors"; + +// UUID extension option is only supported with postgres +// We want to generate all id's with Snowflakes that's why we have our own BaseEntity class + +let promise: Promise<any>; +let dbConnection: Connection | undefined; +let dbConnectionString = process.env.DATABASE || path.join(process.cwd(), "database.db"); + +export function initDatabase(): Promise<Connection> { + if (promise) return promise; // prevent initalizing multiple times + + const type = dbConnectionString.includes("://") ? dbConnectionString.split(":")[0]?.replace("+srv", "") : "sqlite"; + const isSqlite = type.includes("sqlite"); + + console.log(`[Database] ${yellow(`connecting to ${type} db`)}`); + if(isSqlite) { + console.log(`[Database] ${red(`You are running sqlite! Please keep in mind that we recommend setting up a dedicated database!`)}`); + } + // @ts-ignore + promise = createConnection({ + type, + charset: 'utf8mb4', + url: isSqlite ? undefined : dbConnectionString, + database: isSqlite ? dbConnectionString : undefined, + // @ts-ignore + entities: Object.values(Models).filter((x) => x.constructor.name !== "Object" && x.name), + synchronize: type !== "mongodb", + logging: false, + cache: { + duration: 1000 * 3, // cache all find queries for 3 seconds + }, + bigNumberStrings: false, + supportBigNumbers: true, + name: "default", + migrations: [path.join(__dirname, "..", "migrations", "*.js")], + }); + + promise.then(async (connection: Connection) => { + dbConnection = connection; + + // run migrations, and if it is a new fresh database, set it to the last migration + if (connection.migrations.length) { + if (!(await Migration.findOne({}))) { + let i = 0; + + await Migration.insert( + connection.migrations.map((x) => ({ + id: i++, + name: x.name, + timestamp: Date.now(), + })) + ); + } + } + await connection.runMigrations(); + console.log(`[Database] ${green("connected")}`); + }); + + return promise; +} + +export { dbConnection }; + +export function closeDatabase() { + dbConnection?.close(); +} |