Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions .changeset/37320-mysql-text-column-default.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---
'@objectstack/driver-sql': patch
---

fix(driver-sql): a MySQL TEXT column carries its field's declared literal default

Clause-②: no
Metadata-protocol: none

- On MySQL, a text-family field (`text`, `textarea`, `markdown`, `html`, `richtext`, `code`, an unbounded `string`, …) that declares a literal `defaultValue` now gets that DEFAULT on its column. Before, the DEFAULT was silently left out of the DDL, because MySQL takes a DEFAULT on a TEXT column only in the expression form (`DEFAULT ('d')`, MySQL 8.0.13+ / MariaDB 10.2+). So adding such a field with `storage: { notNull: true }` to a table that already held rows filled every existing row with `''` instead of the declared value, and any insert that left the field out was refused (`Field '…' doesn't have a default value`). Postgres and SQLite are unchanged.
- The schema differ reads MySQL's spelling of that DEFAULT (`_utf8mb4\'d\'`) as an expression, so it no longer proposes restating a default the column already carries.
- A table an earlier release created keeps its TEXT column without a DEFAULT. Nothing reports that difference, as before. Writes through the engine still store the declared default there.
18 changes: 14 additions & 4 deletions packages/cli/src/commands/generate-string-family-width.pin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -472,11 +472,21 @@ describe('#16091 — the character column both generators emit is the driver\'s'
const arm = armContaining('text');
expect(
arm,
'driver-sql no longer builds its text family with `keyable === null ? table.text(name) : ' +
'driver-sql no longer builds its text family with `keyable === null ? textColumn() : ' +
'table.string(name, keyable)`. This pin corrects the generators TOWARD the driver, so if ' +
'the driver moved, re-read #16091 before touching generate.ts — the authority is the ' +
'driver, not this file.',
).toContain('col = keyable === null ? table.text(name) : table.string(name, keyable);');
).toContain('col = keyable === null ? textColumn() : table.string(name, keyable);');
// `textColumn()` is createColumn's own unbounded-TEXT builder: `table.text(name)`,
// or on MySQL with a literal default the same `text` type via `specificType`
// (so the expression-form DEFAULT survives). Either way the column is TEXT.
const prologue = SQL_DRIVER_SOURCE.slice(
SQL_DRIVER_SOURCE.indexOf('protected createColumn('),
SQL_DRIVER_SOURCE.indexOf('switch (type)', SQL_DRIVER_SOURCE.indexOf('protected createColumn(')),
);
expect(prologue, 'createColumn no longer defines its textColumn() builder').toContain('const textColumn = () => {');
expect(prologue).toContain("return table.specificType(name, 'text');");
expect(prologue).toContain('return table.text(name);');

