-
Notifications
You must be signed in to change notification settings - Fork 232
Expand file tree
/
Copy pathclean-db.ts
More file actions
271 lines (217 loc) · 7.04 KB
/
clean-db.ts
File metadata and controls
271 lines (217 loc) · 7.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
import { createInterface } from 'readline'
import dotenv from 'dotenv'
import { Knex } from 'knex'
import { getMasterDbClient } from './database/client'
dotenv.config()
type CleanDbOptions = {
all: boolean
dryRun: boolean
force: boolean
help: boolean
kinds: number[]
olderThanDays?: number
}
const HELP_TEXT = [
'Usage: npm run clean-db -- [options]',
'',
'Options:',
' --all Delete all events.',
' --older-than=<days> Delete events older than the given number of days.',
' --kinds=<1,7,4> Delete events for specific kinds.',
' --dry-run Show how many rows would be deleted without deleting them.',
' --force Skip interactive confirmation prompt.',
' --help Show this help message.',
'',
'Examples:',
' npm run clean-db -- --all --dry-run',
' npm run clean-db -- --all --force',
' npm run clean-db -- --older-than=30 --force',
' npm run clean-db -- --older-than=30 --kinds=1,7,4 --dry-run',
].join('\n')
const getOptionValue = (arg: string, args: string[], index: number): [string, number] => {
const [option, inlineValue] = arg.split('=')
if (inlineValue !== undefined) {
if (!inlineValue.trim()) {
throw new Error(`Missing value for ${option}`)
}
return [inlineValue, index]
}
const nextIndex = index + 1
const nextArg = args[nextIndex]
if (!nextArg || nextArg.startsWith('--')) {
throw new Error(`Missing value for ${option}`)
}
return [nextArg, nextIndex]
}
const parseOlderThanDays = (value: string): number => {
if (!/^\d+$/.test(value)) {
throw new Error('--older-than must be a positive integer')
}
const days = Number(value)
if (!Number.isSafeInteger(days) || days <= 0) {
throw new Error('--older-than must be a positive integer')
}
return days
}
const parseKinds = (value: string): number[] => {
const parts = value
.split(',')
.map((kind) => kind.trim())
.filter(Boolean)
if (!parts.length) {
throw new Error('--kinds requires at least one kind')
}
const kinds = parts.map((kind) => {
if (!/^\d+$/.test(kind)) {
throw new Error('--kinds must be a comma-separated list of non-negative integers')
}
const parsed = Number(kind)
if (!Number.isSafeInteger(parsed)) {
throw new Error('--kinds must contain valid integers')
}
return parsed
})
return Array.from(new Set(kinds))
}
export const parseCleanDbOptions = (args: string[]): CleanDbOptions => {
const options: CleanDbOptions = {
all: false,
dryRun: false,
force: false,
help: false,
kinds: [],
}
for (let index = 0; index < args.length; index++) {
const arg = args[index]
if (arg === '--all') {
options.all = true
continue
}
if (arg === '--dry-run') {
options.dryRun = true
continue
}
if (arg === '--force') {
options.force = true
continue
}
if (arg === '--help' || arg === '-h') {
options.help = true
continue
}
if (arg.startsWith('--older-than')) {
const [value, nextIndex] = getOptionValue(arg, args, index)
options.olderThanDays = parseOlderThanDays(value)
index = nextIndex
continue
}
if (arg.startsWith('--kinds')) {
const [value, nextIndex] = getOptionValue(arg, args, index)
options.kinds = parseKinds(value)
index = nextIndex
continue
}
throw new Error(`Unknown option: ${arg}`)
}
if (options.help) {
return options
}
if (!options.all && options.olderThanDays === undefined && !options.kinds.length) {
throw new Error('Select a target with --all, --older-than, or --kinds')
}
if (options.all && (options.olderThanDays !== undefined || options.kinds.length)) {
throw new Error('--all cannot be combined with --older-than or --kinds')
}
return options
}
const applySelectiveFilters = (query: Knex.QueryBuilder, options: CleanDbOptions): Knex.QueryBuilder => {
if (options.olderThanDays !== undefined) {
const olderThanSeconds = options.olderThanDays * 24 * 60 * 60
const cutoff = Math.floor(Date.now() / 1000) - olderThanSeconds
query.where('event_created_at', '<', cutoff)
}
if (options.kinds.length) {
query.whereIn('event_kind', options.kinds)
}
return query
}
const getMatchingEventsCount = async (dbClient: Knex, options: CleanDbOptions): Promise<number> => {
const query = dbClient('events')
if (!options.all) {
applySelectiveFilters(query, options)
}
const result = await query.count<{ count: string | number }>('* as count').first()
return Number(result?.count ?? 0)
}
const askForConfirmation = async (): Promise<boolean> => {
const readline = createInterface({
input: process.stdin,
output: process.stdout,
})
const answer = await new Promise<string>((resolve) => {
readline.question("Type 'DELETE' to confirm: ", (input) => resolve(input))
})
readline.close()
return answer.trim() === 'DELETE'
}
const runAllDelete = async (dbClient: Knex): Promise<void> => {
const hasEventTagsTable = await dbClient.schema.hasTable('event_tags')
if (hasEventTagsTable) {
await dbClient.raw('TRUNCATE TABLE events, event_tags RESTART IDENTITY CASCADE;')
return
}
await dbClient.raw('TRUNCATE TABLE events RESTART IDENTITY CASCADE;')
}
const runSelectiveDelete = async (dbClient: Knex, options: CleanDbOptions): Promise<number> => {
const deleteQuery = applySelectiveFilters(dbClient('events'), options)
const deletedRows = await deleteQuery.del()
await dbClient.raw('VACUUM ANALYZE events;')
return Number(deletedRows)
}
export const runCleanDb = async (args: string[] = process.argv.slice(2)): Promise<number> => {
const options = parseCleanDbOptions(args)
if (options.help) {
console.log(HELP_TEXT)
return 0
}
if (process.env.NODE_ENV === 'production') {
console.warn('WARNING: NODE_ENV=production detected. This operation permanently deletes data.')
}
const dbClient = getMasterDbClient()
try {
if (options.dryRun) {
const matchingEvents = await getMatchingEventsCount(dbClient, options)
console.log(`Dry run: ${matchingEvents} events would be deleted.`)
return 0
}
if (!options.force) {
if (!process.stdin.isTTY) {
throw new Error('Interactive confirmation is unavailable. Re-run with --force.')
}
const confirmed = await askForConfirmation()
if (!confirmed) {
console.log('Aborted. Confirmation text did not match DELETE.')
return 1
}
}
if (options.all) {
await runAllDelete(dbClient)
console.log('Deleted all events with TRUNCATE.')
return 0
}
const deletedRows = await runSelectiveDelete(dbClient, options)
console.log(`Deleted ${deletedRows} events. VACUUM ANALYZE completed.`)
return 0
} finally {
await dbClient.destroy()
}
}
if (require.main === module) {
runCleanDb().then((exitCode) => {
process.exitCode = exitCode
}).catch((error) => {
const message = error instanceof Error ? error.message : String(error)
console.error(message)
process.exitCode = 1
})
}