import _ from "lodash"; import type { CreateDBSchemaParams } from "../../types"; import { readLiveSchema } from "../../functions/live-schema"; import { sqlQuoteIdent as q } from "../../utils/sql-safe"; import removeDBManagerTable from "./remove-db-manager-table"; import recordSchemaChange from "./record-schema-change"; import checkIfTableExists from "./check-if-table-exists"; type Params = CreateDBSchemaParams & { existing_tables: string[]; schema_tables: string[]; }; /** * Drop tables that are no longer in the schema */ export default function dropRemovedTables(params: Params) { const { db, existing_tables, schema_tables } = params; const tablesToDrop = existing_tables.filter( (t) => !schema_tables.includes(t) && !schema_tables.find((scT) => t.startsWith(scT + "_")), ); const currentSchema = readLiveSchema(); for (const table of currentSchema?.tables || []) { if (!table?.tableName) continue; if (!schema_tables.includes(table.tableName)) { tablesToDrop.push(table.tableName); } } for (const tableName of _.uniq(tablesToDrop)) { if (!checkIfTableExists({ db, table_name: tableName })) { removeDBManagerTable({ db, table_name: tableName }); continue; } recordSchemaChange(params, { description: `Drop table "${tableName}"`, destructive: true, }); db.run(`DROP TABLE IF EXISTS ${q(tableName)}`); removeDBManagerTable({ db, table_name: tableName }); } }