import { createClient } from '@supabase/supabase-js'; import * as dotenv from 'dotenv'; import * as path from 'path'; import * as fs from 'fs'; // Load environment variables const envLocalPath = path.resolve(process.cwd(), '../.env.local'); if (fs.existsSync(envLocalPath)) { console.log(`Loading environment from: ${envLocalPath}`); dotenv.config({ path: envLocalPath }); } else { console.log(`No .env.local file found at: ${envLocalPath}`); dotenv.config(); } async function cleanupOrphanedJunctions() { const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL; const supabaseKey = process.env.SUPABASE_SERVICE_ROLE_KEY; if (!supabaseUrl || !supabaseKey) { console.error('Missing Supabase environment variables'); process.exit(1); } const supabase = createClient(supabaseUrl, supabaseKey); console.log('Identifying orphaned junction entries...'); // Get all valid tool IDs const { data: tools } = await supabase .from('tools') .select('id'); if (!tools || tools.length === 0) { console.log('No tools found in database'); return; } const validToolIds = new Set(tools.map(t => t.id)); console.log(`Found ${validToolIds.size} valid tool IDs in database`); // Get all junction entries const { data: junctions } = await supabase .from('tools_categories') .select('*'); if (!junctions) { console.log('No junction entries found'); return; } // Identify orphaned entries const orphanedJunctions = junctions.filter(j => !validToolIds.has(j.tool_id)); console.log(`Found ${orphanedJunctions.length} orphaned junction entries out of ${junctions.length} total`); if (orphanedJunctions.length === 0) { console.log('No orphaned entries to clean up'); return; } // Group by category to understand which categories are affected const orphansByCategory: Record = {}; for (const j of orphanedJunctions) { orphansByCategory[j.category_id] = (orphansByCategory[j.category_id] || 0) + 1; } console.log('\nOrphaned entries by category:'); for (const [categoryId, count] of Object.entries(orphansByCategory)) { const { data: category } = await supabase .from('categories') .select('name') .eq('id', categoryId) .single(); const categoryName = category ? category.name : 'Unknown'; console.log(`- Category ${categoryId} (${categoryName}): ${count} orphaned entries`); } console.log('\n===== RECOMMENDED ACTIONS ====='); console.log('1. Clean up orphaned entries (this requires writing to the database)'); console.log('2. Associate existing tools with category 61 (LLMs)'); // Find potential LLM tools to associate with category 61 console.log('\nPotential tools to associate with category 61 (LLMs):'); const { data: llmTools } = await supabase .from('tools') .select('id, name, published') .or('name.ilike.%llm%,name.ilike.%language model%,name.ilike.%gpt%,name.ilike.%claude%,name.ilike.%gemini%,name.ilike.%llama%') .eq('published', true); if (llmTools && llmTools.length > 0) { for (const tool of llmTools) { console.log(`- ${tool.name} (ID: ${tool.id})`); // Check which categories this tool is already in const { data: toolCategories } = await supabase .from('tools_categories') .select('category_id') .eq('tool_id', tool.id); if (toolCategories && toolCategories.length > 0) { const categoryIds = toolCategories.map(tc => tc.category_id); console.log(` Currently in categories: ${categoryIds.join(', ')}`); // Get category names for (const catId of categoryIds) { const { data: category } = await supabase .from('categories') .select('name') .eq('id', catId) .single(); if (category) { console.log(` - Category ${catId}: ${category.name}`); } } } else { console.log(' Not associated with any categories'); } } } else { console.log('No potential LLM tools found'); } console.log('\nTo clean up orphaned entries, run this script with --execute flag'); console.log('Example: npx ts-node cleanup-orphaned-junctions.ts --execute'); // Check if --execute flag is provided if (process.argv.includes('--execute')) { console.log('\n===== EXECUTING CLEANUP ====='); console.log('Deleting orphaned junction entries...'); // Get IDs of orphaned junctions const orphanedIds = orphanedJunctions.map(j => j.id); // Delete in batches of 10 to avoid potential issues for (let i = 0; i < orphanedIds.length; i += 10) { const batch = orphanedIds.slice(i, i + 10); console.log(`Deleting batch ${i/10 + 1} (${batch.length} entries)...`); const { error } = await supabase .from('tools_categories') .delete() .in('id', batch); if (error) { console.error(`Error deleting batch: ${error.message}`); } else { console.log(`Successfully deleted batch ${i/10 + 1}`); } } console.log('Cleanup completed'); } console.log('\nTo associate tools with category 61 (LLMs), run:'); console.log('npx ts-node associate-tools-with-llms.ts'); } cleanupOrphanedJunctions().catch(console.error);