Files
TREK/server/tests/unit/db/engine/postgres/schema-adjust.test.ts
T
Isaias Tavares 33a18f29dd refactor(db): split the Postgres schema adjustments by concern
schema-adjust.ts mixed the statement splitter, the trigger ports and the
column adjustments, and every caller repeated `meta.props as EntityProperty[]
as ColumnMeta[]` to reach them. Now:

- sql-split.ts holds splitStatements. Its scope is written down: `;` outside
  quotes, '/" quoted text and the $$ body, and the session-setting lines it
  drops. A tagged dollar quote ($tag$) is refused with an error instead of
  being split inside, which the splitter could not do correctly.
- postgres-triggers.ts holds the hand-written trigger ports, which the
  baseline and the parity test read by name.
- schema-adjust.ts holds the column adjustments. applyPostgresColumnAdjustments
  (renamed from adjustColumns, which hid that it mutates its input) takes an
  entity's props directly: ColumnMeta now reads customType as unknown, so
  the entity's property metadata satisfies it without a cast. Each adjustment
  is a small function that returns whether it changed the column.

The timestamp check is now `instanceof DbTimestampType` rather than a compare
on the constructor's name, which would have broken silently on a rename.
2026-11-05 00:32:18 -03:00

103 lines
4.9 KiB
TypeScript

/**
* How the entities' schema is written in Postgres
* (src/db/engine/postgres/schema-adjust.ts): SQLite-only defaults, TEXT timestamps, the
* NOCASE collation, and splitting the generated DDL so one refused statement
* does not take the rest with it.
*/
import { POSTGRES_TRIGGERS } from '../../../../../src/db/engine/postgres/postgres-triggers';
import {
applyPostgresColumnAdjustments,
type ColumnMeta,
NOCASE_COLLATION_SQL,
PG_NOW_TEXT_DEFAULT,
portableDefault,
} from '../../../../../src/db/engine/postgres/schema-adjust';
import { splitStatements } from '../../../../../src/db/engine/postgres/sql-split';
import { DbTimestampType } from '../../../../../src/db/types';
import { describe, expect, it } from 'vitest';
class TextType {}
describe('pg-probe schema', () => {
it('PGPROBE-040: maps the SQLite clock defaults and leaves every other default alone', () => {
expect(PG_NOW_TEXT_DEFAULT).toBe("to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS')");
expect(portableDefault('CURRENT_TIMESTAMP')).toBe(PG_NOW_TEXT_DEFAULT);
expect(portableDefault("(datetime('now'))")).toBe(PG_NOW_TEXT_DEFAULT);
expect(portableDefault("datetime( 'now' )")).toBe(PG_NOW_TEXT_DEFAULT);
expect(portableDefault("(strftime('%s','now'))")).toBe('CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) AS bigint)');
for (const kept of ['0', '1', 'NULL', "'none'", "'#10b981'", "'{}'"]) expect(portableDefault(kept)).toBe(kept);
});
it('PGPROBE-041: makes timestamp columns text, rewrites defaults and the NOCASE collation, and names what it changed', () => {
const columns: ColumnMeta[] = [
{
name: 'created_at',
customType: new DbTimestampType(),
columnTypes: ['timestamptz'],
defaultRaw: 'CURRENT_TIMESTAMP',
},
{ name: 'title', customType: new TextType(), columnTypes: ['text'], defaultRaw: "'x'" },
{ name: 'stamp', columnTypes: ['int'], defaultRaw: "(strftime('%s','now'))" },
{ name: 'region', columnTypes: ['text'], collation: 'NOCASE' },
{ name: 'body', columnTypes: ['text'] },
];
expect(applyPostgresColumnAdjustments(columns)).toEqual(['created_at', 'stamp', 'region']);
expect(columns[0]).toMatchObject({ columnTypes: ['text'], defaultRaw: PG_NOW_TEXT_DEFAULT });
expect(columns[1]).toMatchObject({ columnTypes: ['text'], defaultRaw: "'x'" });
expect(columns[2]).toMatchObject({
columnTypes: ['bigint'],
defaultRaw: 'CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) AS bigint)',
});
expect(columns[3]).toMatchObject({ collation: 'nocase' });
expect(NOCASE_COLLATION_SQL).toContain('CREATE COLLATION IF NOT EXISTS nocase');
});
it('PGPROBE-043: an integer column is bigint, as wide as SQLite INTEGER (epoch milliseconds overflow integer)', () => {
const columns: ColumnMeta[] = [
{ name: 'id', columnTypes: ['integer'] },
{ name: 'next_run_at', columnTypes: ['int'] },
{ name: 'enabled', columnTypes: ['boolean'] },
{ name: 'note', columnTypes: ['text'] },
];
expect(applyPostgresColumnAdjustments(columns)).toEqual(['id', 'next_run_at']);
expect(columns.map((column) => column.columnTypes)).toEqual([['bigint'], ['bigint'], ['boolean'], ['text']]);
});
it('PGPROBE-042: splits DDL on semicolons outside quotes and drops session settings', () => {
const ddl = [
"set names 'utf8';",
'create table "a" ("id" serial primary key, "note" text default \'a;b\');',
'create index "a_x" on "a" ("note") where "note" <> \';\';',
'',
'create table "b ;" ("id" int)',
].join('\n');
expect(splitStatements(ddl)).toEqual([
'create table "a" ("id" serial primary key, "note" text default \'a;b\')',
'create index "a_x" on "a" ("note") where "note" <> \';\'',
'create table "b ;" ("id" int)',
]);
expect(splitStatements(' ; ; ')).toEqual([]);
});
it('PGPROBE-045: refuses a tagged dollar quote, which it does not understand, rather than splitting inside it', () => {
expect(() => splitStatements('create function f() as $f$ select 1; $f$;')).toThrow(
/only the \$\$ dollar quote, not \$f\$/,
);
expect(splitStatements("select '$f$'; select 2")).toEqual(["select '$f$'", 'select 2']);
});
it('PGPROBE-044: a $$ body stays one statement, semicolons and all, and every trigger port splits into its two', () => {
const fn =
"CREATE FUNCTION f() RETURNS trigger LANGUAGE plpgsql AS $$\nBEGIN\n UPDATE t SET x = ';';\n RETURN NEW;\nEND\n$$";
expect(splitStatements(`${fn};\nCREATE TRIGGER g AFTER UPDATE ON t FOR EACH ROW EXECUTE FUNCTION f();`)).toEqual([
fn,
'CREATE TRIGGER g AFTER UPDATE ON t FOR EACH ROW EXECUTE FUNCTION f()',
]);
for (const [name, statements] of Object.entries(POSTGRES_TRIGGERS)) {
expect(splitStatements(statements.join(';\n')), name).toEqual([...statements]);
expect(statements.at(-1), name).toContain(`CREATE TRIGGER ${name} `);
}
});
});