|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * `os migrate organization-ownership` reads its SQL dialect off the stack's |
| 5 | + * driver ONCE, before the first statement, through the resolver it shares |
| 6 | + * with `@objectstack/metadata-core` (`ceremonyDialectOf` → `dialectOfDriver`): |
| 7 | + * the driver's `dialectName` first, then a recognised `config.client` string. |
| 8 | + * On anything else both arms refuse, naming the driver, with exit 1 and no |
| 9 | + * statement run; neither arm reads an unresolved dialect as SQLite. |
| 10 | + * |
| 11 | + * The boot is replaced by a stack whose driver records every statement and |
| 12 | + * answers each with no rows; the apply step is replaced by a recorder (its own |
| 13 | + * suite pins what it does with the executor it is handed). The driver shapes |
| 14 | + * are the ones each in-repo driver presents, measured on the drivers |
| 15 | + * themselves: `SqliteWasmDriver`'s knex `client` is a dialect CLASS and its |
| 16 | + * `dialectName` is `'sqlite'`; `SqlDriver` answers `dialectName: 'unknown'` |
| 17 | + * for a client it does not recognise, a client class included. |
| 18 | + * |
| 19 | + * The `SqliteWasmDriver` row pins the resolver's answer for that SHAPE. The |
| 20 | + * command's boot does not hand that driver over today (the schema boot looks |
| 21 | + * a SQL driver up by service names that do not include it, so a |
| 22 | + * `wasm-sqlite://` run is refused earlier, as having no SQL driver at all); |
| 23 | + * the row keeps the answer right for the day it does. |
| 24 | + */ |
| 25 | + |
| 26 | +import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; |
| 27 | +import { existsSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; |
| 28 | +import { tmpdir } from 'node:os'; |
| 29 | +import { join } from 'node:path'; |
| 30 | +import { fileURLToPath } from 'node:url'; |
| 31 | + |
| 32 | +const boot = vi.hoisted(() => vi.fn()); |
| 33 | +vi.mock('../../utils/schema-migrate.js', () => ({ bootSchemaStack: boot })); |
| 34 | +// The siblings' occupancy stub: no case here passes --database-url, so the real |
| 35 | +// probe would read whatever database the package's own directory resolves to. |
| 36 | +vi.mock('../../utils/migrate-occupancy-gate.js', () => ({ |
| 37 | + OCCUPANCY_STOP_HINT: 'occupancy hint', |
| 38 | + probeMigrationTarget: vi.fn(async () => ({ status: 'free' })), |
| 39 | +})); |
| 40 | + |
| 41 | +const apply = vi.hoisted(() => vi.fn()); |
| 42 | +vi.mock('../../utils/organization-ownership-apply.js', async (importOriginal) => ({ |
| 43 | + ...(await importOriginal<typeof import('../../utils/organization-ownership-apply.js')>()), |
| 44 | + applyOrganizationOwnership: apply, |
| 45 | +})); |
| 46 | + |
| 47 | +type Command = (typeof import('./organization-ownership.js'))['default']; |
| 48 | +let MigrateOrganizationOwnership: Command; |
| 49 | + |
| 50 | +// The command's module graph is large, and oclif reads the package's config on |
| 51 | +// the first run: both are paid outside the 5 s default (CASE_TIMEOUT_MS). |
| 52 | +beforeAll(async () => { |
| 53 | + ({ default: MigrateOrganizationOwnership } = await import('./organization-ownership.js')); |
| 54 | +}, 60_000); |
| 55 | + |
| 56 | +const CASE_TIMEOUT_MS = 60_000; |
| 57 | +const CLI_ROOT = fileURLToPath(new URL('../../..', import.meta.url)); |
| 58 | + |
| 59 | +/** knex's bring-your-own-dialect hatch: a Client constructor as `config.client`. */ |
| 60 | +class Client_PG {} |
| 61 | +class Client_WasmSqlite {} |
| 62 | + |
| 63 | +interface DriverShape { |
| 64 | + name?: string; |
| 65 | + dialectName?: string; |
| 66 | + config?: { client?: unknown }; |
| 67 | +} |
| 68 | + |
| 69 | +/** Refused: no dialect the ceremony can write statements for. */ |
| 70 | +const REFUSED: Array<[string, DriverShape]> = [ |
| 71 | + ['a client class with no dialectName', { name: 'com.example.driver', config: { client: Client_PG } }], |
| 72 | + ['a client class, as SqlDriver answers it (dialectName unknown)', { name: 'com.objectstack.driver.sql', dialectName: 'unknown', config: { client: Client_PG } }], |
| 73 | + ['an unrecognised client string', { name: 'com.objectstack.driver.sql', config: { client: 'oracledb' } }], |
| 74 | + ['dialectName unknown beside a recognised client string', { name: 'com.objectstack.driver.sql', dialectName: 'unknown', config: { client: 'pg' } }], |
| 75 | + ['a driver with neither a dialectName nor a client', { name: 'com.example.driver' }], |
| 76 | +]; |
| 77 | + |
| 78 | +/** Proceeds: each in-repo driver's measured shape, and the first statement its dialect's catalog read. */ |
| 79 | +const PROCEEDS: Array<[string, DriverShape, RegExp]> = [ |
| 80 | + ['SqlDriver on better-sqlite3', { name: 'com.objectstack.driver.sql', dialectName: 'sqlite', config: { client: 'better-sqlite3' } }, /FROM sqlite_master/], |
| 81 | + ['SqliteWasmDriver (a client class, dialectName sqlite)', { name: 'com.objectstack.driver.sqlite-wasm', dialectName: 'sqlite', config: { client: Client_WasmSqlite } }, /FROM sqlite_master/], |
| 82 | + ['SqlDriver on pg', { name: 'com.objectstack.driver.sql', dialectName: 'postgres', config: { client: 'pg' } }, /current_schemas\(false\)/], |
| 83 | + ['SqlDriver on mysql2', { name: 'com.objectstack.driver.sql', dialectName: 'mysql', config: { client: 'mysql2' } }, /table_schema = DATABASE\(\)/], |
| 84 | + ['TursoDriver', { name: 'com.objectstack.driver.turso', dialectName: 'sqlite', config: { client: 'better-sqlite3' } }, /FROM sqlite_master/], |
| 85 | + ['a driver with no dialectName and a recognised client string', { name: 'com.example.driver', config: { client: 'postgresql' } }, /current_schemas\(false\)/], |
| 86 | +]; |
| 87 | + |
| 88 | +let dir: string; |
| 89 | +/** Every statement the driver was handed, in order. */ |
| 90 | +let statements: string[]; |
| 91 | + |
| 92 | +function stackOver(shape: DriverShape) { |
| 93 | + return { |
| 94 | + driver: { |
| 95 | + ...shape, |
| 96 | + execute: async (sql: string) => { |
| 97 | + statements.push(sql); |
| 98 | + return []; |
| 99 | + }, |
| 100 | + }, |
| 101 | + dbLabel: 'fixture.db', |
| 102 | + kernel: { |
| 103 | + getService: (name: string) => |
| 104 | + name === 'objectql' |
| 105 | + ? { registry: { getItem: () => undefined, listItems: () => [], isPackageDisabled: () => false } } |
| 106 | + : name === 'metadata' |
| 107 | + ? { get: async () => undefined, list: async () => [] } |
| 108 | + : undefined, |
| 109 | + }, |
| 110 | + tableAbsent: () => false, |
| 111 | + composition: { securityPlugin: { composed: false, reason: 'no-secret' } }, |
| 112 | + shutdown: async () => {}, |
| 113 | + }; |
| 114 | +} |
| 115 | + |
| 116 | +beforeEach(() => { |
| 117 | + dir = mkdtempSync(join(tmpdir(), 'os-ownership-dialect-')); |
| 118 | + statements = []; |
| 119 | + apply.mockImplementation(async () => ({ |
| 120 | + kind: 'organization-ownership-apply', |
| 121 | + generatedAt: '2026-10-15T00:00:00.000Z', |
| 122 | + steps: [], |
| 123 | + tables: [], |
| 124 | + complete: true, |
| 125 | + blocking: 0, |
| 126 | + advisory: 0, |
| 127 | + })); |
| 128 | +}); |
| 129 | + |
| 130 | +afterEach(() => { |
| 131 | + boot.mockReset(); |
| 132 | + apply.mockReset(); |
| 133 | + rmSync(dir, { recursive: true, force: true }); |
| 134 | +}); |
| 135 | + |
| 136 | +/** A plan file as a plan run writes it (the fields the apply reads). */ |
| 137 | +function writePlan(): string { |
| 138 | + const file = join(dir, 'reviewed-plan.json'); |
| 139 | + writeFileSync(file, JSON.stringify({ |
| 140 | + kind: 'organization-ownership-plan', |
| 141 | + ceremony: 'ADR-0131 D10', |
| 142 | + generatedAt: '2026-10-15T00:00:00.000Z', |
| 143 | + database: 'fixture.db', |
| 144 | + inventoryDigest: 'f'.repeat(64), |
| 145 | + posture: 'single', |
| 146 | + })); |
| 147 | + return file; |
| 148 | +} |
| 149 | + |
| 150 | +async function runJson(argv: string[]): Promise<{ payload: Record<string, unknown>; exitCode: unknown }> { |
| 151 | + const chunks: string[] = []; |
| 152 | + const savedExit = process.exitCode; |
| 153 | + vi.spyOn(process.stdout, 'write').mockImplementation(((chunk: unknown, ...rest: unknown[]) => { |
| 154 | + chunks.push(String(chunk)); |
| 155 | + const cb = rest.find((a) => typeof a === 'function') as (() => void) | undefined; |
| 156 | + if (cb) cb(); |
| 157 | + return true; |
| 158 | + }) as typeof process.stdout.write); |
| 159 | + vi.spyOn(process.stderr, 'write').mockImplementation((() => true) as typeof process.stderr.write); |
| 160 | + try { |
| 161 | + await MigrateOrganizationOwnership.run(argv, { root: CLI_ROOT }); |
| 162 | + } catch (error) { |
| 163 | + if ((error as { oclif?: unknown }).oclif === undefined) throw error; |
| 164 | + } |
| 165 | + const exitCode = process.exitCode; |
| 166 | + process.exitCode = savedExit; |
| 167 | + vi.restoreAllMocks(); |
| 168 | + return { payload: JSON.parse(chunks.join('').trim()) as Record<string, unknown>, exitCode }; |
| 169 | +} |
| 170 | + |
| 171 | +describe('an unresolved dialect is refused, naming the driver, before any statement runs', () => { |
| 172 | + for (const [label, shape] of REFUSED) { |
| 173 | + it(`plan: ${label}`, async () => { |
| 174 | + boot.mockImplementation(async () => stackOver(shape)); |
| 175 | + const target = join(dir, 'plan.json'); |
| 176 | + const { payload, exitCode } = await runJson(['--out', target, '--json']); |
| 177 | + expect(payload).toMatchObject({ error: 'plan_refused', reason: 'driver-unsupported' }); |
| 178 | + expect(String(payload.detail)).toContain(shape.name!); |
| 179 | + expect(exitCode).toBe(1); |
| 180 | + expect(statements).toEqual([]); |
| 181 | + expect(existsSync(target)).toBe(false); |
| 182 | + }, CASE_TIMEOUT_MS); |
| 183 | + |
| 184 | + it(`--apply: ${label}`, async () => { |
| 185 | + boot.mockImplementation(async () => stackOver(shape)); |
| 186 | + const { payload, exitCode } = await runJson(['--apply', '--backup-taken', '--plan-file', writePlan(), '--out', join(dir, 'apply.json'), '--json']); |
| 187 | + expect(payload).toMatchObject({ error: 'apply_refused', reason: 'driver-unsupported' }); |
| 188 | + expect(String(payload.detail)).toContain(shape.name!); |
| 189 | + expect(exitCode).toBe(1); |
| 190 | + expect(statements).toEqual([]); |
| 191 | + expect(apply).not.toHaveBeenCalled(); |
| 192 | + }, CASE_TIMEOUT_MS); |
| 193 | + } |
| 194 | + |
| 195 | + it('a client class is named, never printed as its source', async () => { |
| 196 | + boot.mockImplementation(async () => stackOver({ name: 'com.example.driver', config: { client: Client_PG } })); |
| 197 | + const { payload } = await runJson(['--out', join(dir, 'plan.json'), '--json']); |
| 198 | + expect(String(payload.detail)).toContain('client class Client_PG'); |
| 199 | + expect(String(payload.detail)).not.toContain('class Client_PG {'); |
| 200 | + }, CASE_TIMEOUT_MS); |
| 201 | +}); |
| 202 | + |
| 203 | +describe('a recognised dialect proceeds, in that dialect', () => { |
| 204 | + for (const [label, shape, catalog] of PROCEEDS) { |
| 205 | + it(`plan: ${label}`, async () => { |
| 206 | + boot.mockImplementation(async () => stackOver(shape)); |
| 207 | + const { payload } = await runJson(['--out', join(dir, 'plan.json'), '--json']); |
| 208 | + // The driver answers no tables, so the plan stops at its catalog read, |
| 209 | + // past the dialect, which the catalog statement it issued names. |
| 210 | + expect(payload).toMatchObject({ error: 'plan_refused', reason: 'not-an-objectstack-database' }); |
| 211 | + expect(statements[0]).toMatch(catalog); |
| 212 | + }, CASE_TIMEOUT_MS); |
| 213 | + } |
| 214 | + |
| 215 | + it('--apply hands the apply step the dialect it resolved, and the client string only as a record', async () => { |
| 216 | + boot.mockImplementation(async () => stackOver({ name: 'com.objectstack.driver.sqlite-wasm', dialectName: 'sqlite', config: { client: Client_WasmSqlite } })); |
| 217 | + await runJson(['--apply', '--backup-taken', '--plan-file', writePlan(), '--out', join(dir, 'apply.json'), '--json']); |
| 218 | + expect(apply).toHaveBeenCalledTimes(1); |
| 219 | + const { executor } = apply.mock.calls[0]![0] as { executor: Record<string, unknown> }; |
| 220 | + expect(executor.dialect).toBe('sqlite'); |
| 221 | + expect(executor).not.toHaveProperty('client'); |
| 222 | + }, CASE_TIMEOUT_MS); |
| 223 | + |
| 224 | + it('--apply on pg: the executor speaks postgres', async () => { |
| 225 | + boot.mockImplementation(async () => stackOver({ name: 'com.objectstack.driver.sql', dialectName: 'postgres', config: { client: 'pg' } })); |
| 226 | + await runJson(['--apply', '--backup-taken', '--plan-file', writePlan(), '--out', join(dir, 'apply.json'), '--json']); |
| 227 | + expect(apply).toHaveBeenCalledTimes(1); |
| 228 | + expect(apply.mock.calls[0]![0]).toMatchObject({ executor: { dialect: 'postgres', client: 'pg' } }); |
| 229 | + }, CASE_TIMEOUT_MS); |
| 230 | +}); |
0 commit comments