@proteinjs/user-server 1.25.0 → 1.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,66 @@
1
+ import { Db, Migration, SourceRecordLoader, tables as dbTables } from '@proteinjs/db';
2
+ import { tables } from '@proteinjs/user';
3
+ import { Logger } from '@proteinjs/logger';
4
+
5
+ /**
6
+ * Retires the legacy `user.roles` text column's data. The cutover to the typed `role_list` array
7
+ * (BackfillUserRolesArray) left the old comma-text column physically present and undeclared, its
8
+ * cells intact on every pre-cutover row: a stored key that is also the property's name (`roles`),
9
+ * riding every read of the table. The row reader seats a cell by its declared column name alone
10
+ * (@proteinjs/db ≥ 1.55.0), so the cell is inert — but data no declared column owns has no
11
+ * business on the row. This NULLs it wherever the typed column already carries the roles, or the
12
+ * legacy cell holds nothing to carry (the empty string a pre-cutover signup wrote).
13
+ *
14
+ * Never a legacy value the backfill has not consumed: a row with legacy text and no `role_list`
15
+ * is left for BackfillUserRolesArray — this migration cannot run ahead of it by construction.
16
+ *
17
+ * Idempotent by shape: a NULLed cell no longer matches. Automated (the deploy-gated series); the
18
+ * column itself goes in a later `manual` migration (a destructive contraction), once every
19
+ * environment reads zero legacy cells. Raw SQL through the driver on both sides, as the backfill
20
+ * reads it: the column is undeclared, so the ORM neither reads nor writes it. A database whose
21
+ * user table never had the column (a fresh install) is a clean no-op.
22
+ */
23
+ export class RetireLegacyUserRolesColumn implements SourceRecordLoader<Migration> {
24
+ table = dbTables.Migration;
25
+ record = {
26
+ id: '2f6c0b9e-9c7a-4e0d-8f1b-5a3d7c2e9b41',
27
+ description: `Retire the legacy comma-text user.roles column's cells once role_list carries the roles`,
28
+ estimate: async () => {
29
+ if (!(await this.legacyColumnExists())) {
30
+ return { units: 0, unit: 'rows', note: 'no legacy roles column on the user table' };
31
+ }
32
+
33
+ const counted = (await Db.getDefaultDbDriver().runQuery(() => ({
34
+ sql: `SELECT COUNT(*) AS pending FROM ${tables.User.name} WHERE ${this.retirableCells()}`,
35
+ }))) as unknown as Array<{ pending: number | string }>;
36
+ return { units: Number(counted[0]?.pending ?? 0), unit: 'rows' };
37
+ },
38
+ run: async () => {
39
+ const logger = new Logger({ name: this.constructor.name });
40
+ if (!(await this.legacyColumnExists())) {
41
+ logger.info({ message: `No legacy roles column on ${tables.User.name}; nothing to retire` });
42
+ return { retired: 0 };
43
+ }
44
+
45
+ const retired = await Db.getDefaultDbDriver().runDml(() => ({
46
+ sql: `UPDATE ${tables.User.name} SET roles = NULL WHERE ${this.retirableCells()}`,
47
+ }));
48
+ logger.info({ message: `Retired legacy user roles cells`, obj: { retired } });
49
+ return { retired };
50
+ },
51
+ };
52
+
53
+ /** The cells this migration may NULL: a legacy value the typed column already carries, or nothing at all. */
54
+ private retirableCells(): string {
55
+ return `roles IS NOT NULL AND (role_list IS NOT NULL OR roles = '')`;
56
+ }
57
+
58
+ private async legacyColumnExists(): Promise<boolean> {
59
+ const legacyColumn = await Db.getDefaultDbDriver().runQuery(() => ({
60
+ sql:
61
+ `SELECT column_name FROM information_schema.columns ` +
62
+ `WHERE table_name = '${tables.User.name}' AND column_name = 'roles'`,
63
+ }));
64
+ return legacyColumn.length > 0;
65
+ }
66
+ }
@@ -4,18 +4,26 @@ import { SpannerEmulatorProvisioner, getDropTestTable } from '@proteinjs/db-driv
4
4
  import { SourceRepository } from '@proteinjs/reflection';
