Add auth bootstrap and database safeguards
This commit is contained in:
@@ -0,0 +1,50 @@
|
||||
import { connect } from '@tursodatabase/database';
|
||||
import { mkdir, writeFile } from 'node:fs/promises';
|
||||
import { basename, dirname, resolve } from 'node:path';
|
||||
import process from 'node:process';
|
||||
|
||||
const databasePath = resolve(process.env.TDR_DATABASE_PATH || './data/shd-build-development.db');
|
||||
const requestedOutput = process.argv[2];
|
||||
const timestamp = new Date().toISOString().replaceAll(':', '-').replace(/\.\d{3}Z$/, 'Z');
|
||||
const databaseName = basename(databasePath).replace(/\.[^.]+$/, '');
|
||||
const outputPath = resolve(
|
||||
requestedOutput || `./data/backups/${databaseName}-${timestamp}.json`
|
||||
);
|
||||
const quoteIdentifier = (identifier) => `"${String(identifier).replaceAll('"', '""')}"`;
|
||||
|
||||
await mkdir(dirname(outputPath), { recursive: true });
|
||||
const database = await connect(databasePath);
|
||||
const tableRows = await (
|
||||
await database.prepare(`
|
||||
SELECT name
|
||||
FROM sqlite_master
|
||||
WHERE type = 'table'
|
||||
AND name NOT LIKE 'sqlite_%'
|
||||
ORDER BY rowid
|
||||
`)
|
||||
).all();
|
||||
|
||||
const tables = [];
|
||||
let totalRows = 0;
|
||||
for (const tableRow of tableRows) {
|
||||
const name = String(tableRow.name);
|
||||
const rows = await (await database.prepare(`SELECT * FROM ${quoteIdentifier(name)}`)).all();
|
||||
tables.push({ name, rowCount: rows.length, rows });
|
||||
totalRows += rows.length;
|
||||
}
|
||||
|
||||
const backup = {
|
||||
format: 'shd-build-database-backup',
|
||||
version: 1,
|
||||
createdAt: new Date().toISOString(),
|
||||
sourceDatabase: basename(databasePath),
|
||||
totalRows,
|
||||
tables
|
||||
};
|
||||
await writeFile(outputPath, `${JSON.stringify(backup, null, 2)}\n`, {
|
||||
encoding: 'utf8',
|
||||
flag: 'wx'
|
||||
});
|
||||
|
||||
console.log(`Backed up ${totalRows} rows from ${tables.length} tables.`);
|
||||
console.log(`Backup: ${outputPath}`);
|
||||
Reference in New Issue
Block a user