import type { Database } from "bun:sqlite"; import type { BUN_SQLITE_TableSchemaType } from "../../types"; import { sqlQuoteIdent as q } from "../../utils/sql-safe"; type Params = { db: Database; table: BUN_SQLITE_TableSchemaType; }; /** * Sync indexes for a table */ export default function syncIndexes({ db, table }: Params) { if (!table.indexes || table.indexes.length === 0) { return; } const existingIndexes = ( db .query( `SELECT name FROM sqlite_master WHERE type='index' AND tbl_name=? AND name NOT LIKE 'sqlite_%'`, ) .all(table.tableName) as { name: string }[] ).map((r) => r.name); // Drop indexes not in schema for (const indexName of existingIndexes) { const stillExists = table.indexes.some( (idx) => idx.indexName === indexName, ); if (!stillExists) { console.log(`Dropping index: ${indexName}`); db.run(`DROP INDEX IF EXISTS ${q(indexName)}`); } } // Create new indexes for (const index of table.indexes) { if (!index.indexName || !index.indexTableFields?.length) { continue; } if (!existingIndexes.includes(index.indexName)) { console.log(`Creating index: ${index.indexName}`); const fields = index.indexTableFields .map((f) => q(String(f))) .join(", "); db.run( `CREATE INDEX ${q(index.indexName)} ON ${q(table.tableName)} (${fields})`, ); } } }