Skip to content

Commit

Permalink
feat: db prune script (closes #322)
Browse files Browse the repository at this point in the history
  • Loading branch information
eartharoid committed Feb 13, 2025
1 parent d60a58c commit f140b76
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 1 deletion.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"main": "src/",
"scripts": {
"db.dump": "node scripts/dump.mjs",
"db.prune": "node scripts/prune.mjs",
"db.restore": "node scripts/restore.mjs",
"changelog": "conventional-changelog -p angular -i CHANGELOG.md -s",
"contributors:add": "all-contributors add",
Expand Down
2 changes: 1 addition & 1 deletion scripts/dump.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ if (process.env.DB_PROVIDER === 'sqlite') {

spinner.succeed('Connected');

export const models = [
const models = [
'user',
'guild',
'tag',
Expand Down
49 changes: 49 additions & 0 deletions scripts/prune.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { config } from 'dotenv';
import { program } from 'commander';
import { join } from 'path';
import ora from 'ora';
import { PrismaClient } from '@prisma/client';

config();

program
.requiredOption('-y, --yes', 'ARE YOU SURE?')
.option('-d, --days <number>', 'number of days', 365);

program.parse();

const options = program.opts();

let spinner = ora('Connecting').start();

const prisma_options = {};

if (process.env.DB_PROVIDER === 'sqlite' && !process.env.DB_CONNECTION_URL) {
prisma_options.datasources = { db: { url: 'file:' + join(process.cwd(), './user/database.db') } };
}

const prisma = new PrismaClient(prisma_options);

if (process.env.DB_PROVIDER === 'sqlite') {
const { default: sqliteMiddleware } = await import('../src/lib/middleware/prisma-sqlite.js');
prisma.$use(sqliteMiddleware);
await prisma.$queryRaw`PRAGMA journal_mode=WAL;`;
await prisma.$queryRaw`PRAGMA synchronous=normal;`;
}

spinner.succeed('Connected');

const now = Date.now();
const elapsed = 1000 * 60 * 60 * 24 * options.days;
const cutoff = now - elapsed;

spinner = ora('Counting total guilds').start();
const total = await prisma.guild.count();
spinner.succeed(`Found ${total} total guilds`);

// ! the bot might still be in these guilds
spinner = ora(`Deleting guilds inactive for more than ${options.days} days`).start();
const result = await prisma.guild.deleteMany({ where: { tickets: { none: { createdAt: { gt: new Date(cutoff) } } } } });
spinner.succeed(`Deleted ${result.count} guilds; ${total - result.count} remaining`);

process.exit(0);

0 comments on commit f140b76

Please sign in to comment.