|
| 1 | +/** |
| 2 | + * @vitest-environment node |
| 3 | + */ |
| 4 | + |
| 5 | +// Renders the real expression against the real drizzle dialect and schema. It |
| 6 | +// is a raw `sql` template, so a rendering or type-cast bug only surfaces when |
| 7 | +// Postgres executes it — the global drizzle/schema mocks would hide it. |
| 8 | +import { describe, expect, it, vi } from 'vitest' |
| 9 | + |
| 10 | +vi.unmock('drizzle-orm') |
| 11 | +vi.unmock('@sim/db') |
| 12 | +vi.unmock('@sim/db/schema') |
| 13 | + |
| 14 | +process.env.DATABASE_URL ??= 'postgresql://user:pass@localhost:5432/test' |
| 15 | + |
| 16 | +const { PgDialect } = await import('drizzle-orm/pg-core') |
| 17 | +const { elapsedDurationMsSql } = await import('@/lib/logs/execution/duration') |
| 18 | + |
| 19 | +function render(endedAt: Date) { |
| 20 | + return new PgDialect().sqlToQuery(elapsedDurationMsSql(endedAt)) |
| 21 | +} |
| 22 | + |
| 23 | +describe('elapsedDurationMsSql', () => { |
| 24 | + it('measures against the row started_at rather than a second clock read', () => { |
| 25 | + const { sql } = render(new Date('2026-08-13T12:00:05.000Z')) |
| 26 | + |
| 27 | + expect(sql).toContain('"started_at"') |
| 28 | + expect(sql).not.toContain('now()') |
| 29 | + }) |
| 30 | + |
| 31 | + /** |
| 32 | + * `started_at` is `timestamp without time zone` holding a UTC wall clock. A |
| 33 | + * driver-bound `Date` infers `timestamptz`, which would make the interval |
| 34 | + * depend on the session zone; the explicit cast is what keeps it stable. |
| 35 | + */ |
| 36 | + it('binds the end instant as a zone-free timestamp', () => { |
| 37 | + const { sql, params } = render(new Date('2026-08-13T12:00:05.000Z')) |
| 38 | + |
| 39 | + expect(sql).toContain('::timestamp') |
| 40 | + expect(params).toEqual(['2026-08-13T12:00:05.000Z']) |
| 41 | + expect(params.some((param) => Array.isArray(param))).toBe(false) |
| 42 | + }) |
| 43 | + |
| 44 | + /** The column is `integer`, and a sub-millisecond run still ran. */ |
| 45 | + it('yields a whole number of milliseconds, floored at one', () => { |
| 46 | + const { sql } = render(new Date('2026-08-13T12:00:05.000Z')) |
| 47 | + |
| 48 | + expect(sql).toContain('GREATEST(1,') |
| 49 | + expect(sql).toContain('ROUND(') |
| 50 | + expect(sql).toContain('::integer') |
| 51 | + }) |
| 52 | +}) |
0 commit comments