import { sqlQuoteIdent as q } from "../../utils/sql-safe"; import recordSchemaChange from "./record-schema-change"; /** * Sync indexes for a table */ export default function syncIndexes(params) { const { 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).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) { recordSchemaChange(params, { description: `Drop 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)) { recordSchemaChange(params, { description: `Create index "${index.indexName}" on "${table.tableName}"`, }); const fields = index.indexTableFields .map((f) => q(String(f))) .join(", "); db.run(`CREATE INDEX ${q(index.indexName)} ON ${q(table.tableName)} (${fields})`); } } }