// MEMBERSHIP is the driver's, swept rather than listed — a type that joins
// or leaves this arm changes what is measured here without anyone editing it.
Expand Down Expand Up @@ -599,7 +609,7 @@ describe('#16091 — the character column both generators emit is the driver\'s'
it('a KEYED text-family column takes keyableTextLength\'s width, in both generators', () => {
const arm = armContaining('text');
expect(arm).toContain('const keyable = keyed ? this.keyableTextLength(field) : null;');
expect(arm).toContain('col = keyable === null ? table.text(name) : table.string(name, keyable);');
expect(arm).toContain('col = keyable === null ? textColumn() : table.string(name, keyable);');

for (const type of armMembers('text')) {
// SIZED — the declared bound verbatim, up to the key-part ceiling.
Expand Down Expand Up @@ -741,7 +751,7 @@ describe('#16091 — the character column both generators emit is the driver\'s'
arm,
'driver-sql no longer sizes its string family from `declaredVarcharLength`. Re-read ' +
'#16091 before trusting the generators\' widths — the authority is the driver.',
).toContain('col = declared === null ? table.text(name) : table.string(name, declared);');
).toContain('col = declared === null ? textColumn() : table.string(name, declared);');
expect(arm).toContain('const declared = this.declaredVarcharLength(field);');

const members = armMembers('email');
Expand Down
15 changes: 14 additions & 1 deletion packages/drivers/driver-sql/src/schema-drift.ts
Original file line number Diff line number Diff line change
Expand Up @@ -901,6 +901,7 @@ export type PhysicalDefault =

const BARE_NUMBER = /^[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?$/;
const EXPRESSION_KEYWORD = /^(current_timestamp|current_date|current_time|localtimestamp|localtime|now|sysdate|uuid|gen_random_uuid|nextval)\b/i;
const MYSQL_INTRODUCED_STRING = /^_[A-Za-z0-9]+\\'[\s\S]*\\'$/;
const TRAILING_CAST = /^::\s*[A-Za-z_][\w\s"]*(\(\s*\d+(\s*,\s*\d+)?\s*\))?(\[\])?$/;

/** See {@link PhysicalDefault}. */
Expand Down Expand Up @@ -936,6 +937,15 @@ export function physicalDefaultLiteral(raw: unknown): PhysicalDefault {
if (BARE_NUMBER.test(s)) return { kind: 'literal', text: s };
if (/^(true|false)$/i.test(s)) return { kind: 'literal', text: s.toLowerCase() };
if (s.includes('(') || EXPRESSION_KEYWORD.test(s)) return { kind: 'expression' };
// [#37320] MySQL 8 reports an EXPRESSION default over a string — the
// `DEFAULT ('d')` `createColumn` gives a TEXT column, the only DEFAULT such a
// column takes — as the charset-introduced, backslash-escaped `_utf8mb4\'d\'`
// (`EXTRA = DEFAULT_GENERATED`; measured on 8.0.46). It is an expression to
// MySQL and is read as one here, so neither literal arm acts on it: the
// restating `ALTER COLUMN … SET DEFAULT` is refused on a TEXT column
// (`ER_BLOB_CANT_HAVE_DEFAULT`, measured, the parenthesised form included),
// and read as a bare literal it compared unequal to every declaration.
if (MYSQL_INTRODUCED_STRING.test(s)) return { kind: 'expression' };
// MySQL 8 reports a string literal bare; anything else bare is a keyword
// this module does not know, which is not worth guessing at.
return /\s/.test(s) || /^[A-Z_]+$/.test(s) ? { kind: 'expression' } : { kind: 'literal', text: s };
Expand Down Expand Up @@ -1491,7 +1501,10 @@ export function diffManagedTable(args: {
// token (`NOW()` has its own expression, the app-resolved ones the arm
// above), an object, a multi-value column (no scalar DEFAULT at all) and a
// physical EXPRESSION are left alone, and so is a column with no DEFAULT
// under a declared one (on MySQL a TEXT column cannot carry the literal).
// under a declared one (on MySQL a TEXT column cannot carry the literal;
// since #37320 a fresh one carries the EXPRESSION form, read as an
// expression by `physicalDefaultLiteral`, and one an earlier release
// created carries no DEFAULT at all).
{
const dv = field.defaultValue;
const physical = physicalDefaultLiteral(col.defaultValue);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,9 @@ describe('#36245 §1 — reading a physical DEFAULT', () => {
['current_timestamp(3)', { kind: 'expression' }],
["nextval('seq'::regclass)", { kind: 'expression' }],
["('x' || 'y')", { kind: 'expression' }],
// [#37320] MySQL 8's spelling of a TEXT column's `DEFAULT ('d')`.
[String.raw`_utf8mb4\'d\'`, { kind: 'expression' }],
[String.raw`_latin1\'it\\\'s\'`, { kind: 'expression' }],
])('%j → %j', (raw, expected) => {
expect(physicalDefaultLiteral(raw)).toEqual(expected);
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,16 @@ function declareAddColumnNotNullSuite(cell: DialectCell): void {
expect(ops).not.toContain('tighten_not_null:added_dflt');
});

// [#37320] The DEFAULT the column took is the one the field declares, so
// the differ proposes nothing for it at all — not a `set_column_default`
// restating it. MySQL reports a TEXT column's DEFAULT in its expression
// spelling, and that is the shape that must not read as a different
// literal (the restate statement is refused on a TEXT column there).
it('reports no drift for the column that took its declared literal default', async () => {
const ops = opsOf(await driver.detectManagedDrift([V2(POPULATED)]));
expect(ops.filter((o) => o.endsWith(':added_dflt'))).toEqual([]);
});

it('the object stays writable', async () => {
const created: any = await driver.create(POPULATED, { plain: 'new', added: 'named', added_tags: ['t'] });
const row: any = await driver.findOne(POPULATED, { where: { id: created.id } });
Expand Down
33 changes: 29 additions & 4 deletions packages/drivers/driver-sql/src/sql-driver-column-creation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ import {
} from './sql-driver-top-level.js';
import type { RowWidthContribution } from './sql-driver-top-level.js';
import { emitsDeclaredColumnDefault } from './sql-driver-schema-sync.js';
import { SqlDriverStatics as SqlDriver } from './sql-driver.js';
import { isNowDefaultValue, SqlDriverStatics as SqlDriver } from './sql-driver.js';
import type { SqlDriver as SqlDriverClass } from './sql-driver.js';

/**
Expand Down Expand Up @@ -787,6 +787,31 @@ export class ColumnCreationFacet {
if (!isDeclaredFieldType(field)) refuseUndeclaredFieldType(name);
const type: string = field.type;
let col: any;
// [#37320] An unbounded text column, on every branch below that builds one.
// knex's MySQL column compiler silently drops ANY default on a `text`
// builder (its `defaultTo` answers '' for a text/blob type, a raw
// expression included), and MySQL refuses a literal DEFAULT on a TEXT
// column anyway (`ER_BLOB_CANT_HAVE_DEFAULT`). So a declared literal
// `defaultValue` never reached the DDL there: `ALTER TABLE … ADD COLUMN …
// TEXT NOT NULL` on a populated table filled every existing row with the
// implicit '' instead of the declared value, and every insert that omitted
// the field was refused (`Field '…' doesn't have a default value`).
// MySQL 8.0.13+ (and MariaDB 10.2+, the floor `nowColumnDefault` already
// states) accepts the EXPRESSION form, `DEFAULT ('d')`, on TEXT — measured
// on MySQL 8.0.46: existing rows take it on ADD COLUMN and an omitting
// insert stores it. So the column is declared through `specificType`,
// which knex's compiler does not strip, and {@link applyDeclaredColumnDefault}
// is asked for the expression form. Only for a literal default: `NOW()`
// on a text column keeps the old behaviour (no DEFAULT), because
// `nowColumnDefault` has no text-column expression on MySQL.
let mysqlTextDefault = false;
const textColumn = () => {
if (this.isMysql && emitsDeclaredColumnDefault(field) && !isNowDefaultValue(field.defaultValue)) {
mysqlTextDefault = true;
return table.specificType(name, 'text');
}
return table.text(name);
};
switch (type) {
case 'string':
case 'email':
Expand Down Expand Up @@ -825,7 +850,7 @@ export class ColumnCreationFacet {
// untouched. What this removes is the permanent, self-inflicted drift
// report a fresh table used to raise against itself.
const declared = this.declaredVarcharLength(field);
col = declared === null ? table.text(name) : table.string(name, declared);
col = declared === null ? textColumn() : table.string(name, declared);
break;
}
case 'text':
Expand Down Expand Up @@ -926,7 +951,7 @@ export class ColumnCreationFacet {
// {@link explainUnkeyableTextColumn} for what happens next, which is
// a named refusal and never a silently weaker constraint.
const keyable = keyed ? this.keyableTextLength(field) : null;
col = keyable === null ? table.text(name) : table.string(name, keyable);
col = keyable === null ? textColumn() : table.string(name, keyable);
break;
}
case 'integer':
Expand Down Expand Up @@ -1200,7 +1225,7 @@ export class ColumnCreationFacet {
// added to a populated table with no DEFAULT its rows can take — see the
// head of this method.
if (notNull || tenantColumn) col.notNullable();
this.applyDeclaredColumnDefault(col, field, type);
this.applyDeclaredColumnDefault(col, field, type, mysqlTextDefault);
}
}
}
14 changes: 11 additions & 3 deletions packages/drivers/driver-sql/src/sql-driver-schema-sync.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2843,9 +2843,17 @@ export function emitsDeclaredColumnDefault(field: any): boolean {
return !isRuntimeDefaultToken(dv) && typeof dv !== 'object';
}

/** The body of `SqlDriver#applyDeclaredColumnDefault`; the method's docblock there is its contract. */
export function applyDeclaredColumnDefault(this: Pick<SchemaSyncHost, 'nowColumnDefault'>, col: Knex.ColumnBuilder, field: any, type: string): void {
/**
* The body of `SqlDriver#applyDeclaredColumnDefault`; the method's docblock there is its contract.
*
* [#37320] `expressionForm`: the literal is emitted parenthesised, `DEFAULT
* ('d')` — the only DEFAULT a MySQL TEXT column takes (MySQL 8.0.13+ /
* MariaDB 10.2+). `createColumn` asks for it on exactly that column, which it
* builds through `specificType` so knex does not strip the clause.
*/
export function applyDeclaredColumnDefault(this: Pick<SchemaSyncHost, 'knex' | 'nowColumnDefault'>, col: Knex.ColumnBuilder, field: any, type: string, expressionForm: boolean = false): void {
if (!emitsDeclaredColumnDefault(field)) return;
const dv = field.defaultValue;
col.defaultTo(isNowDefaultValue(dv) ? this.nowColumnDefault(type) : (dv as any));
if (isNowDefaultValue(dv)) col.defaultTo(this.nowColumnDefault(type));
else col.defaultTo(expressionForm ? this.knex.raw('(?)', [dv]) : (dv as any));
}
6 changes: 3 additions & 3 deletions packages/drivers/driver-sql/src/sql-driver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9031,12 +9031,12 @@ export class SqlDriver implements IDataDriver {
* not reading `options` either. Pinned by
* `sql-driver-option-default-ddl.test.ts`.
*/
protected applyDeclaredColumnDefault(col: Knex.ColumnBuilder, field: any, type: string): void {
protected applyDeclaredColumnDefault(col: Knex.ColumnBuilder, field: any, type: string, expressionForm: boolean = false): void {
// [#25521 cut 19] The body moved to `sql-driver-schema-sync.ts` (see `SchemaSyncHost`).
const host: ThisParameterType<typeof applyDeclaredColumnDefault> = {
nowColumnDefault: (...a) => this.nowColumnDefault(...a),
knex: this.knex, nowColumnDefault: (...a) => this.nowColumnDefault(...a),
};
return applyDeclaredColumnDefault.call(host, col, field, type);
return applyDeclaredColumnDefault.call(host, col, field, type, expressionForm);
}

// ── Database helpers ────────────────────────────────────────────────────────
Expand Down
Loading