forked from Vatix-Protocol/vatix-backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidate-migrations.ts
More file actions
181 lines (151 loc) · 4.91 KB
/
Copy pathvalidate-migrations.ts
File metadata and controls
181 lines (151 loc) · 4.91 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
#!/usr/bin/env tsx
/**
* Migration validation script for CI/CD
*
* This script validates that:
* 1. Migration files are in sync with schema
* 2. Migration SQL is valid
* 3. No destructive changes without explicit confirmation
*/
import { execSync } from "child_process";
import { readFileSync, readdirSync } from "fs";
import { join } from "path";
import { exit } from "process";
const MIGRATIONS_DIR = "prisma/migrations";
const SCHEMA_FILE = "prisma/schema.prisma";
export interface MigrationValidationResult {
valid: boolean;
errors: string[];
warnings: string[];
}
function validateMigrationFiles(): MigrationValidationResult {
const result: MigrationValidationResult = {
valid: true,
errors: [],
warnings: [],
};
try {
// Check if migrations directory exists
const migrations = readdirSync(MIGRATIONS_DIR, { withFileTypes: true })
.filter((dirent) => dirent.isDirectory())
.map((dirent) => dirent.name)
.sort();
if (migrations.length === 0) {
result.errors.push("No migration files found");
result.valid = false;
return result;
}
console.log(`Found ${migrations.length} migration(s):`);
migrations.forEach((migration) => console.log(` - ${migration}`));
// Validate each migration file
for (const migration of migrations) {
const migrationFile = join(MIGRATIONS_DIR, migration, "migration.sql");
try {
const sql = readFileSync(migrationFile, "utf8");
// Check for potentially dangerous operations
const dangerousPatterns = [
/DROP\s+TABLE/i,
/DROP\s+COLUMN/i,
/DROP\s+INDEX/i,
/DELETE\s+FROM\s+\w+\s*$/i, // DELETE without WHERE
];
for (const pattern of dangerousPatterns) {
if (pattern.test(sql)) {
result.warnings.push(
`Dangerous operation detected in ${migration}: ${pattern.source}`
);
}
}
// Basic SQL syntax check (simple validation)
if (!sql.trim().startsWith("--")) {
const sqlCommands = sql.split(";").filter((cmd) => cmd.trim());
if (sqlCommands.length === 0) {
result.errors.push(`No SQL commands found in ${migration}`);
result.valid = false;
}
}
} catch (error) {
result.errors.push(
`Failed to read migration file ${migration}: ${error}`
);
result.valid = false;
}
}
} catch (error) {
result.errors.push(`Failed to read migrations directory: ${error}`);
result.valid = false;
}
return result;
}
function validateSchemaSync(): MigrationValidationResult {
const result: MigrationValidationResult = {
valid: true,
errors: [],
warnings: [],
};
try {
// Check if schema and migrations are in sync
console.log("Checking schema synchronization...");
const diffCommand = `npx prisma migrate diff --config prisma.diff.config.ts --from-migrations ${MIGRATIONS_DIR} --to-schema ${SCHEMA_FILE}`;
const output = execSync(diffCommand, { encoding: "utf8" });
if (output.trim() && !output.includes("No difference detected")) {
result.errors.push("Schema and migrations are out of sync:");
result.errors.push(output);
result.valid = false;
} else {
console.log("✓ Schema and migrations are in sync");
}
} catch (error) {
result.errors.push(`Failed to check schema synchronization: ${error}`);
result.valid = false;
}
return result;
}
function validatePrismaClient(): MigrationValidationResult {
const result: MigrationValidationResult = {
valid: true,
errors: [],
warnings: [],
};
try {
console.log("Generating Prisma client...");
execSync("npx prisma generate", { stdio: "pipe" });
console.log("✓ Prisma client generated successfully");
} catch (error) {
result.errors.push(`Failed to generate Prisma client: ${error}`);
result.valid = false;
}
return result;
}
function main() {
console.log("🔍 Validating database migrations...\n");
const results = [
validateMigrationFiles(),
validateSchemaSync(),
validatePrismaClient(),
];
const allErrors = results.flatMap((r) => r.errors);
const allWarnings = results.flatMap((r) => r.warnings);
const isValid = results.every((r) => r.valid);
// Print results
if (allWarnings.length > 0) {
console.log("\n⚠️ Warnings:");
allWarnings.forEach((warning) => console.log(` - ${warning}`));
}
if (allErrors.length > 0) {
console.log("\n❌ Errors:");
allErrors.forEach((error) => console.log(` - ${error}`));
}
if (isValid) {
console.log("\n✅ All migration validations passed!");
exit(0);
} else {
console.log("\n❌ Migration validation failed!");
exit(1);
}
}
// Run validation if called directly
if (import.meta.url === `file://${process.argv[1]}`) {
main();
}
export { validateMigrationFiles, validateSchemaSync, validatePrismaClient };