Files
bun-sqlite/src/lib/schema/drop-removed-tables.ts
T
tbenandClaude Opus 5.5 4e47bd8ce0 Port bun-mariadb schema guard, targetId fix, lazy init and tests
- schema: add --dry-run (sync in a rolled-back transaction) and require
  confirmation (or --yes) before dropping tables or columns; unapproved
  destructive changes are refused
- only rebuild tables whose CREATE TABLE statement changed
- always AND targetId with the query, regardless of searchOperator
- empty IN / NOT IN lists become 1 = 0 / 1 = 1
- initialize lazily on first call so importing never throws
- read CLI version from package.json, chmod CLI on compile, pin @types/bun
- add SQL generator, value and schema guard tests

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-14 03:00:29 +01:00

50 lines
1.5 KiB
TypeScript

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 });
}
}