Skip to content

Commit 2951e93

Browse files
committed
Drop stale (older than an hour) test databases automatically on test close
1 parent c5a4897 commit 2951e93

File tree

2 files changed

+29
-2
lines changed

2 files changed

+29
-2
lines changed

src/core/database/database.module.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,9 @@ export class DatabaseModule implements OnApplicationShutdown {
4040

4141
async onApplicationShutdown() {
4242
if (this.config.neo4j.ephemeral) {
43+
if (this.config.jest) {
44+
await this.dbService.dropStaleTestDbs();
45+
}
4346
await this.dbService.dropDb();
4447
}
4548
await this.db.close();

src/core/database/database.service.ts

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,14 @@ import { entries, mapKeys } from '@seedcompany/common';
33
import { Connection, node, type Query, relation } from 'cypher-query-builder';
44
import { LazyGetter } from 'lazy-get-decorator';
55
import { pickBy, startCase } from 'lodash';
6-
import { Duration } from 'luxon';
7-
import { defer, firstValueFrom, shareReplay, takeUntil } from 'rxjs';
6+
import { DateTime, Duration } from 'luxon';
7+
import {
8+
defer,
9+
EmptyError,
10+
firstValueFrom,
11+
shareReplay,
12+
takeUntil,
13+
} from 'rxjs';
814
import {
915
DuplicateException,
1016
type ID,
@@ -209,6 +215,24 @@ export class DatabaseService {
209215
await this.runAdminCommand('DROP', dbName);
210216
}
211217

218+
async dropStaleTestDbs() {
219+
const info = await this.getServerInfo().catch((e) => {
220+
if (e instanceof EmptyError) return null;
221+
throw e;
222+
});
223+
const staleTestDbs = (info?.databases ?? []).filter(({ name }) => {
224+
const match = /test\.([\d-]+\.[\d-]+)\..+/.exec(name);
225+
if (!match) {
226+
return false;
227+
}
228+
const dt = DateTime.fromFormat(match[1], 'y-MM-dd.HH-mm-ss');
229+
return dt.diffNow().as('hours') < -1;
230+
});
231+
for (const staleTestDb of staleTestDbs) {
232+
await this.runAdminCommand('DROP', staleTestDb.name);
233+
}
234+
}
235+
212236
private async runAdminCommand(action: 'CREATE' | 'DROP', dbName: string) {
213237
// @ts-expect-error Yes this is private, but we have a special use case.
214238
// We need to run this query with a session that's not configured to use the

0 commit comments

Comments
 (0)