001project_wildgrowth/backend/deploy/fix-notes-constraints.js

63 lines
2.3 KiB
JavaScript
Raw Normal View History

2026-02-11 15:26:03 +08:00
const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();
async function fixConstraints() {
try {
// Create indexes
await prisma.$executeRawUnsafe(`
CREATE INDEX IF NOT EXISTS "notes_user_id_course_id_idx" ON "notes"("user_id", "course_id");
`);
console.log('✓ Created index: notes_user_id_course_id_idx');
await prisma.$executeRawUnsafe(`
CREATE INDEX IF NOT EXISTS "notes_user_id_node_id_idx" ON "notes"("user_id", "node_id");
`);
console.log('✓ Created index: notes_user_id_node_id_idx');
await prisma.$executeRawUnsafe(`
CREATE INDEX IF NOT EXISTS "notes_course_id_node_id_idx" ON "notes"("course_id", "node_id");
`);
console.log('✓ Created index: notes_course_id_node_id_idx');
// Create foreign keys (check if they exist first)
const constraints = await prisma.$queryRaw`
SELECT conname FROM pg_constraint
WHERE conrelid = 'notes'::regclass
AND contype = 'f'
`;
const existingConstraints = constraints.map(c => c.conname);
if (!existingConstraints.includes('notes_user_id_fkey')) {
await prisma.$executeRawUnsafe(`
ALTER TABLE "notes" ADD CONSTRAINT "notes_user_id_fkey"
FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
`);
console.log('✓ Created foreign key: notes_user_id_fkey');
}
if (!existingConstraints.includes('notes_course_id_fkey')) {
await prisma.$executeRawUnsafe(`
ALTER TABLE "notes" ADD CONSTRAINT "notes_course_id_fkey"
FOREIGN KEY ("course_id") REFERENCES "courses"("id") ON DELETE CASCADE ON UPDATE CASCADE;
`);
console.log('✓ Created foreign key: notes_course_id_fkey');
}
if (!existingConstraints.includes('notes_node_id_fkey')) {
await prisma.$executeRawUnsafe(`
ALTER TABLE "notes" ADD CONSTRAINT "notes_node_id_fkey"
FOREIGN KEY ("node_id") REFERENCES "course_nodes"("id") ON DELETE CASCADE ON UPDATE CASCADE;
`);
console.log('✓ Created foreign key: notes_node_id_fkey');
}
console.log('\n✅ All constraints created successfully');
} catch (error) {
console.error('Error:', error.message);
} finally {
await prisma.$disconnect();
}
}
fixConstraints();