fix: 完善权威数据约束与测试隔离

This commit is contained in:
root
2026-09-14 11:34:07 +08:00
parent a2a5e4bd0f
commit c547e78a22
9 changed files with 600 additions and 160 deletions
+37
View File
@@ -0,0 +1,37 @@
export const DEFAULT_TEST_DATABASE_URL =
"postgresql://drift:drift_test_only@127.0.0.1:55432/drift_bottle_test?schema=public";
const SAFETY_ERROR =
"Refusing database operation: DATABASE_URL must target localhost or 127.0.0.1 and a database ending in _test.";
export function assertSafeTestDatabaseUrl(databaseUrl: string): void {
try {
const parsed = new URL(databaseUrl);
const isLocal =
parsed.hostname === "localhost" || parsed.hostname === "127.0.0.1";
const databaseName = decodeURIComponent(parsed.pathname.slice(1));
if (
parsed.protocol !== "postgresql:" ||
!isLocal ||
!databaseName.endsWith("_test")
) {
throw new Error(SAFETY_ERROR);
}
} catch {
throw new Error(SAFETY_ERROR);
}
}
export function resolveTestDatabaseUrl(environment = process.env): string {
const databaseUrl = environment.DATABASE_URL ?? DEFAULT_TEST_DATABASE_URL;
assertSafeTestDatabaseUrl(databaseUrl);
return databaseUrl;
}
export function assertSeedDatabaseAllowed(
databaseUrl: string,
environment = process.env,
): void {
if (environment.ALLOW_SEED_NON_TEST_DATABASE === "true") return;
assertSafeTestDatabaseUrl(databaseUrl);
}