Files
supabase/apps/studio/data/content/notebooks/notebook-upsert-mutation.test.ts
Charis 1296a1c745 feat(studio): notebook query and mutation hooks (#48907)
## Summary

Implements the "notebook query and mutation hooks" step of the notebooks
data layer:

- `data/content/notebooks/notebook-query.ts` —
`getNotebook`/`useNotebookQuery`, wrapping the existing `getContentById`
and narrowing to `type: 'notebook'`.
- `data/content/notebooks/notebooks-infinite-query.ts` —
`useNotebooksInfiniteQuery`, a typed wrapper over
`useContentInfiniteQuery` narrowing pages to notebook rows.
- `data/content/notebooks/notebook-upsert-mutation.ts` —
`createNotebook`/`updateNotebook` + their mutation hooks, PUTting
through the existing `upsertContent`.

Write-path correctness, worked out while building the mutation hooks:

- Cell `id`s are always backend-generated, never client-supplied — a
brand-new cell has no `id` at all; an existing cell being kept/edited in
an update keeps its real id so the backend can diff it against the
previous version. `notebook-schema.ts` gains
`writableCellSchema`/`writableNotebookSchema` (ids optional per cell)
and `WritableCell`/`WritableNotebook` types, derived from `z.infer` of
those schemas rather than hand-duplicated, with only the `sql` field
re-branded per cell type via a small distributive conditional type.
- Cell SQL at this write boundary must already be
`SafeSqlFragment`/`SafeLogSqlFragment` (proven user-authored at a
save/run event handler), not `unchecked_sql` — matching the
`safe-sql-execution` skill's provenance model.
- `content-remap.ts`'s notebook `unmapSqlContentField` branch is
simplified to a passthrough: notebook writes only ever arrive already
wire-shaped via `createNotebook`/`updateNotebook`, so there's nothing
left to unmap.

Note: this was originally stacked on
`feature/notebooks-types-convergence`, but that branch merged into
`master` (#48905) while this PR was in progress, so it's rebased
directly onto `master` now.

## Test plan

- [x] `pnpm --filter studio run typecheck` passes
- [x] `pnpm --filter studio exec vitest run data/content/notebooks
data/content/content-remap.test.ts` — 38/38 passing
- [x] `pnpm --filter studio exec eslint` clean on all touched files

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

## Summary by CodeRabbit

* **New Features**
* Added notebook listing with pagination, filtering, sorting, and
project-specific queries.
  * Added notebook retrieval for viewing individual notebooks.
  * Added notebook creation and editing with automatic content refresh.
* Added support for preserving cell IDs and safely handling SQL content.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-08-10 15:32:46 -04:00

145 lines
4.8 KiB
TypeScript

import { safeSql } from '@supabase/pg-meta'
import { HttpResponse } from 'msw'
import { describe, expect, it } from 'vitest'
import type { WritableNotebook } from './notebook-schema'
import { createNotebook, updateNotebook } from './notebook-upsert-mutation'
import { safeSql as safeLogSql } from '@/data/logs/safe-analytics-sql'
import { addAPIMock } from '@/tests/lib/msw'
const DATABASE_SQL = safeSql`select * from auth.users limit 100`
const LOG_SQL = "select timestamp, event_message from edge_logs where source = 'edge_logs' limit 10"
const EXISTING_CELL_ID = 'b1ffcd88-8d1a-4de7-aa5c-5aa8ac270b22'
// Create-shaped: no cell carries an `id` — the notebook is brand new, so no cell has a
// prior version for the backend to diff against; ids are backend-generated on write.
const VALID_CONTENT: WritableNotebook = {
schema_version: 1,
cells: [
{ _tag: 'markdown_cell', text: '# Signup funnel' },
{ _tag: 'database_cell', sql: DATABASE_SQL, row_limit: 100 },
{
_tag: 'log_cell',
sql: safeLogSql`select timestamp, event_message from edge_logs where source = 'edge_logs' limit 10`,
time_range: { _tag: 'relative_time_range', unit: 'hour', amount: 1 },
},
],
}
// Update-shaped: mixes an existing cell (kept, carries its real backend-assigned id so the
// backend can diff it against the previous version) with a newly inserted cell (no id —
// same as create, the backend assigns one on write).
const UPDATE_CONTENT: WritableNotebook = {
schema_version: 1,
cells: [
{
_tag: 'database_cell',
id: EXISTING_CELL_ID,
sql: DATABASE_SQL,
row_limit: 100,
},
{
_tag: 'log_cell',
sql: safeLogSql`select timestamp, event_message from edge_logs where source = 'edge_logs' limit 10`,
time_range: { _tag: 'relative_time_range', unit: 'hour', amount: 1 },
},
],
}
// Missing `row_limit` on the database_cell — invalid per writableNotebookSchema. The
// point of this fixture is to prove validation runs (and rejects) before any request is
// sent, so it's cast rather than satisfying the real type.
const INVALID_CONTENT = {
schema_version: 1,
cells: [
{
_tag: 'database_cell',
sql: safeSql`select 1`,
},
],
} as unknown as WritableNotebook
describe('createNotebook', () => {
it('PUTs with type notebook, visibility project, a freshly generated id, and cells with no id', async () => {
let sentBody: Record<string, unknown> | undefined
addAPIMock({
method: 'put',
path: '/platform/projects/:ref/content',
response: async ({ request }) => {
sentBody = (await request.json()) as Record<string, unknown>
return HttpResponse.json(null)
},
})
await createNotebook({
projectRef: 'default',
name: 'Signup funnel',
content: VALID_CONTENT,
})
expect(sentBody?.type).toBe('notebook')
expect(sentBody?.visibility).toBe('project')
expect(typeof sentBody?.id).toBe('string')
const content = sentBody?.content as WritableNotebook
for (const cell of content.cells) {
expect(cell).not.toHaveProperty('id')
}
const [, databaseCell, logCell] = content.cells as Array<Record<string, unknown>>
expect(databaseCell.sql).toBe(DATABASE_SQL)
expect(logCell.sql).toBe(LOG_SQL)
})
it('rejects malformed content without making a network request', async () => {
await expect(
createNotebook({ projectRef: 'default', name: 'Bad notebook', content: INVALID_CONTENT })
).rejects.toThrow()
})
})
describe('updateNotebook', () => {
const NOTEBOOK_ID = 'd3aadd77-7c3c-4de7-aa5c-5aa8ac270b44'
it('PUTs with the given id, keeping the existing cell id and leaving the new cell without one', async () => {
let sentBody: Record<string, unknown> | undefined
addAPIMock({
method: 'put',
path: '/platform/projects/:ref/content',
response: async ({ request }) => {
sentBody = (await request.json()) as Record<string, unknown>
return HttpResponse.json(null)
},
})
await updateNotebook({
projectRef: 'default',
id: NOTEBOOK_ID,
name: 'Signup funnel',
content: UPDATE_CONTENT,
})
expect(sentBody?.id).toBe(NOTEBOOK_ID)
expect(sentBody?.type).toBe('notebook')
const content = sentBody?.content as WritableNotebook
const [databaseCell, logCell] = content.cells as Array<Record<string, unknown>>
expect(databaseCell.id).toBe(EXISTING_CELL_ID)
expect(databaseCell.sql).toBe(DATABASE_SQL)
expect(logCell).not.toHaveProperty('id')
expect(logCell.sql).toBe(LOG_SQL)
})
it('rejects malformed content without making a network request', async () => {
await expect(
updateNotebook({
projectRef: 'default',
id: NOTEBOOK_ID,
name: 'Bad notebook',
content: INVALID_CONTENT,
})
).rejects.toThrow()
})
})