Files
shd.build/scripts/db-backup.mjs
jb dd84dff055
Validate and deploy production / validate (push) Successful in 23s
Validate and deploy staging / validate (push) Successful in 50s
Validate and deploy production / deploy (push) Failing after 40s
Validate and deploy staging / deploy (push) Failing after 7s
feat: add community publishing and news syndication
2026-08-01 21:42:09 -04:00

59 lines
1.6 KiB
JavaScript

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}`);