Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Postgres support #3748

Open
wants to merge 15 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions db/knex_init_db.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,11 @@ const { log } = require("../src/util");
* ⚠️⚠️⚠️⚠️⚠️⚠️ DO NOT ADD ANYTHING HERE!
* IF YOU NEED TO ADD FIELDS, ADD IT TO ./db/knex_migrations
* See ./db/knex_migrations/README.md for more information
* @param {"mariadb"|"postgres"} dbType database type, should be either "mariadb" or "postgres"
* @returns {Promise<void>}
*/
async function createTables() {
log.info("mariadb", "Creating basic tables for MariaDB");
async function createTables(dbType) {
log.info(dbType, "Creating basic tables");
const knex = R.knex;

// TODO: Should check later if it is really the final patch sql file.
Expand Down
90 changes: 90 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,7 @@
"@popperjs/core": "~2.10.2",
"@types/bootstrap": "~5.1.9",
"@types/node": "^20.8.6",
"@types/pg": "^8.10.2",
"@typescript-eslint/eslint-plugin": "^6.7.5",
"@typescript-eslint/parser": "^6.7.5",
"@vitejs/plugin-vue": "~5.0.1",
Expand Down
60 changes: 55 additions & 5 deletions server/database.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ const knex = require("knex");
const path = require("path");
const { EmbeddedMariaDB } = require("./embedded-mariadb");
const mysql = require("mysql2/promise");
const pg = require("pg");

/**
* Database & App Data Folder
Expand Down Expand Up @@ -186,6 +187,18 @@ class Database {
fs.writeFileSync(path.join(Database.dataDir, "db-config.json"), JSON.stringify(dbConfig, null, 4));
}

/**
* Validate a database name
* @param {string} dbName Database name to validate
* @throws {Error} If the database name is invalid
* @returns {void}
*/
static validateDBName(dbName) {
if (!/^\w+$/.test(dbName)) {
throw Error("Invalid database name. A database name can only consist of letters, numbers and underscores");
}
}

/**
* Connect to the database
* @param {boolean} testMode Should the connection be started in test mode?
Expand Down Expand Up @@ -217,7 +230,6 @@ class Database {
log.info("db", `Database Type: ${dbConfig.type}`);

if (dbConfig.type === "sqlite") {

if (! fs.existsSync(Database.sqlitePath)) {
log.info("server", "Copying Database");
fs.copyFileSync(Database.templatePath, Database.sqlitePath);
Expand All @@ -242,9 +254,7 @@ class Database {
}
};
} else if (dbConfig.type === "mariadb") {
if (!/^\w+$/.test(dbConfig.dbName)) {
throw Error("Invalid database name. A database name can only consist of letters, numbers and underscores");
}
this.validateDBName(dbConfig.dbName);

const connection = await mysql.createConnection({
host: dbConfig.hostname,
Expand Down Expand Up @@ -296,6 +306,24 @@ class Database {
},
pool: mariadbPoolConfig,
};
} else if (dbConfig.type === "postgres") {
this.validateDBName(dbConfig.dbName);

const clientConfig = {
host: dbConfig.hostname,
port: dbConfig.port,
user: dbConfig.username,
password: dbConfig.password,
database: dbConfig.dbName,
};
const client = new pg.Client(clientConfig);
await client.execute("CREATE DATABASE IF NOT EXISTS " + dbConfig.dbName);
await client.end();

config = {
client: "pg",
connection: clientConfig,
};
} else {
throw new Error("Unknown Database type: " + dbConfig.type);
}
Expand Down Expand Up @@ -328,6 +356,8 @@ class Database {
await this.initSQLite(testMode, noLog);
} else if (dbConfig.type.endsWith("mariadb")) {
await this.initMariaDB();
} else if (dbConfig.type === "postgres") {
await this.initPostgres();
}
}

Expand Down Expand Up @@ -377,6 +407,22 @@ class Database {
}
}

/**
* Initialize PostgresDB
* @returns {Promise<void>}
*/
static async initPostgres() {
log.debug("db", "Checking if PostgresDB database exists...");

let hasTable = await R.hasTable("docker_host");
if (!hasTable) {
const { createTables } = require("../db/knex_init_db");
await createTables();
} else {
log.debug("db", "PostgresDB database already exists");
}
}

/**
* Patch the database
* @returns {Promise<void>}
Expand Down Expand Up @@ -702,13 +748,17 @@ class Database {

/**
* @returns {string} Get the SQL for the current time plus a number of hours
* @throws {Error} If the database type is unknown
*/
static sqlHourOffset() {
if (Database.dbConfig.type === "sqlite") {
return "DATETIME('now', ? || ' hours')";
} else {
} else if (Database.dbConfig.type.endsWith("mariadb")) {
return "DATE_ADD(NOW(), INTERVAL ? HOUR)";
} else if (Database.dbConfig.type === "postgres") {
return "NOW() + INTERVAL '? HOUR'";
}
throw new Error("Unknown database type: " + Database.dbConfig.type);
}

}
Expand Down
Loading