import { readFileSync } from 'node:fs'; import { join } from 'node:path'; import { getConnections, PgTestClient } from 'pgsql-test'; let pg: PgTestClient; let teardown: () => Promise; const migration = (phase: string) => readFileSync(join(__dirname, '..', phase, 'functions', 'uuidv7.sql'), 'utf8') .replace(/^BEGIN;$/m, '').replace(/^(COMMIT|ROLLBACK);$/m, ''); beforeAll(async () => { ({ pg, teardown } = await getConnections({}, [])); }); afterAll(async () => teardown()); beforeEach(async () => pg.beforeEach()); afterEach(async () => pg.afterEach()); test('provides usable UUIDv7 and reverts without removing native UUIDv7', async () => { const [{ native }] = await pg.any( "SELECT to_regprocedure('pg_catalog.uuidv7(interval)') IS NOT NULL AS native" ); await pg.query(migration('deploy')); await pg.query(migration('verify')); const [{ id }] = await pg.any('SELECT uuidv7()::text AS id'); const timestamp = parseInt(id.slice(0, 13).replace('-', ''), 16); expect(Math.abs(Date.now() - timestamp)).toBeLessThan(5000); const [{ count }] = await pg.any('SELECT count(DISTINCT uuidv7())::int AS count FROM generate_series(1, 100)'); expect(count).toBe(100); await pg.query(migration('revert')); const [{ shim, usable }] = await pg.any(`SELECT to_regprocedure('public.uuidv7()') IS NOT NULL AS shim, to_regprocedure('pg_catalog.uuidv7(interval)') IS NOT NULL AS usable`); expect(shim).toBe(false); expect(usable).toBe(native); }); test('does not replace or remove an existing public.uuidv7()', async () => { await pg.query("CREATE FUNCTION public.uuidv7() RETURNS uuid LANGUAGE sql AS 'SELECT gen_random_uuid()'"); await pg.query(migration('deploy')); await pg.query(migration('revert')); const [{ existing }] = await pg.any("SELECT to_regprocedure('public.uuidv7()') IS NOT NULL AS existing"); expect(existing).toBe(true); });