import { execFileSync } from 'node:child_process'; import { DB_CONTAINER } from './config'; /** * Run a SQL statement against the local Supabase Postgres container and return * the raw psql output. Used for backend-state assertions and resets (spec ยง40: * "validate the resulting persisted state through a database-facing test helper"). */ export function psql(sql: string): string { const out = execFileSync('docker', ['exec', '-i', DB_CONTAINER, 'psql', '-U', 'postgres', '-t', '-A'], { input: sql, encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'], }); return out.trim(); } /** Sleep helper (ms). */ export function sleep(ms: number): Promise { return new Promise((r) => setTimeout(r, ms)); } /** Normalize a Postgres boolean rendered as `t`/`f` or `true`/`false`. */ export function isTrue(s: string): boolean { return s === 't' || s === 'true' || s === '1'; } /** * Poll a boolean SQL predicate until it is true (or timeout). Used to make * backend-state assertions robust against the small gap between a UI action * completing and the committed row being read by a fresh psql connection. */ export async function psqlUntil( sql: string, { timeoutMs = 5000, intervalMs = 150 } = {}, ): Promise { const deadline = Date.now() + timeoutMs; for (;;) { if (isTrue(psqlScalar(sql))) return true; if (Date.now() > deadline) return isTrue(psqlScalar(sql)); await sleep(intervalMs); } } /** Run a SQL statement and return the first column of the first row as a string. */ export function psqlScalar(sql: string): string { return psql(sql).split('\n')[0]?.trim() ?? ''; } /** Run a SQL statement and return all rows as an array of strings (one per row). */ export function psqlRows(sql: string): string[] { const out = psql(sql); return out ? out.split('\n').map((r) => r.trim()).filter(Boolean) : []; } /** Escape a string for safe interpolation into a SQL literal. */ export function sqlQuote(s: string): string { return `'${s.replace(/'/g, "''")}'`; } /** * A small, typed view over the demo data for the most common assertions. * Every method returns raw values; tests assert on them explicitly. */ export const db = { /** The registration row for a contact (or null). */ registration(contactEmail: string) { const row = psql( `select type || '|' || checked_in || '|' || coalesce(qr_token, '') || '|' || points from public.registrations where contact_email = ${sqlQuote(contactEmail)} limit 1`, ); if (!row) return null; const [type, checkedIn, qrToken, points] = row.split('|'); return { type, checkedIn: isTrue(checkedIn), qrToken, points: Number(points) }; }, /** Whether a contact is welcome-checked-in. */ isWelcomeCheckedIn(contactEmail: string): boolean { return this.registration(contactEmail)?.checkedIn ?? false; }, /** Poll until a contact is welcome-checked-in (robust against commit timing). */ async waitForWelcomeCheckedIn(contactEmail: string, timeoutMs = 5000): Promise { const deadline = Date.now() + timeoutMs; for (;;) { if (this.isWelcomeCheckedIn(contactEmail)) return true; if (Date.now() > deadline) return this.isWelcomeCheckedIn(contactEmail); await sleep(150); } }, /** Poll until a contact has a session check-in for the given session. */ async waitForSessionCheckin(contactEmail: string, sessionId: string, timeoutMs = 5000): Promise { const deadline = Date.now() + timeoutMs; for (;;) { if (this.sessionCheckins(contactEmail).includes(sessionId)) return true; if (Date.now() > deadline) return this.sessionCheckins(contactEmail).includes(sessionId); await sleep(150); } }, /** The session ids a contact is session-checked-in to. */ sessionCheckins(contactEmail: string): string[] { return psqlRows( `select session_id from public.checkins where contact_email = ${sqlQuote(contactEmail)} order by created_at`, ); }, /** The connection rows involving a contact (status|from|to). */ connections(contactEmail: string): { status: string; from: string; to: string }[] { return psqlRows( `select status || '|' || from_email || '|' || to_email from public.connections where from_email = ${sqlQuote(contactEmail)} or to_email = ${sqlQuote(contactEmail)} order by created_at`, ).map((r) => { const [status, from, to] = r.split('|'); return { status, from, to }; }); }, /** The feedback rows for a contact (session_id|rating). */ feedback(contactEmail: string): { sessionId: string; rating: number }[] { return psqlRows( `select session_id || '|' || rating from public.feedback where contact_email = ${sqlQuote(contactEmail)} order by created_at`, ).map((r) => { const [sessionId, rating] = r.split('|'); return { sessionId, rating: Number(rating) }; }); }, /** The contact's visibility settings (show_email|show_linkedin|linkedin_url). */ contact(contactEmail: string) { const row = psql( `select show_email || '|' || show_linkedin || '|' || coalesce(linkedin_url, '') from public.contacts where email = ${sqlQuote(contactEmail)} limit 1`, ); if (!row) return null; const [showEmail, showLinkedin, linkedinUrl] = row.split('|'); return { showEmail: isTrue(showEmail), showLinkedin: isTrue(showLinkedin), linkedinUrl }; }, /** Whether a session has material uploaded. */ sessionHasMaterial(sessionId: string): boolean { return isTrue( psqlScalar( `select material_path is not null from public.sessions where id = ${sqlQuote(sessionId)}`, ), ); }, /** The session_speakers rows for a contact. */ speakerSessions(contactEmail: string): string[] { return psqlRows( `select session_id from public.session_speakers where contact_email = ${sqlQuote(contactEmail)} order by session_id`, ); }, };