Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

feat(studio): logs SQL brands + execution data layer (#48301)

Charisec1c8893491b
diff --git a/apps/studio/data/logs/execute-logs-sql-mutation.test.ts b/apps/studio/data/logs/execute-logs-sql-mutation.test.ts
new file mode 100644
index 00000000000..6505ba9781e
--- /dev/null
+++ b/apps/studio/data/logs/execute-logs-sql-mutation.test.ts
@@ -0,0 +1,57 @@
+import { describe, expect, it } from 'vitest'
+
+import { mapLogsError } from './execute-logs-sql-mutation'
+
+describe('mapLogsError', () => {
+ it('returns undefined when there is no error', () => {
+ expect(mapLogsError(undefined)).toBeUndefined()
+ expect(mapLogsError(null)).toBeUndefined()
+ })
+
+ it('extracts the top-level message from the structured backend error body', () => {
+ const structured = {
+ code: 400,
+ errors: [{ domain: 'global', message: 'nested detail', reason: 'invalidQuery' }],
+ message: 'Syntax error near LIMIT',
+ status: 'INVALID_ARGUMENT',
+ }
+ expect(mapLogsError(structured)).toEqual({ message: 'Syntax error near LIMIT' })
+ })
+
+ it('falls back to the first nested errors[].message when top-level message is missing', () => {
+ const structured = {
+ code: 400,
+ errors: [
+ { domain: 'global', message: '', reason: 'invalidQuery' },
+ { domain: 'global', message: 'first usable detail', reason: 'invalidQuery' },
+ ],
+ status: 'INVALID_ARGUMENT',
+ }
+ expect(mapLogsError(structured)).toEqual({ message: 'first usable detail' })
+ })
+
+ it('does not throw and falls back when errors is a malformed non-array value', () => {
+ expect(mapLogsError({ code: 400, errors: {}, status: 'INVALID_ARGUMENT' })).toEqual({
+ message: 'An unexpected error occurred while running the logs query.',
+ })
+ expect(mapLogsError({ message: 'top-level wins', errors: 'nope' })).toEqual({
+ message: 'top-level wins',
+ })
+ })
+
+ it('normalizes a plain string error', () => {
+ expect(mapLogsError('boom')).toEqual({ message: 'boom' })
+ })
+
+ it('returns a generic fallback when an error is present but carries no usable text', () => {
+ expect(mapLogsError({ code: 500, errors: [], status: 'INTERNAL' })).toEqual({
+ message: 'An unexpected error occurred while running the logs query.',
+ })
+ expect(mapLogsError('')).toEqual({
+ message: 'An unexpected error occurred while running the logs query.',
+ })
+ expect(mapLogsError({ message: '' })).toEqual({
+ message: 'An unexpected error occurred while running the logs query.',
+ })
+ })
+})
diff --git a/apps/studio/data/logs/execute-logs-sql-mutation.ts b/apps/studio/data/logs/execute-logs-sql-mutation.ts
new file mode 100644
index 00000000000..cb241ea64df
--- /dev/null
+++ b/apps/studio/data/logs/execute-logs-sql-mutation.ts
@@ -0,0 +1,176 @@
+/**
+ * Execution data layer for user-authored logs SQL run from the SQL editor.
+ *
+ * This is the logs-path analog of `data/sql/execute-sql-mutation.ts`. It wraps
+ * the analytics wire boundary (`executeAnalyticsSql`) and:
+ * - accepts only a `SafeLogSqlFragment` (promoted from `UntrustedLogSqlFragment`
+ * at an explicit user run gesture — see `safe-analytics-sql.ts`),
+ * - attaches the resolved time range as request params
+ * (`iso_timestamp_start`/`iso_timestamp_end`), never spliced into the SQL,
+ * - normalizes the response to `{ rows, error? }`.
+ *
+ * There are two ways a logs query can fail, and the layer keeps them distinct
+ * only at the pure-function level:
+ * - Transport failures (non-2xx) throw out of `executeAnalyticsSql` via
+ * `handleError`.
+ * - The analytics backend also returns a *200 body* carrying a structured error
+ * (`{ code, errors, message, status }`) — the same shape `useLogsQuery`
+ * reads. `mapLogsError` normalizes that into the `{ message }` shape the SQL
+ * editor's result pane renders, returned in `executeLogsSql`'s `error` field.
+ *
+ * `useExecuteLogsSqlMutation` then collapses both into React Query's single
+ * `onError` path so consumers handle one normalized error shape in one place.
+ */
+import { useMutation } from '@tanstack/react-query'
+import { toast } from 'sonner'
+
+import { executeAnalyticsSql, type AnalyticsSqlEndpoint } from './execute-analytics-sql'
+import type { SafeLogSqlFragment } from './safe-analytics-sql'
+import type { ResolvedLogDateRange } from '@/components/interfaces/Settings/Logs/logsDateRange'
+import type { UseCustomMutationOptions } from '@/types'
+
+/**
+ * Normalized logs query error in the shape the SQL editor result pane reads
+ * (`{ message }`). Produced by `mapLogsError` from either a transport error or
+ * the analytics backend's structured 200-body error.
+ */
+export interface LogsQueryError {
+ message: string
+}
+
+/**
+ * Structured error the analytics backend returns inside a 200 response body.
+ * Mirrors `LFResponse['error']` from the Logs types; every field is optional
+ * here because the value crosses the wire and must be treated defensively.
+ */
+interface RawLogsResponseError {
+ code?: number
+ errors?: Array<{ domain?: string; message?: string; reason?: string }>
+ message?: string
+ status?: string
+}
+
+const UNKNOWN_LOGS_ERROR_MESSAGE = 'An unexpected error occurred while running the logs query.'
+
+/**
+ * Normalizes an analytics backend error into the `{ message }` shape the SQL
+ * editor result pane renders. Follows `useLogsQuery`'s extraction: prefer the
+ * top-level `message`, then the first nested `errors[].message`. Returns
+ * `undefined` when there is no error, and a generic fallback message when an
+ * error is present but carries no usable text.
+ */
+export function mapLogsError(error: unknown): LogsQueryError | undefined {
+ if (error === undefined || error === null) return undefined
+
+ if (typeof error === 'string') {
+ return { message: error.length > 0 ? error : UNKNOWN_LOGS_ERROR_MESSAGE }
+ }
+
+ if (typeof error === 'object') {
+ const structured = error as RawLogsResponseError
+ const nestedMessage = Array.isArray(structured.errors)
+ ? structured.errors.find(
+ (entry) => typeof entry?.message === 'string' && entry.message.length > 0
+ )?.message
+ : undefined
+ const message = structured.message || nestedMessage
+ if (typeof message === 'string' && message.length > 0) {
+ return { message }
+ }
+ }
+
+ return { message: UNKNOWN_LOGS_ERROR_MESSAGE }
+}
+
+export interface ExecuteLogsSqlVariables {
+ projectRef: string
+ /** Must carry the `SafeLogSqlFragment` brand — promote at the run gesture. */
+ sql: SafeLogSqlFragment
+ /** Resolved (absolute) time range; relative ranges re-resolve at each run. */
+ range: ResolvedLogDateRange
+ /**
+ * Analytics endpoint to run against. The SQL editor pins this to the OTEL
+ * (ClickHouse) endpoint; kept as a param so callers stay explicit.
+ */
+ endpoint: AnalyticsSqlEndpoint
+ signal?: AbortSignal
+}
+
+export interface ExecuteLogsSqlResult {
+ rows: unknown[]
+ /** Present when the backend returned a 200 body carrying a structured error. */
+ error?: LogsQueryError
+}
+
+/**
+ * Runs a logs SQL query against the analytics backend and normalizes the
+ * response. Transport failures throw; a structured 200-body error is returned
+ * in `error` alongside empty `rows`.
+ *
+ * @throws {ResponseError} on transport failure (via `executeAnalyticsSql`).
+ */
+export async function executeLogsSql({
+ projectRef,
+ sql,
+ range,
+ endpoint,
+ signal,
+}: ExecuteLogsSqlVariables): Promise<ExecuteLogsSqlResult> {
+ const data = await executeAnalyticsSql({
+ projectRef,
+ endpoint,
+ sql,
+ iso_timestamp_start: range.from,
+ iso_timestamp_end: range.to,
+ key: 'sql-editor',
+ signal,
+ })
+
+ const body = (data ?? {}) as { result?: unknown[]; error?: unknown }
+ const error = mapLogsError(body.error)
+
+ return { rows: body.result ?? [], ...(error ? { error } : {}) }
+}
+
+/**
+ * React Query mutation wrapping `executeLogsSql`.
+ *
+ * Collapses both failure modes into React Query's single `onError` path: a
+ * transport failure (thrown by `executeAnalyticsSql`) and the analytics
+ * backend's structured 200-body error are both normalized to `LogsQueryError`
+ * before they reach `onError`, so callers only ever handle one error shape in
+ * one place. `onSuccess` therefore always receives a genuinely successful
+ * result.
+ */
+export const useExecuteLogsSqlMutation = ({
+ onSuccess,
+ onError,
+ ...options
+}: Omit<
+ UseCustomMutationOptions<ExecuteLogsSqlResult, LogsQueryError, ExecuteLogsSqlVariables>,
+ 'mutationFn'
+> = {}) => {
+ return useMutation<ExecuteLogsSqlResult, LogsQueryError, ExecuteLogsSqlVariables>({
+ async mutationFn(variables) {
+ let result: ExecuteLogsSqlResult
+ try {
+ result = await executeLogsSql(variables)
+ } catch (error) {
+ // Transport failure — normalize to the same shape as a query error.
+ throw mapLogsError(error) ?? { message: UNKNOWN_LOGS_ERROR_MESSAGE }
+ }
+ // 200-body query error — route through onError alongside transport errors.
+ if (result.error) throw result.error
+ return result
+ },
+ onSuccess,
+ async onError(error, variables, context) {
+ if (onError === undefined) {
+ toast.error(error.message)
+ } else {
+ onError(error, variables, context)
+ }
+ },
+ ...options,
+ })
+}
diff --git a/apps/studio/data/logs/safe-analytics-sql.test.ts b/apps/studio/data/logs/safe-analytics-sql.test.ts
index 376d721e03d..dd6a92fcb92 100644
--- a/apps/studio/data/logs/safe-analytics-sql.test.ts
+++ b/apps/studio/data/logs/safe-analytics-sql.test.ts
@@ -1,7 +1,19 @@
+import {
+ acceptUntrustedSql as pgAcceptUntrustedSql,
+ safeSql as pgSafeSql,
+ untrustedSql as pgUntrustedSql,
+} from '@supabase/pg-meta'
import { describe, expect, it } from 'vitest'
import { executeAnalyticsSql } from './execute-analytics-sql'
-import { analyticsLiteral, keyword, quotedIdent, safeSql } from './safe-analytics-sql'
+import {
+ acceptUntrustedLogsSql,
+ analyticsLiteral,
+ keyword,
+ quotedIdent,
+ safeSql,
+ untrustedLogSql,
+} from './safe-analytics-sql'
describe('keyword', () => {
it('returns the matching SafeLogSqlFragment from the allow-list', () => {
@@ -101,6 +113,44 @@ describe('executeAnalyticsSql — compile-time boundary', () => {
})
})
+describe('untrusted logs SQL brands', () => {
+ it('untrustedLogSql preserves the raw text', () => {
+ expect(untrustedLogSql('SELECT 1 FROM logs')).toBe('SELECT 1 FROM logs')
+ })
+
+ it('acceptUntrustedLogsSql promotes untrusted text to a runnable fragment unchanged', () => {
+ const untrusted = untrustedLogSql('SELECT 1 FROM logs')
+ const safe = acceptUntrustedLogsSql(untrusted)
+ expect(safe).toBe('SELECT 1 FROM logs')
+ })
+
+ it('a promoted logs fragment composes via safeSql', () => {
+ const safe = acceptUntrustedLogsSql(untrustedLogSql('SELECT 1'))
+ expect(safeSql`${safe}`).toBe('SELECT 1')
+ })
+
+ it('rejects an unbranded string at the acceptUntrustedLogsSql boundary', () => {
+ const plain: string = 'SELECT 1'
+ // @ts-expect-error — only UntrustedLogSqlFragment may be promoted
+ const _check = () => acceptUntrustedLogsSql(plain)
+ expect(_check).toBeDefined()
+ })
+
+ it('rejects Postgres-branded fragments at the logs boundary (brands are disjoint)', () => {
+ // The logs boundary must not accept Postgres SQL, whether it is still untrusted or
+ // already promoted.
+ const pgUntrusted = pgUntrustedSql('SELECT 1')
+ const pgSafe = pgAcceptUntrustedSql(pgSafeSql`SELECT 1`)
+ const _check = () => [
+ // @ts-expect-error — pg untrusted brand is not assignable to UntrustedLogSqlFragment
+ acceptUntrustedLogsSql(pgUntrusted),
+ // @ts-expect-error — pg safe brand is not assignable to UntrustedLogSqlFragment
+ acceptUntrustedLogsSql(pgSafe),
+ ]
+ expect(_check).toBeDefined()
+ })
+})
+
describe('safeSql template tag — existing helpers still compose', () => {
it('analyticsLiteral output is composable via safeSql', () => {
const val = analyticsLiteral('hello')
diff --git a/apps/studio/data/logs/safe-analytics-sql.ts b/apps/studio/data/logs/safe-analytics-sql.ts
index 7f2b24787f2..e8f401b774f 100644
--- a/apps/studio/data/logs/safe-analytics-sql.ts
+++ b/apps/studio/data/logs/safe-analytics-sql.ts
@@ -51,6 +51,41 @@
*/
export type SafeLogSqlFragment = string & { readonly __safeLogSqlFragmentBrand: never }
+/**
+ * User-authored logs SQL that has NOT yet been promoted to a runnable
+ * `SafeLogSqlFragment`. Mirrors pg-meta's `UntrustedSqlFragment`, but is an
+ * intentionally distinct brand so that Postgres SQL and logs SQL can never
+ * cross paths: neither can be promoted through the other's boundary, and
+ * neither can be composed into the other's queries.
+ *
+ * Safe to display and to store as the editor's working text; must never be
+ * executed without an explicit user run gesture. Promote via
+ * `acceptUntrustedLogsSql` — only inside a user-action event handler.
+ */
+export type UntrustedLogSqlFragment = string & { readonly __untrustedLogSqlBrand: never }
+
+/**
+ * Marks a raw string as user-authored logs SQL awaiting an explicit run
+ * gesture. Use at the editor boundary where the user's logs SQL text enters
+ * the type system; the value stays untrusted until `acceptUntrustedLogsSql`
+ * promotes it.
+ */
+export function untrustedLogSql(sql: string): UntrustedLogSqlFragment {
+ return sql as UntrustedLogSqlFragment
+}
+
+/**
+ * SECURITY BOUNDARY — promotes user-authored logs SQL to a runnable
+ * `SafeLogSqlFragment`.
+ *
+ * ONLY call from an event handler tied to a deliberate user action (Run button
+ * onClick, Cmd+Enter keydown). Never call from render, useEffect, or any path
+ * that runs without a user gesture.
+ */
+export function acceptUntrustedLogsSql(sql: UntrustedLogSqlFragment): SafeLogSqlFragment {
+ return sql as unknown as SafeLogSqlFragment
+}
+
type LogSqlFragmentSeparator =
| ','
| ', '