import { db, schema } from './db/connection' import { sql, count } from 'drizzle-orm' export async function optimizeDatabase(): Promise { try { // PostgreSQL automatically creates indexes defined in schema.ts // Run ANALYZE to update statistics for query optimization const tables = [ 'sources', 'reports', 'api_keys', 'source_categories', 'categories', 'users' ] for (const tableName of tables) { await db.execute(sql`ANALYZE ${sql.raw(tableName)}`) } // PostgreSQL equivalent of VACUUM - VACUUM ANALYZE updates statistics and cleans up await db.execute(sql`VACUUM ANALYZE`) console.log('Database optimization completed successfully') } catch (error) { console.error('Database optimization failed:', error) throw error } } export async function getDatabaseStats(): Promise { try { // Get row counts for each table const [sourcesCount] = await db.select({ count: count() }).from(schema.sources) const [reportsCount] = await db.select({ count: count() }).from(schema.reports) const [apiKeysCount] = await db.select({ count: count() }).from(schema.apiKeys) const [categoriesCount] = await db.select({ count: count() }).from(schema.categories) const [usersCount] = await db.select({ count: count() }).from(schema.users) const [sourceCategoriesCount] = await db.select({ count: count() }).from(schema.sourceCategories) const tables = [ { table_name: 'sources', row_count: sourcesCount.count }, { table_name: 'reports', row_count: reportsCount.count }, { table_name: 'api_keys', row_count: apiKeysCount.count }, { table_name: 'categories', row_count: categoriesCount.count }, { table_name: 'users', row_count: usersCount.count }, { table_name: 'source_categories', row_count: sourceCategoriesCount.count } ] return { tables, optimized_at: new Date().toISOString() } } catch (error) { console.error('Failed to get database stats:', error) throw error } }