Skip to content

Commit 89ce4fb

Browse files
fix(driver-sql): removing a field default stores NULL on MySQL 8, and never leaves a NOT NULL column refusing writes (#36600)
<!-- claude-projects-attribution: {"github_login":"os-warren"} --> _Requested by **Warren** · [project thread](https://claude.ai/code/project/chan_01U5RdnAAmkSQmZbqh6FtqZ8?thread=cmsg_01U5RdnAAmkSQmZbqh6FtqZ8Jy8bxCRdEndf2kW8g6WXtd)_ Fixes #36596 Clause-②: no Metadata-protocol: none ## 维护者速读 - 修复 main 变红:字段删掉默认值后,MySQL 8 上不填该字段的新记录会被数据库拒绝,现在改为存空值,和 Postgres、SQLite 一致。 - 对「不允许为空」的列,删默认值不再单独执行:字段允许为空时和「放开非空」一起执行;字段仍要求非空时原样保留,只报出。 - 已有记录一行不改;改动可直接回退。 ## The cause (premise correction) The card says the dropped DEFAULT "leaves the column NOT NULL". Measured on MySQL 8.0.46, it does not: `digest` is `IS_NULLABLE = YES` throughout. The cause is MySQL 8's `ALTER COLUMN … DROP DEFAULT`, which leaves even a **nullable** column with no default at all, so a strict-mode insert that omits it fails with ER 1364 "Field 'digest' doesn't have a default value". `SET DEFAULT NULL` stores NULL. Round 1 (#36564) was measured on MariaDB 10.11, which stores NULL after `DROP DEFAULT`, and the live MySQL leg did not run on that PR. ``` mysql> CREATE TABLE p (id varchar(36) PRIMARY KEY, digest varchar(255) DEFAULT 'none'); mysql> ALTER TABLE p ALTER COLUMN digest DROP DEFAULT; mysql> INSERT INTO p (id) VALUES ('a'); ERROR 1364 (HY000): Field 'digest' doesn't have a default value mysql> ALTER TABLE p ALTER COLUMN digest SET DEFAULT NULL; mysql> INSERT INTO p (id) VALUES ('a'); -- stores NULL ``` ## What changes `packages/drivers/driver-sql/**` only, plus this changeset. - **MySQL `drop_column_default`** (`sql-driver-schema-sync.ts`): on a nullable column it is now `ALTER COLUMN … SET DEFAULT NULL`; a NOT NULL column keeps `DROP DEFAULT`. This also covers the #4560 token arm, which used the same statement. - **A NOT NULL column with a stale literal DEFAULT** (`schema-drift.ts`): the drop never travels alone, because an omitting insert would then be refused. - When the declaration does not hold the column NOT NULL (the differ already proposes `relax_not_null`: `storage: { notNull: false }` in words, or no storage declaration on a non-`required` field), the drop is reported **with** that relax at the relax's category, `needs_confirm`. `os migrate apply` applies both; the publish and the managed package install (#33724) apply both when the field says `storage: { notNull: false }`. An unset insert then stores NULL. Dev auto-reconcile applies neither (ADR-0113 D5), so the column keeps storing the old default and is never left refusing writes. - Otherwise (`storage: { notNull: true }`, a `required` field, the ceremony-owned tenant column), the column is left alone. The entry is `destructive`, so no automatic or non-destructive path applies it, and it is warned at boot and listed by `os migrate plan`. - `isPublishedColumnChange` / `isInstallRelaxation` select the paired drop alongside the declared relax (`isDeclaredRelaxPair`). ## Tests `sql-driver-36245-stale-literal-default.test.ts`: §1 and §2 unchanged (not skipped, quarantined or narrowed); §2 now passes on live MySQL 8. New §3, per dialect cell (SQLite, live PG, live MySQL), on a NOT NULL column with `DEFAULT 'none'`: 1. No default, no storage declaration, not required: drift is `drop_column_default` + `relax_not_null`, both `needs_confirm`; dev boot leaves the column (unset insert stores `'none'`); `applyMigrationEntries` applies both; unset insert stores NULL; no drift after. 2. `storage: { notNull: false }`: `applyPublishedColumnChanges` applies both; unset insert stores NULL. 3. `storage: { notNull: true }`: one `destructive` entry; boot, publish and non-destructive apply leave the column NOT NULL with its default. 4. `required: true`, no storage: same as 3. ## Live PG + MySQL evidence (in-container, CI's own setup) Servers: MySQL 8.0.46 (`STRICT_TRANS_TABLES`, `innodb_strict_mode=1`, `SET GLOBAL time_zone='+08:00'`) and PostgreSQL 16 (`ALTER SYSTEM SET timezone='Asia/Shanghai'`). Run exactly as the "Temporal Conformance (live PG + MySQL)" step runs it: `TZ=America/New_York OS_EXPECT_LIVE_DIALECT_MATRIX=1 OS_TEST_POSTGRES_URL=… OS_TEST_MYSQL_URL=… pnpm --filter @objectstack/driver-sql test`. **Before (origin/main 79d9c14), the red reproduced on live MySQL 8:** ``` FAIL sql-driver-36245-stale-literal-default.test.ts > … #36245 §2 … (live mysql) > the second boot drops the removed default … Error: insert into `os36245_pref` (`id`, `title`) values ('after', 'after') - Field 'digest' doesn't have a default value FAIL sql-driver-36245-stale-literal-default.test.ts > … #36245 §2 … (live mysql) > without auto-reconcile the divergence is reported `safe` … Error: insert into `os36245_pref` (`id`, `title`) values ('repaired', 'repaired') - Field 'digest' doesn't have a default value ``` **After (head f972c24), the file, verbose:** 51 passed (51). Every §2 and §3 case passes on `sqlite`, `live postgres` and `live mysql` (18 two-boot cases, 6 per dialect); `driver-sql live-dialect coverage: all 3 dialects were exercised (sqlite, live postgres, live mysql)`. **After, the whole driver-sql suite under the CI step's setup:** ``` Test Files 1 failed | 280 passed | 1 skipped (282) Tests 1 failed | 7007 passed | 10 skipped (7018) FAIL sql-driver-11565-row-byte-budget.test.ts > … row byte budget on live MySQL (#11565) > reports InnoDB page-limit refusals with the page limit, not the row budget ``` The one failure is not this PR's: it fails identically at origin/main 79d9c14 against the same local server (same command, main's `src/`), and passes on main's CI `mysql:8.0` image. The difference is this container's Ubuntu MySQL build, not the code: the case expects the server to refuse a new 40-column table, and this server accepts it. This PR touches no create path. **Ablations** (`scripts/ablation-replace.mjs`, each restored to HEAD, run on all three cells): | Mutation | Result | |---|---| | MySQL drop back to `DROP DEFAULT` on a nullable column | 4 fail: both §2 MySQL cases (ER 1364, the main-red failure), and the two MySQL §3 cases that relax then drop | | NOT NULL column drop emitted `safe` and unpaired, as on main | 9 fail across all three dialects | | Publish/install no longer select the paired drop | 3 fail: the `storage: { notNull: false }` publish case on each dialect | | Pair the drop even when the declaration holds NOT NULL | 6 fail: the `notNull: true` and `required` cases on each dialect | ## Follow-ups (not in this PR) - `content/docs/deployment/cli.mdx` (the publish paragraph under the drift-category table) says the publish applies "every `safe` column change, and a `relax_not_null` whose field declares `storage: { notNull: false }`". It now also applies the paired `drop_column_default`. That page is outside this card's file surface, so it is not edited here. - On MySQL, `relax_not_null` runs `MODIFY … NULL`, which also drops a column's declared literal DEFAULT (measured: `NOT NULL DEFAULT 'x'` becomes `DEFAULT NULL`); the #36245 `set_column_default` arm restates it on the next sync. Pre-existing and unchanged here. - The "Temporal Conformance (live PG + MySQL)" job is path-filtered and skipped on PRs, which is how round 1 reached main. Making it run on a `driver-sql` PR is a `.github/workflows/ci.yml` change: governed (Tier H) and outside this card's file surface, so it is not made here. Evidence from in-container live servers is pasted instead. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01JQwxbY6wSVQZ9QBM4hLeYw <!-- signed: repo:objectstack#1 · os-warren · session_01JQwxbY6wSVQZ9QBM4hLeYw --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent aff34ba commit 89ce4fb

4 files changed

Lines changed: 215 additions & 8 deletions

File tree

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
---
2+
'@objectstack/driver-sql': patch
3+
---
4+
5+
fix(driver-sql): removing a field's default stores NULL on MySQL 8, and never leaves a NOT NULL column refusing writes
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
#36245 made schema sync drop a column DEFAULT the field no longer declares. On MySQL 8 the drop left the column with no default at all, so an insert that omitted the field was refused ("Field … doesn't have a default value") where Postgres and SQLite store NULL. On a nullable column MySQL now sets the default to NULL instead, so an unset insert stores NULL on all three databases.
11+
12+
On a NOT NULL column the drop no longer travels alone, because the database would then refuse every insert that omits the field. When the field does not hold the column NOT NULL (no `storage.notNull` and not `required`, or `storage: { notNull: false }` in words), the drop is reported together with relaxing the column, both `needs_confirm`: `os migrate apply` applies them, and so do the publish of the object and the managed install of its package when the field declares `storage: { notNull: false }`. Afterwards an unset insert stores NULL. Dev auto-reconcile applies neither, as before for a relax. When the field still holds the column NOT NULL (`storage: { notNull: true }` or `required`), the column is left alone and the stale default is reported as `destructive`, which no automatic path applies. No metadata key, value or default changes.

‎packages/drivers/driver-sql/src/schema-drift.ts‎

Lines changed: 44 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1344,7 +1344,12 @@ export function diffManagedTable(args: {
13441344
// explicit physical constraint — NOT against `required`, which is the
13451345
// write-time contract and implies nothing about the column) ──────────
13461346
const expectNullable = field.storage?.notNull !== true;
1347+
// [#36596] Whether a `relax_not_null` is proposed for this column: the
1348+
// literal-DEFAULT arm below drops a NOT NULL column's stale default only
1349+
// alongside it, never alone.
1350+
let relaxProposed = false;
13471351
if (expectNullable && !col.nullable && field.storage?.notNull === false && fieldName !== ceremonyOwnedNullability) {
1352+
relaxProposed = true;
13481353
// [#32590] The author DECLARED the column nullable — `storage: { notNull:
13491354
// false }`, written out, not merely absent. The column constraint is the
13501355
// declaration's to own (ADR-0113 D2), and this is the "deliberately
@@ -1385,6 +1390,7 @@ export function diffManagedTable(args: {
13851390
`package applies it ("os package install"); or relax it deliberately via "os migrate apply".`,
13861391
});
13871392
} else if (expectNullable && !col.nullable && field.required !== true && fieldName !== ceremonyOwnedNullability) {
1393+
relaxProposed = true;
13881394
// Column STRICTER than its declaration — and the field is not even
13891395
// write-gated, so an omitting write reaches the DB and dies as a raw
13901396
// driver error instead of a clean validation 400. That surprise is
@@ -1491,7 +1497,7 @@ export function diffManagedTable(args: {
14911497
const physical = physicalDefaultLiteral(col.defaultValue);
14921498
const multiValue = isMultiValueField({ type: String(field.type ?? ''), multiple: field.multiple === true });
14931499
if (physical.kind === 'literal' && !multiValue) {
1494-
if (dv === undefined || dv === null) {
1500+
if ((dv === undefined || dv === null) && col.nullable) {
14951501
out.push({
14961502
kind: 'default_mismatch',
14971503
remoteName: table,
@@ -1508,6 +1514,43 @@ export function diffManagedTable(args: {
15081514
`database stores nothing. Dropping the default is non-destructive and rewrites no stored row. ` +
15091515
SAFE_COLUMN_REMEDY,
15101516
});
1517+
} else if (dv === undefined || dv === null) {
1518+
// [#36596] A NOT NULL column. Dropping its only DEFAULT alone would
1519+
// turn every insert that omits the field from "stores the old value"
1520+
// into "refused by the database" — so the drop never travels alone.
1521+
// Where the declaration does not hold the column NOT NULL (the relax
1522+
// above is proposed: `storage.notNull: false` in words, or no storage
1523+
// declaration on a field that is not `required`), the drop travels
1524+
// WITH that relax at the relax's own category, `needs_confirm`, and
1525+
// is applied by the same deliberate acts (publish / package install
1526+
// for the declared-`false` case, #33724; `os migrate apply`), after
1527+
// which an omitting insert stores NULL. Anywhere else (`storage:
1528+
// { notNull: true }`, a `required` field, the ceremony-owned tenant
1529+
// column) the column is left alone: the entry is `destructive`, so no
1530+
// automatic path applies it, and it is reported (warned at boot, listed
1531+
// by "os migrate plan") rather than silently ignored.
1532+
const pairs = relaxProposed;
1533+
out.push({
1534+
kind: 'default_mismatch',
1535+
remoteName: table,
1536+
table,
1537+
column: fieldName,
1538+
expected: '(no column default)',
1539+
actual: `DEFAULT ${quoteDefaultForMessage(physical.text)}`,
1540+
severity: 'warning',
1541+
category: pairs ? 'needs_confirm' : 'destructive',
1542+
op: { type: 'drop_column_default', table, column: fieldName },
1543+
message: pairs
1544+
? `${table}.${fieldName}: the NOT NULL column carries DEFAULT ${quoteDefaultForMessage(physical.text)}, but the ` +
1545+
`field declares no default and does not hold the column NOT NULL. Dropping the default goes with ` +
1546+
`relaxing the column (reported alongside), so an insert that omits the field stores NULL, as on a new ` +
1547+
`database; neither statement rewrites a stored row. Apply both together: publish the object, install ` +
1548+
`the package that declares it, or run "os migrate apply".`
1549+
: `${table}.${fieldName}: the NOT NULL column carries DEFAULT ${quoteDefaultForMessage(physical.text)}, but the ` +
1550+
`field declares no default. Left as it is: the column stays NOT NULL, so dropping its default would ` +
1551+
`make the database refuse every insert that omits the field. Declare the default again, or relax the ` +
1552+
`column (\`storage: { notNull: false }\`) and the default is dropped with it.`,
1553+
});
15111554
} else if ((typeof dv === 'string' || typeof dv === 'number' || typeof dv === 'boolean') && !isRuntimeDefaultValue(dv)) {
15121555
if (physicalLiteralMatches(physical.text, dv, field.type) === false) {
15131556
out.push({

‎packages/drivers/driver-sql/src/sql-driver-36245-stale-literal-default.test.ts‎

Lines changed: 134 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,18 @@
2828
* neither reported nor changed; a changed literal stores the new value; a row
2929
* stored before is not rewritten; and with no auto-reconcile the two entries
3030
* are reported `safe` and applied by the explicit apply door.
31+
*
32+
* [#36596] §3, one cell per dialect: the same removal on a NOT NULL column.
33+
* #36245 first shipped a MySQL `DROP DEFAULT`, which on MySQL 8 leaves even a
34+
* NULLABLE column with no default at all, so §2's unset insert was refused
35+
* ("Field 'digest' doesn't have a default value", ER 1364) — MariaDB 10.11,
36+
* where it was measured, stores NULL. §2 now holds on MySQL 8 as it stands. On
37+
* a NOT NULL column the drop never travels alone, since an omitting insert
38+
* would then be refused: where the declaration does not hold the column NOT
39+
* NULL it is paired with the `relax_not_null` (`needs_confirm`, both applied by
40+
* the explicit apply door, and by the publish when the field says `storage:
41+
* { notNull: false }` in words), after which an unset insert stores NULL;
42+
* where it does, the column is left alone and the entry reported `destructive`.
3143
*/
3244

3345
import { afterEach, describe, expect, it, vi } from 'vitest';
@@ -198,6 +210,128 @@ function measure(cell: DialectCell): void {
198210
expect(await second.detectManagedDrift([SECOND])).toEqual([]);
199211
});
200212
});
213+
214+
describe(`#36596 §3 — a stale literal DEFAULT on a NOT NULL column (${cell.label})`, () => {
215+
const NN = 'os36596_pref';
216+
const open: SqlDriver[] = [];
217+
let dir: string | undefined;
218+
219+
const config = (): Record<string, any> => {
220+
if (cell.id !== 'sqlite') return cell.config();
221+
dir ??= mkdtempSync(join(tmpdir(), 'os36596-'));
222+
return { ...cell.config(), connection: { filename: join(dir, 'db.sqlite') } };
223+
};
224+
225+
const boot = async (obj: any, opts: Record<string, any> = {}): Promise<SqlDriver> => {
226+
const driver = new SqlDriver({ ...config(), ...opts } as any);
227+
(driver as any).logger = quietLogger();
228+
open.push(driver);
229+
await driver.initObjects([obj]);
230+
return driver;
231+
};
232+
233+
const insertUnset = async (driver: SqlDriver, id: string) => {
234+
await driver.create(NN, { id, title: id }, { bypassTenantAudit: true } as any);
235+
return (driver as any).knex(NN).where('id', id).first();
236+
};
237+
238+
/** The first release: `code` is NOT NULL, with a literal default. */
239+
const FIRST_NN = {
240+
name: NN,
241+
fields: {
242+
title: { type: 'string' },
243+
code: { type: 'string', defaultValue: 'none', storage: { notNull: true } },
244+
},
245+
} as any;
246+
const second = (code: Record<string, any>) => ({ name: NN, fields: { title: { type: 'string' }, code: { type: 'string', ...code } } }) as any;
247+
248+
/** Create the first release's table, then boot the second declaration over it. */
249+
const upgrade = async (next: any, opts: Record<string, any> = {}): Promise<SqlDriver> => {
250+
const first = await boot(FIRST_NN);
251+
await (first as any).knex.schema.dropTableIfExists(NN);
252+
await first.initObjects([FIRST_NN]);
253+
await first.disconnect();
254+
open.splice(open.indexOf(first), 1);
255+
return boot(next, opts);
256+
};
257+
258+
const nullable = async (driver: SqlDriver): Promise<boolean> =>
259+
(await (driver as any).knex(NN).columnInfo())?.code?.nullable === true;
260+
261+
afterEach(async () => {
262+
const last = open[open.length - 1];
263+
if (last) await (last as any).knex.schema.dropTableIfExists(NN);
264+
for (const d of open.splice(0)) await d.disconnect();
265+
if (dir) rmSync(dir, { recursive: true, force: true });
266+
dir = undefined;
267+
});
268+
269+
it('no default, no storage declaration, not required: the drop is paired with the relax and an unset insert then stores NULL', async () => {
270+
const next = second({});
271+
const driver = await upgrade(next, { autoMigrate: 'safe', schemaMode: 'managed' });
272+
273+
const drift = await driver.detectManagedDrift([next]);
274+
expect(drift.map((d) => [d.column, d.op.type, d.category]).sort()).toEqual([
275+
['code', 'drop_column_default', 'needs_confirm'],
276+
['code', 'relax_not_null', 'needs_confirm'],
277+
]);
278+
// Dev auto-reconcile applies neither (ADR-0113 D5): the column is left as
279+
// it was, so an unset insert still stores the old default, never refused.
280+
expect(await nullable(driver)).toBe(false);
281+
expect((await insertUnset(driver, 'unrepaired')).code).toBe('none');
282+
283+
const { applied, skipped } = await driver.applyMigrationEntries(drift, { allowDestructive: false });
284+
expect(skipped).toEqual([]);
285+
expect(applied).toHaveLength(2);
286+
expect(await nullable(driver)).toBe(true);
287+
expect((await insertUnset(driver, 'repaired')).code).toBeNull();
288+
expect(await driver.detectManagedDrift([next])).toEqual([]);
289+
// The row stored before keeps what it holds.
290+
expect((await (driver as any).knex(NN).where('id', 'unrepaired').first()).code).toBe('none');
291+
});
292+
293+
it('`storage: { notNull: false }` declared: the publish applies the relax and the drop together', async () => {
294+
const next = second({ storage: { notNull: false } });
295+
const driver = await upgrade(next);
296+
expect((await insertUnset(driver, 'unrepaired')).code).toBe('none');
297+
298+
const { applied, skipped } = await driver.applyPublishedColumnChanges(next);
299+
expect(skipped).toEqual([]);
300+
expect(applied.map((d) => d.op.type).sort()).toEqual(['drop_column_default', 'relax_not_null']);
301+
expect((await insertUnset(driver, 'repaired')).code).toBeNull();
302+
expect(await driver.detectManagedDrift([next])).toEqual([]);
303+
});
304+
305+
it('a declaration that still holds the column NOT NULL: the column is left alone and the entry reported `destructive`', async () => {
306+
const next = second({ storage: { notNull: true } });
307+
const driver = await upgrade(next, { autoMigrate: 'safe', schemaMode: 'managed' });
308+
309+
const drift = await driver.detectManagedDrift([next]);
310+
expect(drift.map((d) => [d.column, d.op.type, d.category])).toEqual([['code', 'drop_column_default', 'destructive']]);
311+
expect(drift[0].message).toMatch(/Left as it is/);
312+
313+
// Neither the boot, the publish nor the non-destructive apply door touches it.
314+
expect((await driver.applyPublishedColumnChanges(next)).applied).toEqual([]);
315+
const { applied } = await driver.applyMigrationEntries(drift, { allowDestructive: false });
316+
expect(applied).toEqual([]);
317+
expect(await nullable(driver)).toBe(false);
318+
expect((await insertUnset(driver, 'kept')).code).toBe('none');
319+
});
320+
321+
it('a `required` field over the NOT NULL column (no storage declaration): left alone and reported `destructive`', async () => {
322+
const next = second({ required: true });
323+
const driver = await upgrade(next);
324+
325+
const drift = await driver.detectManagedDrift([next]);
326+
// The relax stays silent for a legacy `required` field (ADR-0113); the
327+
// stale default is reported, never applied by a non-destructive door.
328+
expect(drift.map((d) => [d.column, d.op.type, d.category])).toEqual([['code', 'drop_column_default', 'destructive']]);
329+
expect((await driver.applyMigrationEntries(drift, { allowDestructive: false })).applied).toEqual([]);
330+
expect(await nullable(driver)).toBe(false);
331+
await driver.create(NN, { id: 'r', title: 'r', code: 'given' }, { bypassTenantAudit: true } as any);
332+
expect((await (driver as any).knex(NN).where('id', 'r').first()).code).toBe('given');
333+
});
334+
});
201335
}
202336

203337
for (const cell of DIALECT_CELLS) {

‎packages/drivers/driver-sql/src/sql-driver-schema-sync.ts‎

Lines changed: 25 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -563,10 +563,19 @@ export async function applyDriftOpInPlace(this: Pick<SchemaSyncHost, 'applyIndex
563563
await this.knex.raw('ALTER TABLE ?? DROP COLUMN ??', [table, column]);
564564
return true;
565565
case 'drop_column_default':
566-
// `ALTER … ALTER COLUMN … DROP DEFAULT` — the one ALTER COLUMN form
567-
// MySQL accepts without restating the type, so it cannot lose a
568-
// varchar length the way MODIFY can.
569-
await this.knex.raw('ALTER TABLE ?? ALTER COLUMN ?? DROP DEFAULT', [table, column]);
566+
// `ALTER … ALTER COLUMN …` — the one form MySQL accepts without
567+
// restating the type, so it cannot lose a varchar length the way
568+
// MODIFY can. [#36596] On a NULLABLE column it is `SET DEFAULT NULL`,
569+
// never `DROP DEFAULT`: MySQL 8's DROP DEFAULT leaves the column with
570+
// no default at all, and a strict-mode insert that omits it is then
571+
// refused ("Field … doesn't have a default value", ER 1364) where
572+
// Postgres and SQLite store NULL. Measured on 8.0.46. A NOT NULL
573+
// column keeps DROP DEFAULT: NULL is not a default it can take.
574+
if (ci?.nullable === true) {
575+
await this.knex.raw('ALTER TABLE ?? ALTER COLUMN ?? SET DEFAULT NULL', [table, column]);
576+
} else {
577+
await this.knex.raw('ALTER TABLE ?? ALTER COLUMN ?? DROP DEFAULT', [table, column]);
578+
}
570579
return true;
571580
case 'set_column_default':
572581
// `ALTER … ALTER COLUMN … SET DEFAULT` — the same MODIFY-free form.
@@ -1545,7 +1554,17 @@ export async function reconcileAndWarnDrift(this: Pick<SchemaSyncHost, 'applyMig
15451554
function isPublishedColumnChange(d: ManagedDriftEntry, fields: Record<string, any> | undefined): boolean {
15461555
if (isIndexDriftOp(d.op)) return false;
15471556
if (d.category === 'safe') return true;
1548-
return d.op.type === 'relax_not_null' && d.category === 'needs_confirm'
1557+
return isDeclaredRelaxPair(d, fields);
1558+
}
1559+
1560+
/**
1561+
* [#32590 / #36596] The `needs_confirm` entries a declared `storage: { notNull:
1562+
* false }` makes deliberate: the relax of the NOT NULL column, and the drop of
1563+
* a stale literal DEFAULT the differ pairs with that relax (never proposed
1564+
* without it). Applying the relax alone would keep storing the old default.
1565+
*/
1566+
function isDeclaredRelaxPair(d: ManagedDriftEntry, fields: Record<string, any> | undefined): boolean {
1567+
return (d.op.type === 'relax_not_null' || d.op.type === 'drop_column_default') && d.category === 'needs_confirm'
15491568
&& fields?.[d.op.column]?.storage?.notNull === false;
15501569
}
15511570

@@ -1579,8 +1598,7 @@ export async function applyPublishedColumnChanges(this: Pick<SchemaSyncHost, 'ap
15791598
* installing package's own declaration says so for.
15801599
*/
15811600
function isInstallRelaxation(d: ManagedDriftEntry, fields: Record<string, any> | undefined, columns: ReadonlySet<string>): boolean {
1582-
return d.op.type === 'relax_not_null' && d.category === 'needs_confirm'
1583-
&& columns.has(d.op.column) && fields?.[d.op.column]?.storage?.notNull === false;
1601+
return isDeclaredRelaxPair(d, fields) && columns.has(d.op.column ?? '');
15841602
}
15851603

15861604
/** The body of `SqlDriver#relaxDeclaredNotNull`; the method's docblock there is its contract. */

0 commit comments

Comments
 (0)