Files
supabase/apps/studio/components/interfaces/SQLEditor/querySource.ts
Charis 4c8ed105d2 feat(studio): logs SQL execution wiring + source-aware run gestures (#48414)
## I have read the
[CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md)
file.

YES

## What kind of change does this PR introduce?

Feature (SQL editor: execution wiring for logs-source snippets). Part of
the stacked SQL-editor "Database vs Logs" query-source series.

## What is the current behavior?

The SQL editor only ever runs queries against the user's Postgres
database. There is no execution path for a logs (`log_sql`) snippet, and
the run-button telemetry event carries no backend discriminator.

## What is the new behavior?

- `useRunSource(id)` derives the run backend from the snippet type; a
`log_sql` snippet resolves to `{ type: 'logs', dateRange }`, pairing the
run with its session time range (default: last hour).
- `useLogsSqlExecution` runs a promoted `SafeLogSqlFragment` against the
analytics OTEL (ClickHouse) endpoint with the resolved time range as
`iso_timestamp_start`/`iso_timestamp_end` request params. The endpoint
is **pinned to OTEL** — a snippet's dialect must not flip with org
migration.
- The run gestures (toolbar button and Cmd+Enter) branch on the source
and promote with the matching `acceptUntrusted*` right at the user
action, preserving the auditable promotion-at-gesture boundary. pg
intellisense is gated off for logs snippets.
- The `sql_editor_query_run_button_clicked` telemetry event gains a
required `{ source: 'database' | 'logs' }` property, fired from both
execution paths.
- Capability guard: a `log_sql` snippet is reachable by direct URL
regardless of the (later) entry-point flag gating, so `executeLogsQuery`
short-circuits when `otelLegacyLogs` is off — recording a clear "not
available yet" result message instead of firing a request that would
only return an opaque backend error on a non-ClickHouse project. This is
a guard on the gesture, not endpoint selection.
- Tests: `useRunSource` routing, `useLogsSqlExecution`
endpoint/range/structured-error/capability-guard, and a reusable `flags`
option on `renderSqlEditorHook`.

No UI entry points are added — the feature runs dark until the
flag-gated creation/nav PRs later in the stack.

## Additional context

Stacked on the query-source series; base branch is `master` now that PR
4 (log date range domain + session state, #48401) is merged. Follow-ups
in the stack add the toolbar/creation UI (with a run-affordance gate on
`otelLegacyLogs`), nav section, AI dialect support, and reports guard.

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

* **New Features**
  * Added support for running log queries directly from the SQL editor.
* Log query results, errors, and time ranges are now handled within the
editor session.
* Added automatic selection between database and log query execution,
including support for custom date ranges.
* SQL assistance is disabled while editing log queries where database
definitions do not apply.

* **Tests**
* Added coverage for log query execution, date ranges, feature
availability, and execution source selection.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-07-29 10:43:48 -04:00

153 lines
6.5 KiB
TypeScript

import dayjs from 'dayjs'
import { generateDynamicHelper } from '@/components/interfaces/Settings/Logs/Logs.datePickerHelpers'
import type { Unit } from '@/components/interfaces/Settings/Logs/Logs.datePickerHelpers'
import type { DatePickerValue } from '@/components/interfaces/Settings/Logs/Logs.DatePickers'
import type { ResolvedLogDateRange } from '@/components/interfaces/Settings/Logs/logsDateRange'
import type { Snippet } from '@/data/content/sql-folders-query'
/**
* Domain view of where a snippet's query runs. Derived from the content TYPE:
* a `log_sql` snippet always targets the logs backend and a `sql` (or `report`)
* snippet always targets the user's Postgres database. A snippet's source is
* immutable — switching backends means creating a new snippet, not toggling this
* value.
*/
export type SqlSnippetSource = 'database' | 'logs'
/**
* The single reader every surface (AI, reports, tabs, nav, execution) uses to
* decide where a snippet runs. `'log_sql'` → `'logs'`; everything else (`'sql'`,
* `'report'`) → `'database'`. Accepts the raw `Snippet['type']` so a snippet of
* any content type maps to a source without narrowing first.
*/
export function getSnippetSource(snippet: Pick<Snippet, 'type'>): SqlSnippetSource {
return snippet.type === 'log_sql' ? 'logs' : 'database'
}
/**
* An ISO-8601 datetime proven valid at construction via a dayjs parse. Absolute
* log ranges carry these instead of raw strings so an unvalidated datetime can
* never reach execution.
*/
export type IsoDateTimeString = string & { readonly __isoDateTimeBrand: unique symbol }
/**
* Validate a raw string as an ISO datetime, returning the branded value or null.
* The sole construction site for `IsoDateTimeString` outside `now`.
*/
export function isoDateTimeString(raw: string): IsoDateTimeString | null {
if (!raw) return null
return dayjs(raw).isValid() ? (raw as IsoDateTimeString) : null
}
/** `now` as a branded ISO datetime — `toISOString()` is always valid ISO-8601. */
function nowIsoDateTime(): IsoDateTimeString {
return dayjs().toISOString() as IsoDateTimeString
}
/**
* The units a relative log range is expressed in. Aliases the Logs date picker's
* `Unit` so the two stay in lockstep rather than drifting as parallel unions.
*/
export type RelativeTimeUnit = Unit
/**
* A log query's time range. Relative ranges are structural (amount + unit) and
* re-resolve against `now` at every run — so a saved "last hour" always means the
* hour before the run, not the hour before the snippet was opened. Absolute ranges
* carry validated ISO datetimes and pass through unchanged.
*/
export type LogDateRange =
| { kind: 'relative'; last: { amount: number; unit: RelativeTimeUnit } }
| { kind: 'absolute'; from: IsoDateTimeString; to: IsoDateTimeString }
/** The range a freshly opened logs snippet starts with: the last hour. */
export const DEFAULT_LOG_DATE_RANGE: LogDateRange = {
kind: 'relative',
last: { amount: 1, unit: 'hour' },
}
/**
* The runtime query source for a snippet, pairing the database/logs discriminant
* with the extra state each backend needs to run. A logs run carries the active
* time range (session state, re-resolved at every run); a database run needs
* nothing beyond the connection the execution pipeline already resolves.
*/
export type QuerySource = { type: 'database' } | { type: 'logs'; dateRange: LogDateRange }
/**
* Parse a date-picker helper's label (e.g. "Last hour", "Last 3 hours", "Last 30
* minutes") into a relative amount/unit. Covers both the static presets in
* `EXPLORER_DATEPICKER_HELPERS` and the dynamic helpers `generateHelpersFromInput`
* produces from typed input like "2h"/"30m". A label with no number means one unit
* ("Last hour"). Returns null for any other label.
*/
function parseRelativeHelperLabel(
text: string | undefined
): { amount: number; unit: RelativeTimeUnit } | null {
if (!text) return null
const match = text
.trim()
.toLowerCase()
.match(/^last\s+(?:(\d+)\s+)?(minute|hour|day)s?$/)
if (!match) return null
const amount = match[1] ? parseInt(match[1], 10) : 1
if (!Number.isFinite(amount) || amount <= 0) return null
const unit = match[2]
if (unit !== 'minute' && unit !== 'hour' && unit !== 'day') return null
return { amount, unit }
}
/**
* Convert a Logs date-picker value into a `LogDateRange`. Helper picks (presets and
* dynamic "2h"/"30m" helpers) become relative ranges by parsing the helper label;
* a preset's `calcTo()` resolves to `''` (meaning "now"), which the relative variant
* models implicitly. Everything else — custom calendar picks, or a helper whose label
* we can't parse — becomes an absolute range with validated ISO datetimes, degrading
* via `from`/now rather than rejecting an empty string. A value with no usable `from`
* falls back to the default range.
*/
export function datePickerValueToLogDateRange(value: DatePickerValue): LogDateRange {
if (value.isHelper) {
const relative = parseRelativeHelperLabel(value.text)
if (relative) return { kind: 'relative', last: relative }
}
const from = isoDateTimeString(value.from)
if (from === null) return DEFAULT_LOG_DATE_RANGE
const to = isoDateTimeString(value.to) ?? nowIsoDateTime()
return { kind: 'absolute', from, to }
}
/**
* Render a `LogDateRange` back into a Logs date-picker value for display. Relative
* ranges reuse the picker's own `generateDynamicHelper` to derive the resolved
* `from`/`to` and matching "Last N unit(s)" label, so the value is byte-for-byte
* what the picker itself would emit for that helper. Absolute ranges pass their
* datetimes through.
*/
export function logDateRangeToDatePickerValue(range: LogDateRange): DatePickerValue {
if (range.kind === 'relative') {
const helper = generateDynamicHelper(range.last.amount, range.last.unit)
return { from: helper.calcFrom(), to: helper.calcTo(), isHelper: true, text: helper.text }
}
return { from: range.from, to: range.to, isHelper: false }
}
/**
* Resolve a `LogDateRange` to concrete ISO endpoints for a run. Relative ranges
* re-resolve against `now` (so "last hour" is always the hour before the run);
* absolute ranges pass through. Reuses the Logs `ResolvedLogDateRange` shape.
*/
export function resolveLogRunRange(range: LogDateRange): ResolvedLogDateRange {
if (range.kind === 'relative') {
const now = dayjs()
return {
from: now.subtract(range.last.amount, range.last.unit).toISOString(),
to: now.toISOString(),
}
}
return { from: range.from, to: range.to }
}