Skip to content

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

feat(studio): make the notebook wire schema the source of truth for query sources (#49069)

Charise126b683907e
diff --git a/apps/studio/data/content/notebooks/notebook-schema.test.ts b/apps/studio/data/content/notebooks/notebook-schema.test.ts
index c6fc30abbaa..2f1615ba0e8 100644
--- a/apps/studio/data/content/notebooks/notebook-schema.test.ts
+++ b/apps/studio/data/content/notebooks/notebook-schema.test.ts
@@ -3,8 +3,10 @@ import { describe, expect, it } from 'vitest'
import {
agentNotebookSchema,
+ isQueryCell,
notebookDomainSchema,
notebookSchema,
+ timeRangeSchema,
writableNotebookSchema,
} from './notebook-schema'
import { untrustedLogSql } from '@/data/logs/safe-analytics-sql'
@@ -114,6 +116,116 @@ describe('notebookSchema', () => {
expect(result.success).toBe(false)
})
+
+ it('accepts an optional database_identifier on a database_cell', () => {
+ const result = notebookSchema.safeParse({
+ schema_version: 1,
+ cells: [
+ {
+ _tag: 'database_cell',
+ id: '1',
+ sql: 'select 1',
+ row_limit: 100,
+ database_identifier: 'replica-1',
+ },
+ ],
+ })
+
+ expect(result.success).toBe(true)
+ })
+
+ it('keeps a chart configured while the table view is selected', () => {
+ const result = notebookSchema.safeParse({
+ schema_version: 1,
+ cells: [
+ {
+ _tag: 'database_cell',
+ id: '1',
+ sql: 'select 1',
+ row_limit: 100,
+ view: 'table',
+ chart: {
+ type: 'bar',
+ x_column: 'day',
+ y_columns: ['signups'],
+ cumulative: false,
+ show_labels: true,
+ },
+ },
+ ],
+ })
+
+ expect(result.success).toBe(true)
+ if (!result.success) return
+ expect(result.data.cells[0]).toMatchObject({ view: 'table', chart: { x_column: 'day' } })
+ })
+})
+
+describe('timeRangeSchema', () => {
+ const logCell = (time_range: unknown) => ({
+ schema_version: 1,
+ cells: [{ _tag: 'log_cell', id: '1', sql: 'select 1', time_range }],
+ })
+
+ it('rejects a relative_time_range with a non-positive or fractional amount', () => {
+ expect(
+ timeRangeSchema.safeParse({ _tag: 'relative_time_range', unit: 'hour', amount: 0 }).success
+ ).toBe(false)
+ expect(
+ timeRangeSchema.safeParse({ _tag: 'relative_time_range', unit: 'hour', amount: -1 }).success
+ ).toBe(false)
+ expect(
+ timeRangeSchema.safeParse({ _tag: 'relative_time_range', unit: 'hour', amount: 1.5 }).success
+ ).toBe(false)
+ })
+
+ it('accepts every relative unit the wire schema allows', () => {
+ for (const unit of ['minute', 'hour', 'day', 'week', 'month', 'year']) {
+ expect(
+ timeRangeSchema.safeParse({ _tag: 'relative_time_range', unit, amount: 2 }).success
+ ).toBe(true)
+ }
+ })
+
+ it('rejects an absolute_time_range that does not move forward in time', () => {
+ const equal = timeRangeSchema.safeParse({
+ _tag: 'absolute_time_range',
+ start: '2025-01-01T00:00:00.000Z',
+ end: '2025-01-01T00:00:00.000Z',
+ })
+ expect(equal.success).toBe(false)
+ expect(equal.error?.issues[0].path).toEqual(['end'])
+
+ expect(
+ timeRangeSchema.safeParse({
+ _tag: 'absolute_time_range',
+ start: '2025-01-02T00:00:00.000Z',
+ end: '2025-01-01T00:00:00.000Z',
+ }).success
+ ).toBe(false)
+
+ expect(
+ notebookSchema.safeParse(
+ logCell({
+ _tag: 'absolute_time_range',
+ start: '2025-01-02T00:00:00.000Z',
+ end: '2025-01-01T00:00:00.000Z',
+ })
+ ).success
+ ).toBe(false)
+ })
+
+ it('reports an invalid bound against its own field rather than the ordering rule', () => {
+ const result = timeRangeSchema.safeParse({
+ _tag: 'absolute_time_range',
+ start: 'not-a-date',
+ end: '2025-01-01T00:00:00.000Z',
+ })
+
+ expect(result.success).toBe(false)
+ expect(result.error?.issues).toHaveLength(1)
+ expect(result.error?.issues[0].path).toEqual(['start'])
+ })
})
describe('agentNotebookSchema', () => {
@@ -212,6 +324,20 @@ describe('writableNotebookSchema', () => {
})
})
+describe('isQueryCell', () => {
+ it('narrows every runnable cell and excludes content cells', () => {
+ const result = notebookDomainSchema.safeParse(FULL_NOTEBOOK)
+ expect(result.success).toBe(true)
+ if (!result.success) return
+
+ expect(result.data.cells.map(isQueryCell)).toEqual([false, true, true])
+ expect(result.data.cells.filter(isQueryCell).map((cell) => cell._tag)).toEqual([
+ 'database_cell',
+ 'log_cell',
+ ])
+ })
+})
+
describe('notebookDomainSchema', () => {
it('brands database_cell and log_cell sql as unchecked_sql, leaving markdown_cell untouched', () => {
const result = notebookDomainSchema.safeParse(FULL_NOTEBOOK)
diff --git a/apps/studio/data/content/notebooks/notebook-schema.ts b/apps/studio/data/content/notebooks/notebook-schema.ts
index c326011f3b7..6e563a6ae15 100644
--- a/apps/studio/data/content/notebooks/notebook-schema.ts
+++ b/apps/studio/data/content/notebooks/notebook-schema.ts
@@ -1,4 +1,5 @@
import { untrustedSql, type SafeSqlFragment } from '@supabase/pg-meta'
+import dayjs from 'dayjs'
import * as z from 'zod'
import { untrustedLogSql, type SafeLogSqlFragment } from '@/data/logs/safe-analytics-sql'
@@ -31,38 +32,76 @@ const absoluteTimeRangeSchema = z.object({
const relativeTimeRangeSchema = z.object({
_tag: z.literal('relative_time_range'),
unit: z.enum(['minute', 'hour', 'day', 'week', 'month', 'year']),
- amount: z.number(),
+ amount: z.number().int().positive(),
})
-const timeRangeSchema = z.discriminatedUnion('_tag', [
- absoluteTimeRangeSchema,
- relativeTimeRangeSchema,
-])
+export const timeRangeSchema = z
+ .discriminatedUnion('_tag', [absoluteTimeRangeSchema, relativeTimeRangeSchema])
+ .refine(
+ (range) => {
+ if (range._tag !== 'absolute_time_range') return true
+
+ const start = dayjs(range.start)
+ const end = dayjs(range.end)
+ // An unparseable bound is already reported against its own field; the ordering
+ // rule stays quiet so it doesn't add a second, misleading issue.
+ if (!start.isValid() || !end.isValid()) return true
+
+ return end.isAfter(start)
+ },
+ { message: 'must be later than the start of the range', path: ['end'] }
+ )
+
+// Source parameters — the per-backend values a query needs beyond its SQL. Declared
+// here, in the wire contract, because this schema is the shape shared with the API and
+// the agent tool surface, so it is where the validation has to be authoritative. The
+// runtime registry (data/query-sources/query-source-registry.ts) borrows these rather
+// than redeclaring them. Each is spread flat into its cell — no `source` wrapper — to
+// keep the JSON an agent has to author as shallow as possible.
+export const databaseSourceSchema = z.object({
+ /**
+ * Which database the query runs against: the read-replica `identifier`, or absent
+ * for the project's primary. Named `database_identifier` rather than `identifier`
+ * because every cell already carries an `id`.
+ */
+ database_identifier: z.string().optional(),
+})
-const markdownCellSchema = z.object({
- _tag: z.literal('markdown_cell'),
+export const logsSourceSchema = z.object({
+ time_range: timeRangeSchema,
+})
+
+const cellBaseSchema = z.object({
id: z.string(),
+})
+
+// Fields every runnable cell shares, regardless of backend. `sql` is deliberately NOT
+// here: it stays on each member so the domain transform can brand it per dialect and
+// generic code holding a `QueryCell` can't hand it to the wrong wire boundary.
+const queryCellBaseSchema = cellBaseSchema.extend({
+ title: z.string().optional(),
+ view: z.enum(['table', 'chart']).optional(),
+ // Persisted independently of `view` so a user who switches to the table and back
+ // gets their chart configuration returned rather than rebuilt.
+ chart: chartConfigSchema.optional(),
+})
+
+const markdownCellSchema = cellBaseSchema.extend({
+ _tag: z.literal('markdown_cell'),
text: z.string(),
})
-const databaseCellSchema = z.object({
+const databaseCellSchema = queryCellBaseSchema.extend({
_tag: z.literal('database_cell'),
- id: z.string(),
- title: z.string().optional(),
sql: z.string(),
row_limit: z.number(),
- view: z.enum(['table', 'chart']).optional(),
- chart: chartConfigSchema.optional(),
+ ...databaseSourceSchema.shape,
})
-const logCellSchema = z.object({
+const logCellSchema = queryCellBaseSchema.extend({
_tag: z.literal('log_cell'),
- id: z.string(),
- title: z.string().optional(),
sql: z.string(),
- time_range: timeRangeSchema,
- view: z.enum(['table', 'chart']).optional(),
- chart: chartConfigSchema.optional(),
+ ...logsSourceSchema.shape,
})
const cellSchema = z.discriminatedUnion('_tag', [
@@ -156,3 +195,33 @@ export type DatabaseCell = Extract<Cell, { _tag: 'database_cell' }>
export type LogCell = Extract<Cell, { _tag: 'log_cell' }>
export type TimeRange = z.infer<typeof timeRangeSchema>
export type ChartConfig = z.infer<typeof chartConfigSchema>
+export type DatabaseSourceParameters = z.infer<typeof databaseSourceSchema>
+export type LogsSourceParameters = z.infer<typeof logsSourceSchema>
+
+type CellKind = 'content' | 'query'
+
+/**
+ * Classifies every cell tag as content or query. The `satisfies` clause makes this the
+ * registration point for a new backend: adding a member to `cellSchema` fails to compile
+ * here until it is classified, and `QueryCell` / `isQueryCell` widen automatically once
+ * it is — so a new cell type can never be silently left out of query-generic UI.
+ */
+const CELL_KINDS = {
+ markdown_cell: 'content',
+ database_cell: 'query',
+ log_cell: 'query',
+} as const satisfies Record<Cell['_tag'], CellKind>
+
+type QueryCellTag = {
+ [K in keyof typeof CELL_KINDS]: (typeof CELL_KINDS)[K] extends 'query' ? K : never
+}[keyof typeof CELL_KINDS]
+
+export type QueryCell = Extract<Cell, { _tag: QueryCellTag }>
+
+/**
+ * Narrows any cell-shaped value to its query members. Generic over the input so it works
+ * on domain cells and on the deep-readonly `Snapshot<Cell>` values valtio hands the UI.
+ */
+export const isQueryCell = <C extends { _tag: Cell['_tag'] }>(
+ cell: C
+): cell is Extract<C, { _tag: QueryCellTag }> => CELL_KINDS[cell._tag] === 'query'