mirror of
https://github.com/supabase/supabase.git
synced 2026-10-08 19:05:06 +03:00
Third of a stack. **Stacked on #49070** (which is stacked on #49069) — review those first. Base retargets automatically as each merges. Mechanical throughout; no behavior change. ## The problem Three types described where a query runs, and no two agreed: | | shape | |---|---| | `CellSource` (registry) | `{ id, type, parameters: { … } }` — `id` and `type` always held the same literal | | `QuerySource` (SQL editor) | `{ type: 'database' } \| { type: 'logs', dateRange }` | | notebook cells | flat per-backend fields, neither of the above | Anything crossing between them needed a translation that dropped fields on the way — which is how a notebook cell's replica selection had nowhere to go. ## What changed One `QuerySourceBinding`: a backend `_tag` with that backend's parameters spread flat beside it, borrowed from the wire schema (#49069) so the binding and the persisted cell agree by construction. - **`QuerySource` is deleted.** `useRunSource` returns the shared binding, so `runSource.type`/`dateRange` become `_tag`/`time_range` across the SQL editor — that is most of the file count here. - **`getQuerySourceBinding`** projects a notebook cell onto a binding; **`toQuerySourceBinding`** does the same for any backend-tagged carrier. Both overloaded so an already-narrowed caller gets the matching binding back rather than the union, which keeps the result spreadable without re-narrowing. - **`ExplorerQuerySourceMenu`** drops its inline copy of the custom-range and upgrade-prompt logic in favor of `useLogsCustomRange`, which the SQL editor menu already used. The registry keeps only what is genuinely runtime: endpoints, labels, icons, availability, defaults. What a query *is* stays in the wire schema. ## Verification Typecheck, Prettier, and the lint ratchet clean. 405 tests pass across the notebook schema, query sources, the logs components, the SQL editor, and the Explorer surfaces. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Improvements** * Updated query source handling across Explorer and SQL Editor for a more consistent selection experience. * Database and log sources now preserve identifiers and time ranges more reliably when switching or editing queries. * Source menus, labels, icons, validation, and query execution now reflect the selected source more accurately. * **Bug Fixes** * Invalid or outdated saved source settings now safely fall back to a database source. * Improved log-source detection and time-range handling throughout query editing and execution. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Joshen Lim <joshenlimek@gmail.com>
172 lines
5.6 KiB
TypeScript
172 lines
5.6 KiB
TypeScript
import { act, screen, waitFor } from '@testing-library/react'
|
|
import userEvent from '@testing-library/user-event'
|
|
import { HttpResponse } from 'msw'
|
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
|
|
|
import { QueryTab } from './QueryTab'
|
|
import type { ReadReplicasData } from '@/data/read-replicas/replicas-query'
|
|
import { explorerQueryState } from '@/state/explorer-query'
|
|
import { createTabsState, TabsStateContext } from '@/state/tabs'
|
|
import { customRender } from '@/tests/lib/custom-render'
|
|
import { addAPIMock } from '@/tests/lib/msw'
|
|
import { setupSqlEditorMocks } from '@/tests/lib/sql-editor-test-utils'
|
|
|
|
const testContext = vi.hoisted(() => ({
|
|
flags: { otelLegacyLogs: true } as Record<string, boolean>,
|
|
params: { ref: 'default', id: 'query-test' } as { ref?: string; id?: string },
|
|
}))
|
|
|
|
vi.mock('common', async (importOriginal) => {
|
|
const actual = await importOriginal<typeof import('common')>()
|
|
return {
|
|
...actual,
|
|
IS_PLATFORM: true,
|
|
useParams: () => testContext.params,
|
|
useFlag: (flag: string) => testContext.flags[flag] ?? false,
|
|
}
|
|
})
|
|
|
|
vi.mock('@/components/ui/CodeEditor/CodeEditor', () => ({
|
|
CodeEditor: ({ value }: { value: string }) => (
|
|
<textarea aria-label="SQL editor" value={value} readOnly />
|
|
),
|
|
}))
|
|
|
|
vi.mock('./ExplorerQuerySourceMenu', () => ({ ExplorerQuerySourceMenu: () => null }))
|
|
|
|
const renderQueryTab = () =>
|
|
customRender(
|
|
<TabsStateContext.Provider value={createTabsState('default')}>
|
|
<QueryTab />
|
|
</TabsStateContext.Provider>
|
|
)
|
|
|
|
const createDraft = (
|
|
source:
|
|
| { _tag: 'database'; database_identifier?: string }
|
|
| {
|
|
_tag: 'logs'
|
|
time_range: { _tag: 'relative_time_range'; amount: number; unit: 'hour' }
|
|
}
|
|
) => {
|
|
explorerQueryState.removeDraft({ id: 'query-test', projectRef: 'default' })
|
|
explorerQueryState.createDraft({
|
|
id: 'query-test',
|
|
projectRef: 'default',
|
|
sql: 'select 1',
|
|
source,
|
|
})
|
|
}
|
|
|
|
beforeEach(() => {
|
|
setupSqlEditorMocks()
|
|
testContext.flags.otelLegacyLogs = true
|
|
testContext.params = { ref: 'default', id: 'query-test' }
|
|
explorerQueryState.removeDraft({ id: 'query-test', projectRef: 'default' })
|
|
})
|
|
|
|
afterEach(() => explorerQueryState.flushPendingPersistence())
|
|
|
|
describe('QueryTab execution', () => {
|
|
it('keeps loading while dynamic route parameters are unavailable', () => {
|
|
testContext.params = {}
|
|
|
|
renderQueryTab()
|
|
|
|
expect(screen.getByRole('status', { name: 'Loading query' })).toBeInTheDocument()
|
|
expect(screen.queryByText('Query draft not found')).not.toBeInTheDocument()
|
|
})
|
|
|
|
it('records an unavailable error and skips the logs endpoint when the flag is off', async () => {
|
|
testContext.flags.otelLegacyLogs = false
|
|
createDraft({
|
|
_tag: 'logs',
|
|
time_range: { _tag: 'relative_time_range', amount: 1, unit: 'hour' },
|
|
})
|
|
const requests: Request[] = []
|
|
addAPIMock({
|
|
method: 'post',
|
|
path: '/platform/projects/:ref/analytics/endpoints/logs.all.otel',
|
|
response: ({ request }) => {
|
|
requests.push(request)
|
|
return HttpResponse.json({ result: [] })
|
|
},
|
|
})
|
|
|
|
renderQueryTab()
|
|
const runButton = await screen.findByRole('button', { name: 'Run' })
|
|
await waitFor(() => expect(runButton).toBeEnabled())
|
|
await userEvent.click(runButton)
|
|
|
|
expect(
|
|
await screen.findByText("Error: Querying logs isn't available for this project yet.")
|
|
).toBeInTheDocument()
|
|
expect(requests).toHaveLength(0)
|
|
})
|
|
|
|
it('waits for replicas, then fails closed when the selected database is absent', async () => {
|
|
createDraft({ _tag: 'database', database_identifier: 'missing-replica' })
|
|
let releaseReplicas: () => void = () => undefined
|
|
const replicasPending = new Promise<void>((resolve) => {
|
|
releaseReplicas = resolve
|
|
})
|
|
addAPIMock({
|
|
method: 'get',
|
|
path: '/platform/projects/:ref/databases',
|
|
response: async () => {
|
|
await replicasPending
|
|
return HttpResponse.json<ReadReplicasData>([])
|
|
},
|
|
})
|
|
const requests: Request[] = []
|
|
addAPIMock({
|
|
method: 'post',
|
|
path: '/platform/pg-meta/:ref/query',
|
|
response: ({ request }) => {
|
|
requests.push(request)
|
|
return HttpResponse.json([])
|
|
},
|
|
})
|
|
|
|
renderQueryTab()
|
|
const runButton = await screen.findByRole('button', { name: 'Run' })
|
|
expect(runButton).toBeDisabled()
|
|
|
|
act(() => releaseReplicas())
|
|
await waitFor(() => expect(runButton).toBeEnabled())
|
|
await userEvent.click(runButton)
|
|
|
|
expect(
|
|
await screen.findByText('Error: Unable to run query: Connection string is missing')
|
|
).toBeInTheDocument()
|
|
expect(requests).toHaveLength(0)
|
|
})
|
|
|
|
it('resolves a relative logs range before sending the request', async () => {
|
|
createDraft({
|
|
_tag: 'logs',
|
|
time_range: { _tag: 'relative_time_range', amount: 2, unit: 'hour' },
|
|
})
|
|
const bodies: Array<{ iso_timestamp_start: string; iso_timestamp_end: string }> = []
|
|
addAPIMock({
|
|
method: 'post',
|
|
path: '/platform/projects/:ref/analytics/endpoints/logs.all.otel',
|
|
response: async ({ request }) => {
|
|
bodies.push((await request.json()) as (typeof bodies)[number])
|
|
return HttpResponse.json({ result: [] })
|
|
},
|
|
})
|
|
|
|
renderQueryTab()
|
|
const runButton = await screen.findByRole('button', { name: 'Run' })
|
|
await waitFor(() => expect(runButton).toBeEnabled())
|
|
await userEvent.click(runButton)
|
|
await waitFor(() => expect(bodies).toHaveLength(1))
|
|
|
|
expect(
|
|
new Date(bodies[0].iso_timestamp_end).getTime() -
|
|
new Date(bodies[0].iso_timestamp_start).getTime()
|
|
).toBe(2 * 60 * 60 * 1000)
|
|
})
|
|
})
|