5
5
  import { tables } from '@proteinjs/user';
6
6
  import { BackfillUserRolesArray } from '../src/migrations/BackfillUserRolesArray';
7
+ import { RetireLegacyUserRolesColumn } from '../src/migrations/RetireLegacyUserRolesColumn';
7
8
 
8
9
  /**
9
- * The user.roles cutover migration against a real Spanner emulator, simulating a deployed
10
+ * The user.roles cutover migrations against a real Spanner emulator, simulating a deployed
10
11
  * database: the user table carries the NEW schema (role_list, added by schema sync) PLUS the
11
12
  * legacy comma-string `roles` column with pre-cutover data — exactly the state a deployment is
12
- * in when the migration runs.
13
+ * in when the migrations run. Every read below goes through the ORM: what the row reader makes
14
+ * of a row holding BOTH cells — the legacy `roles` (a word, an empty string, NULL) and the typed
15
+ * `role_list` — is the law this suite proves, not a comment's claim.
13
16
  *
14
17
  * Pinned outcomes:
15
18
  * - legacy comma strings land in role_list as normalized arrays (trim, drop empties, dedupe)
16
- * - empty/NULL legacy values stay untouched (no roles then, no roles now)
17
- * - rows already carrying role_list are never clobbered (idempotence / post-cutover grants win)
18
- * - a database that never had the legacy column (fresh install) is a clean no-op
19
+ * - empty/NULL legacy values stay untouched by the backfill (no roles then, no roles now)
20
+ * - rows already carrying role_list are never clobbered (idempotence / post-cutover grants win),
21
+ * and the ORM reads the array beside the stale legacy word
22
+ * - the retirement NULLs every legacy cell the typed column has absorbed — or that held nothing —
23
+ * and never one the backfill has not consumed; the ORM reads the same arrays before and after
24
+ * (a NULL legacy cell beside the array is the shape a row reader seating by property name
25
+ * would blank)
26
+ * - a database that never had the legacy column (fresh install) is a clean no-op for both
19
27
  */
20
28
 
21
29
  const spannerDriver = new SpannerDriver({
@@ -33,6 +41,8 @@ class DbDriverFactory {
33
41
  const dropTable = getDropTestTable(spannerDriver);
34
42
 
35
43
  const runMigration = async () => await new BackfillUserRolesArray().record.run();
44
+ const runRetirement = async () => await new RetireLegacyUserRolesColumn().record.run();
45
+ const estimateRetirement = async () => await new RetireLegacyUserRolesColumn().record.estimate();
36
46
 
37
47
  const rawUserInsert = async (id: string, legacyRoles: string | null) => {
38
48
  const rolesValue = legacyRoles === null ? 'NULL' : `'${legacyRoles}'`;
@@ -51,6 +61,14 @@ const rawRoleList = async (id: string) =>
51
61
  }))) as unknown as Array<{ role_list: string | null }>
52
62
  )[0].role_list;
53
63
 
