/** * SQL transparency. An agent that can read the SQL a query generates can fix a * slow or wrong read by itself; a query builder that hides its output forces it * to guess. `explainQuery` is the read path for `/_x` and for `x db explain`. */ import type { Ctx } from '@ultimat3/core'; import type { StandardSchemaV1 } from '@ultimat3/schema'; import type { AnyQuery, Query } from './query'; import { queryName, sourceFor } from './query'; import { listQueries } from './registry'; import type { QueryShape } from './shape'; import type { SqlText } from './source'; export interface ExplainResult extends SqlText { readonly query: string; readonly shape: QueryShape; readonly live: boolean; } /** * Policy is deliberately NOT enforced here: `explainQuery` never returns rows, and the * surfaces that expose it (`/_x`, the CLI) are admin-gated in their own right. */ export async function explainQuery( target: Query, input: unknown, ctx?: Ctx, ): Promise { const source = await sourceFor(target, input, { unenforced: 'explain returns the statement and never a row, and its surfaces are admin-gated', ...(ctx === undefined ? {} : { ctx }), }); const text = source.toSQL(); return { query: queryName(target), sql: text.sql, params: text.params, shape: source.shape(), live: target.isLive, }; } export interface QuerySqlInfo { readonly query: string; readonly live: boolean; /** `null` when no sample input was supplied — SQL depends on arguments. */ readonly sql: string | null; } /** * Dashboard listing. Pass sample inputs keyed by query name to get real SQL; * without one, the entry is listed with `sql: null` rather than a guess. */ export async function describeSql( samples: Readonly> = {}, queries: readonly AnyQuery[] = listQueries(), ctx?: Ctx, ): Promise { const entries: QuerySqlInfo[] = []; for (const target of queries) { const name = queryName(target); // `Object.hasOwn`, because `samples` is a caller's object literal and a name it never carried // — `constructor`, `toString` — would otherwise resolve to a FUNCTION and be parsed as input. const sample = Object.hasOwn(samples, name) ? samples[name] : undefined; // A download has no statement to render, sample or not: it answers a file. if (sample === undefined || target.download === true) { entries.push({ query: name, live: target.isLive, sql: null }); continue; } const source = await sourceFor(target, sample, { unenforced: 'the dashboard listing renders SQL text for a sample input and reads no rows', ...(ctx === undefined ? {} : { ctx }), }); entries.push({ query: name, live: target.isLive, sql: source.toSQL().sql }); } return entries; }