41 lines
1.2 KiB
JavaScript
41 lines
1.2 KiB
JavaScript
require('dotenv').config({ quiet: true });
|
|
const mysql = require('mysql2/promise');
|
|
(async () => {
|
|
let db;
|
|
try {
|
|
const u = new URL(process.env.DATABASE_URL);
|
|
const name = u.pathname.slice(1);
|
|
if (!/^[a-zA-Z0-9_]+$/.test(name)) throw Error();
|
|
db = await mysql.createConnection({
|
|
host: u.hostname,
|
|
port: Number(u.port || 3306),
|
|
user: decodeURIComponent(u.username),
|
|
password: decodeURIComponent(u.password),
|
|
});
|
|
const [existing] = await db.execute(
|
|
'SELECT SCHEMA_NAME FROM information_schema.SCHEMATA WHERE SCHEMA_NAME=?',
|
|
[name],
|
|
);
|
|
if (existing.length) {
|
|
const [tables] = await db.execute(
|
|
'SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA=?',
|
|
[name],
|
|
);
|
|
console.log(
|
|
'Database already exists; tables:',
|
|
tables.map((t) => t.TABLE_NAME),
|
|
);
|
|
} else {
|
|
await db.query(
|
|
'CREATE DATABASE `' + name + '` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci',
|
|
);
|
|
console.log('Created new empty project database.');
|
|
}
|
|
} catch (e) {
|
|
console.error('Database preflight failed:', e.code || 'configuration error');
|
|
process.exitCode = 1;
|
|
} finally {
|
|
if (db) await db.end();
|
|
}
|
|
})();
|