64
+ /** The legacy cell as the database holds it. */
65
+ const rawRoles = async (id: string) =>
66
+ (
67
+ (await spannerDriver.runQuery(() => ({
68
+ sql: `SELECT roles FROM ${tables.User.name} WHERE id = '${id}'`,
69
+ }))) as unknown as Array<{ roles: string | null }>
70
+ )[0].roles;
71
+
54
72
  describe('BackfillUserRolesArray — legacy comma-string roles → typed role_list', () => {
55
73
  beforeAll(async () => {
56
74
  (SourceRepository.get() as any).objectCache['@proteinjs/db/DefaultDbDriverFactory'] = [new DbDriverFactory()];
@@ -72,8 +90,64 @@ describe('BackfillUserRolesArray — legacy comma-string roles → typed role_li
72
90
 
73
91
  it('is a clean no-op on a database that never had the legacy roles column', async () => {
74
92
  expect(await runMigration()).toEqual({ backfilled: 0 });
93
+ expect(await runRetirement()).toEqual({ retired: 0 });
94
+ expect(await estimateRetirement()).toMatchObject({ units: 0, unit: 'rows' });
75
95
  }, 60000);
76
96
 
97
+ it('retires every legacy cell the typed column has absorbed, never one the backfill has not consumed; the ORM reads the same arrays before and after', async () => {
98
+ await spannerDriver.runUpdateSchema(`ALTER TABLE ${tables.User.name} ADD COLUMN roles STRING(255)`);
99
+ const db = getDbAsSystem();
100
+ try {
101
+ await rawUserInsert('retire-carried', 'admin');
102
+ await rawUserInsert('retire-empty', '');
103
+ await rawUserInsert('retire-null', null);
104
+ // A legacy value the backfill has not consumed yet: role_list NULL, legacy text present.
105
+ await rawUserInsert('retire-unconsumed', 'ops');
106
+ // A post-cutover grant beside a stale legacy word (the collision shape).
107
+ const granted = await db.insert(tables.User, {
108
+ name: 'Granted',
109
+ email: 'granted@test.local',
110
+ password: 'test',
111
+ emailVerified: false,
112
+ roles: ['ops', 'dev'],
113
+ });
114
+ await spannerDriver.runDml(() => ({
115
+ sql: `UPDATE ${tables.User.name} SET roles = 'admin' WHERE id = '${granted.id}'`,
116
+ }));
117
+ // Carry the one consumable legacy value over (as the backfill would); leave 'retire-unconsumed' as a later backfill's.
118
+ await db.update(tables.User, { id: 'retire-carried', roles: ['admin'] });
119
+
120
+ // Before: the ORM reads the arrays beside the legacy cells, whatever they hold.
121
+ expect((await db.get(tables.User, { id: 'retire-carried' })).roles).toEqual(['admin']);
122
+ expect((await db.get(tables.User, { id: granted.id })).roles).toEqual(['ops', 'dev']);
123
+
124
+ expect(await estimateRetirement()).toMatchObject({ units: 3, unit: 'rows' });
125
+ expect(await runRetirement()).toEqual({ retired: 3 });
126
+
127
+ // The retired cells are NULL; the unconsumed legacy value is untouched.
128
+ expect(await rawRoles('retire-carried')).toBeNull();
129
+ expect(await rawRoles('retire-empty')).toBeNull();
130
+ expect(await rawRoles('retire-null')).toBeNull();
131
+ expect(await rawRoles(granted.id)).toBeNull();
132
+ expect(await rawRoles('retire-unconsumed')).toBe('ops');
133
+ expect(await rawRoleList('retire-unconsumed')).toBeNull();
134
+
135
+ // After: a NULL legacy cell beside the array — the ORM still reads the array.
136
+ expect((await db.get(tables.User, { id: 'retire-carried' })).roles).toEqual(['admin']);
137
+ expect((await db.get(tables.User, { id: granted.id })).roles).toEqual(['ops', 'dev']);
138
+ const everyone = await db.query(tables.User, {});
139
+ expect(everyone.find((user) => user.id === granted.id)?.roles).toEqual(['ops', 'dev']);
140
+ expect(everyone.find((user) => user.id === 'retire-carried')?.roles).toEqual(['admin']);
141
+
142
+ // Re-run: nothing left to retire.
143
+ expect(await runRetirement()).toEqual({ retired: 0 });
144
+ expect(await estimateRetirement()).toMatchObject({ units: 0, unit: 'rows' });
145
+ } finally {
146
+ await dropTable(tables.User as Table<any>);
147
+ await spannerDriver.getTableManager().loadTable(tables.User);
148
+ }
149
+ }, 120000);
150
+
77
151
  it('backfills, normalizes, preserves, and re-runs clean on a deployed-shape database', async () => {
78
152
  // Simulate the deployed state: the legacy column exists beside the new schema.
79
153
  await spannerDriver.runUpdateSchema(`ALTER TABLE ${tables.User.name} ADD COLUMN roles STRING(255)`);