[All-kit]: Build one `identifier` function per push command from the renames and standardize the data loss warnings
Input
PR author’s description
The data loss checks of drizzle-kit push run before any statement, so they query a table by the name that the database still has. Each call site did that lookup by hand with tableBefore or schemaBefore before it…
PR diff
Current GitHub diff ↗+type TableName = { schema?: string; name: string };++export const nameWithRename = (before: string, after: string) => {+ return before === after ? before : `${before} (would become ${after})`;
Browse 20 changed files
drizzle-kit/src/cli/commands/warnings.ts+62 −0
@@ -0,0 +1,62 @@+type TableName = { schema?: string; name: string };++export const nameWithRename = (before: string, after: string) => {+ return before === after ? before : `${before} (would become ${after})`;+};++// Statements name a table as it is after the diff. A data loss check runs before any statement,+// so it must query the table by the name that the database still has.+// `'dropped'` applies only the schema rename, because a table can be renamed or moved to the name+// of a dropped view.+export const tableNamesBeforeRenames = (+ renames: {+ schemas?: readonly { from: { name: string }; to: { name: string } }[];+ tables: readonly { schema?: string; from: string; to: string }[];+ moves?: readonly { name: string; from: string; to: string }[];+ },+ quoteTable: (table: TableName) => string,+) => {+ const identifier = (table: TableName, diffResult: 'kept' | 'dropped'): string => {+ let { schema, name } = table;+ if (diffResult === 'kept') {+ schema = renames.moves?.find((it) => it.name === name && it.to === schema)?.from ?? schema;+ name = renames.tables.find((it) => it.to === name && it.schema === schema)?.from ?? name;+ }+ schema = renames.schemas?.find((it) => it.to.name === schema)?.from.name ?? schema;++ return quoteTable({ schema, name });+ };++ const label = (table: TableName) => nameWithRename(identifier(table, 'kept'), quoteTable(table));++ return { identifier, label };+};++export const dropTableWarning = (table: string) => `You're about to delete non-empty ${table} table`;++export const dropViewWarning = (view: string) => `You're about to delete non-empty ${view} materialized view`;++export const dropColumnWarning = (column: string, table: string) => {+ return `You're about to delete non-empty ${column} column in ${table} table`;+};++export const dropSchemaWarning = (schema: string, tableCount: number) => {+ return `You're about to delete ${schema} schema with ${tableCount} ${tableCount === 1 ? 'table' : 'tables'}`;+};++export const dropPrimaryKeyWarning = (table: string) => {+ return `You're about to drop the primary key of ${table} table. The statements may fail, and the table may lose its primary key`;+};++export const addNotNullColumnWarning = (column: string, table: string) => {+ return `You're about to add not-null ${column} column without default value to non-empty ${table} table`;+};++export const changeColumnTypeWarning = (column: string, table: string, from: string, to: string) => {+ return `You're about to change ${column} column type in ${table} table from ${from} to ${to}`;+};++export const dropReferencedPrimaryKeyWarning = (table: string, columns: string[]) => {+ const columnNames = columns.join(', ');+ return `You are trying to drop primary key from ${table} (${columnNames}), but there is an existing reference on this column. You must either add a UNIQUE constraint to (${columnNames}) or drop the foreign key constraint that references this column.`;+};
drizzle-kit/tests/postgres/pg-tables.test.ts+111 −7
@@ -7,6 +7,7 @@ import { geometry, index, integer,+ pgMaterializedView, PgSchema, pgSchema, pgTable,@@ -23,6 +24,10 @@ import { vector, } from 'drizzle-orm/pg-core'; import { stripAnsi } from 'hanji/utils';+import { suggestions } from 'src/cli/commands/push-postgres';+import { runWithCliContext } from 'src/cli/context';+import { HintsHandler } from 'src/cli/hints';+import { prepareStatement } from 'src/dialects/postgres/statements'; import { afterAll, beforeAll, beforeEach, expect, test } from 'vitest'; import { diff, prepareTestDatabase, push, TestDatabase } from './mocks'; @@ -1706,7 +1711,7 @@ test('drop column in a renamed table with data', async () => { 'ALTER TABLE "accounts" DROP COLUMN "name";', ]); expect(phints).toStrictEqual([- { hint: `You're about to delete non-empty name column in "accounts" table` },+ { hint: `You're about to delete non-empty "name" column in "users" (would become "accounts") table` }, ]); }); @@ -1735,7 +1740,7 @@ test('drop column in a table with data that moves to another schema', async () = 'ALTER TABLE "app"."users" DROP COLUMN "name";', ]); expect(phints).toStrictEqual([- { hint: `You're about to delete non-empty name column in "app"."users" table` },+ { hint: `You're about to delete non-empty "name" column in "users" (would become "app"."users") table` }, ]); }); @@ -1761,7 +1766,7 @@ test('drop column in a table with data in a renamed schema', async () => { 'ALTER TABLE "after"."users" DROP COLUMN "name";', ]); expect(phints).toStrictEqual([- { hint: `You're about to delete non-empty name column in "after"."users" table` },+ { hint: `You're about to delete non-empty "name" column in "before"."users" (would become "after"."users") table` }, ]); }); @@ -1791,7 +1796,7 @@ test('drop column in a table with data that is renamed and moves to another sche 'ALTER TABLE "app"."accounts" DROP COLUMN "name";', ]); expect(phints).toStrictEqual([- { hint: `You're about to delete non-empty name column in "app"."accounts" table` },+ { hint: `You're about to delete non-empty "name" column in "users" (would become "app"."accounts") table` }, ]); }); @@ -1822,7 +1827,10 @@ test('drop column in a renamed table with data in a renamed schema', async () => 'ALTER TABLE "after"."accounts" DROP COLUMN "name";', ]); expect(phints).toStrictEqual([- { hint: `You're about to delete non-empty name column in "after"."accounts" table` },+ {+ hint:+ `You're about to delete non-empty "name" column in "before"."users" (would become "after"."accounts") table`,+ }, ]); }); @@ -1849,7 +1857,7 @@ test('drop primary key in a renamed table with data', async () => { ]); expect(phints.map((it) => ({ ...it, hint: stripAnsi(it.hint) }))).toStrictEqual([{ hint:- `You're about to drop "public"."accounts" primary key, this statements may fail and your table may lose primary key`,+ `You're about to drop the primary key of "users" (would become "accounts") table. The statements may fail, and the table may lose its primary key`, }]); }); @@ -1877,6 +1885,102 @@ test('drop materialized view with data in a renamed schema', async () => { 'DROP MATERIALIZED VIEW "after"."view";', ]); expect(phints).toStrictEqual([- { hint: `You're about to delete non-empty "after"."view" materialized view` },+ { hint: `You're about to delete non-empty "before"."view" materialized view` },+ ]);+});++test('drop primary key with an implicit name in a renamed table with data', async () => {+ await db.query(`CREATE TABLE "orders" ("id" integer CONSTRAINT "orders_custom_pk" PRIMARY KEY);`);+ await db.query(`INSERT INTO "orders" ("id") VALUES (1);`);++ const hints = await runWithCliContext({ output: 'text', interactive: true }, () =>+ suggestions(db, [+ prepareStatement('rename_table', { schema: 'public', from: 'orders', to: 'purchases' }),+ prepareStatement('drop_pk', {+ pk: {+ entityType: 'pks',+ schema: 'public',+ table: 'purchases',+ name: 'purchases_pkey',+ nameExplicit: false,+ columns: ['id'],+ },+ }),+ ], new HintsHandler()));++ for (const it of hints) {+ if (it.statement) await db.query(it.statement);+ }++ const primaryKeys = await db.query(+ `select conname from pg_constraint where conrelid = '"orders"'::regclass and contype = 'p';`,+ );+ expect(hints).toHaveLength(1);+ expect(primaryKeys).toStrictEqual([]);+});++test('drop column without values in a table with data', async () => {+ const schema1 = {+ users: pgTable('users', { id: integer('id').primaryKey(), name: text('name') }),+ };+ const schema2 = {+ users: pgTable('users', { id: integer('id').primaryKey() }),+ };++ await push({ db, to: schema1 });+ await db.query(`INSERT INTO "users" ("id") VALUES (1);`);++ const { hints: phints } = await push({ db, to: schema2 });++ expect(phints).toStrictEqual([]);+});++test('drop table with data in a renamed schema', async () => {+ const before = pgSchema('before');+ const after = pgSchema('after');+ const schema1 = {+ before,+ users: before.table('users', { id: integer('id').primaryKey() }),+ };+ const schema2 = { after };++ await push({ db, to: schema1 });+ await db.query(`INSERT INTO "before"."users" ("id") VALUES (1);`);++ const { hints: phints } = await push({ db, to: schema2, renames: ['before->after'] });++ expect(phints).toStrictEqual([+ { hint: `You're about to delete non-empty "before"."users" table` },+ ]);+});++test('drop materialized view with data when a renamed table takes its name', async () => {+ const users = pgTable('users', { id: integer('id').primaryKey() });+ const schema1 = {+ users,+ accounts: pgTable('accounts', { id: integer('id').primaryKey() }),+ report: pgMaterializedView('report', { id: integer('id') }).as(sql`SELECT "id" FROM "users"`),+ };+ const schema2 = {+ users,+ report: pgTable('report', { id: integer('id').primaryKey() }),+ };++ await push({ db, to: schema1 });+ await db.query(`INSERT INTO "users" ("id") VALUES (1);`);+ await db.query(`REFRESH MATERIALIZED VIEW "report";`);++ const { sqlStatements: pst, hints: phints } = await push({+ db,+ to: schema2,+ renames: ['public.accounts->public.report'],+ });++ expect(pst).toStrictEqual([+ 'DROP MATERIALIZED VIEW "report";',+ 'ALTER TABLE "accounts" RENAME TO "report";',+ ]);+ expect(phints).toStrictEqual([+ { hint: `You're about to delete non-empty "report" materialized view` }, ]); });
drizzle-kit/src/cli/commands/push-mysql.ts+33 −40
@@ -6,7 +6,6 @@ import { interimToDDL } from '../../dialects/mysql/ddl'; import { ddlDiff } from '../../dialects/mysql/diff'; import type { JsonStatement } from '../../dialects/mysql/statements'; import { prepareEntityFilter } from '../../dialects/pull-utils';-import { tableBeforeRenames } from '../../dialects/utils'; import type { DB } from '../../utils'; import { connectToMySQL } from '../connections'; import { isInteractive, outputFormat } from '../context';@@ -26,6 +25,15 @@ import { ProgressView, } from '../views'; import { introspect } from './pull-mysql';+import {+ changeColumnTypeWarning,+ dropColumnWarning,+ dropPrimaryKeyWarning,+ dropReferencedPrimaryKeyWarning,+ dropTableWarning,+ nameWithRename,+ tableNamesBeforeRenames,+} from './warnings'; export const handle = async ( filenames: string[],@@ -131,14 +139,16 @@ export const handle = async ( return { status: 'ok' as const, dialect: 'mysql' }; }; -const identifier = ({ table, column }: { table?: string; column?: string }) => {- return [table, column].filter(Boolean).map((t) => `\`${t}\``).join('.');-};+const quote = (name: string) => `\`${name}\``;+ export const suggestions = async (db: DB, jsonStatements: JsonStatement[], ddl2: MysqlDDL, hints: HintsHandler) => { const json = outputFormat() === 'json'; const useHints = json || !isInteractive(); const grouped: { hint: string; statement?: string }[] = [];- const tableBefore = tableBeforeRenames({ tables: jsonStatements.filter((it) => it.type === 'rename_table') });+ const { identifier, label } = tableNamesBeforeRenames(+ { tables: jsonStatements.filter((it) => it.type === 'rename_table') },+ (it) => quote(it.name),+ ); const filtered = jsonStatements.filter((it) => { if (it.type === 'alter_column' && it.diff.generated) return false;@@ -148,59 +158,54 @@ export const suggestions = async (db: DB, jsonStatements: JsonStatement[], ddl2: for (const statement of filtered) { if (statement.type === 'drop_table') {+ const id = identifier({ name: statement.table }, 'dropped'); const entity = ['public', statement.table] as const; if (hints.matchConfirm('table', entity)) continue;- const res = await db.query(`select 1 from ${identifier({ table: statement.table })} limit 1`);+ const res = await db.query(`select 1 from ${id} limit 1`); if (res.length > 0) { if (useHints) { hints.pushMissingHint({ type: 'confirm_data_loss', kind: 'table', entity, reason: 'non_empty' }); } else {- grouped.push({ hint: `You're about to delete non-empty ${chalk.underline(statement.table)} table` });+ grouped.push({ hint: dropTableWarning(id) }); } } continue; } if (statement.type === 'drop_column') { const column = statement.column;+ const table = { name: column.table }; const entity = ['public', column.table, column.name] as const; if (hints.matchConfirm('column', entity)) continue;- const tableInDb = tableBefore({ name: column.table }).name;- const res = await db.query(`select 1 from ${identifier({ table: tableInDb })} limit 1`);+ const res = await db.query(+ `select 1 from ${identifier(table, 'kept')} where ${quote(column.name)} is not null limit 1`,+ ); if (res.length === 0) continue; if (useHints) { hints.pushMissingHint({ type: 'confirm_data_loss', kind: 'column', entity, reason: 'non_empty' }); } else {- grouped.push({- hint: `You're about to delete non-empty ${chalk.underline(column.name)} column in ${- chalk.underline(column.table)- } table`,- });+ grouped.push({ hint: dropColumnWarning(quote(column.name), label(table)) }); } continue; } // drop pk if (statement.type === 'drop_pk') { const { table, columns } = statement.pk;- const id = identifier({ table: tableBefore({ name: table }).name });+ const id = identifier({ name: table }, 'kept'); const entity = ['public', table, statement.pk.name] as const; if (hints.matchConfirm('primary_key', entity)) continue; const res = await db.query( `select 1 from ${id} limit 1`, ); if (res.length > 0) {- const hint = `You're about to drop ${- chalk.underline(table)- } primary key, this statements may fail and your table may lose primary key`;- if (useHints) { hints.pushMissingHint({ type: 'confirm_data_loss', kind: 'primary_key', entity, reason: 'non_empty' }); } else {- grouped.push({ hint });+ grouped.push({ hint: dropPrimaryKeyWarning(label({ name: table })) }); } } @@ -233,20 +238,11 @@ export const suggestions = async (db: DB, jsonStatements: JsonStatement[], ddl2: blocking_fks: fkFound.map((fk) => fk.name), }); }- grouped.push({- hint: `You are trying to drop primary key from "${table}" ("${- columns.join('", ')- }"), but there is an existing reference on this column. You must either add a UNIQUE constraint to ("${- columns.join('", ')- }") or drop the foreign key constraint that references this column.`,- });+ grouped.push({ hint: dropReferencedPrimaryKeyWarning(label({ name: table }), columns.map(quote)) }); continue; } if (statement.type === 'alter_column') {- const tableName = identifier({ table: statement.origin.table });- const columnName = identifier({ column: statement.origin.column });- if (statement.diff.type) { const entity = ['public', statement.column.table, statement.column.name] as const; if (!hints.matchConfirm('column', entity)) {@@ -259,17 +255,14 @@ export const suggestions = async (db: DB, jsonStatements: JsonStatement[], ddl2: reason_details: { from: statement.diff.type.from, to: statement.diff.type.to }, }); } else {- const hint = `You're about to change ${- chalk.underline(- columnName,- )- } column type in ${tableName} from ${- chalk.underline(+ grouped.push({+ hint: changeColumnTypeWarning(+ nameWithRename(quote(statement.origin.column), quote(statement.column.name)),+ label({ name: statement.column.table }), statement.diff.type.from,- )- } to ${chalk.underline(statement.diff.type.to)}`;-- grouped.push({ hint });+ statement.diff.type.to,+ ),+ }); } } }
Outcome
Why this verdict
concerns — Updated data loss warnings in drizzle-kit push → unified warning texts and SQL quoting across dialects → users now see quoted identifiers and only confirm dropped columns with non-null values
-
🟡
drizzle-kit/src/cli/commands/push-cockroach.ts:quote— 1 finding ↳ 20 callers (drizzle-kit/src/cli/commands/generate-mysql.ts:53, drizzle-kit/src/cli/commands/generate-mysql.ts:54, drizzle-kit/src/cli/commands/generate-mysql.ts:87) — downstream impact 🔴 narrator-identified-concern -
Ordinary source not in the index yet (a re-sync/overlay rebuild may cover them): changelogs/drizzle-kit/1.0.0-rc.5.md, drizzle-kit/skills/drizzle-hints/SKILL.md, drizzle-kit/skills/drizzle/SKILL.md, drizzle-kit/tests/other/payload-push.test.ts, drizzle-kit/tests/sqlite/sqlite-columns.test.ts
Evidence and perspectives
Observation · Narrated concernUpdated data loss warnings in `drizzle-kit push` → unified warning texts and SQL quoting across dialects → users now see quoted identifiers and only confirm dropped columns with non-null values
Recorded location drizzle-kit/src/cli/commands/push-cockroach.ts:19