Files
supabase/e2e/studio/utils/wait-for-response.ts
Joshen Lim 6abbb5700d Joshenlim/fe 5274 re database tables reshuffles the (#54521)
## Context

On Database > Tables, schemas with more than 50 relations reshuffle as
you scroll.
- Tables were paged by `oid`, then the merged list was re-sorted by name
on the client
- Views, materialized views and foreign tables came from three separate
unpaginated queries and were merged into the same sorted list, so the
list was never stable across pages

## Changes involved

Am hence opting to use the same query that we fetch entities in the
Table Editor for the Database > Tables page with a few tweaks
- `TableList` now uses `getEntityTypesSQL` instead of 4 separate queries
to fetch tables, views, materialised views and partition tables
- `getEntityTypesSQL` gets a new `enrich` prop which fetches additional
data that the Database > Tables page requires (e.g column count, row
count, size, etc
- Selecting "Edit" or "Duplicate" actions in the Database > Tables page
will fetch the table's details on demand
- Also fixed searching via `getEntityTypesSQL` to escape `%` and `_` in
`search` with `escapeIlikeLiteral`, otherwise searching `my_table` also
matched `myXtable`

## Performance

As with every change to SQL queries in the dashboard, we benchmark the
performance to ensure that the dashboard never runs a heavy query
against the project's DB. This just benchmarks `enrich` off vs on with
`EXPLAIN ANALYZE` on synthetic schemas of 500, 2,000 and 8,000 tables.
Execution time, median of 5 warm runs:

| Schema tables | limit 50 | limit 200 |
|---|---|---|
| 500 | +7.6 ms | +35.2 ms |
| 2,000 | +8.6 ms | +34.9 ms |
| 8,000 | +8.0 ms | +36.0 ms |

The extra cost is about 0.16 ms per row, the same at every schema size,
and the same on deep pages. It follows the page size, not the schema
size.

## To test

Create more than 50 relations in a schema (tables, views, materialized
views, a partitioned table), then on Database > Tables:

- [ ] Scroll through the list. New rows append at the bottom in
alphabetical order, with views mixed in.
- [ ] Untick and tick entity types. The list filters correctly, and
unticking all shows the empty state.
- [ ] Search `alph_` returns nothing when no name contains `alph_`, and
`zz_alpha` finds the matching rows.
- [ ] Create, edit, duplicate and delete a table. The list refreshes.
- [ ] Table Editor sidebar still lists and searches as before.
2026-12-04 14:49:17 +07:00

120 lines
4.3 KiB
TypeScript

import { Page } from '@playwright/test'
type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'
/**
* Waits for a API response for a specific endpoint before continuing the playwright test.
* @param page - Playwright page object
* @param basePath - Base path of API endpoint to wait for (e.g. 'pg-meta', 'platform/projects', etc.)
* @param ref - Project reference
* @param action - Action path of API endpoint to wait for (e.g. 'types', 'triggers', 'content', etc.)
* @param options - Optional object which checks more scenarios
*/
export async function waitForApiResponse(
page: Page,
basePath: string,
ref: string,
action: string,
options?: Options
): Promise<void> {
return createApiResponseWaiter(page, basePath, ref, action, options)
}
function buildUrlMatcher(basePath: string, ref: string, action: string, method?: HttpMethod) {
// Normalize inputs and build a tolerant matcher that works across environments
const trimmedBasePath = basePath.replace(/^\/+|\/+$/g, '')
const refAlternatives = [ref, 'default']
const [actionPath, actionQuery] = action.split('?')
const trimmedActionPath = actionPath.replace(/^\/+/, '')
const expectedSearchParams = new URLSearchParams(actionQuery ?? '')
return (response: any) => {
const url = new URL(response.url())
const requestMethod = response.request().method()
// Must include base path and one of the ref alternatives
const hasBasePath = url.pathname.includes(`/${trimmedBasePath}/`)
const hasRef = refAlternatives.some((r) => url.pathname.includes(`/${r}/`))
const hasActionPath =
trimmedActionPath.length === 0 || url.pathname.includes(`/${trimmedActionPath}`)
const hasExpectedSearchParams = [...expectedSearchParams.entries()].every(([key, value]) =>
url.searchParams.getAll(key).some((actualValue) => actualValue.includes(value))
)
const urlMatches = hasBasePath && hasRef && hasActionPath && hasExpectedSearchParams
if (method) return urlMatches && requestMethod === method
return urlMatches
}
}
/**
* Starts listening for a specific API response and returns a promise you can await later.
* Use this to avoid races by creating the waiter BEFORE triggering navigation/clicks.
*
* Example:
* const wait = createApiResponseWaiter(page, 'pg-meta', ref, 'query?key=schemas')
* await page.goto(...)
* await wait
*/
export function createApiResponseWaiter(
page: Page,
basePath: string,
ref: string,
action: string,
options?: Options
): Promise<void> {
const matcher = buildUrlMatcher(basePath, ref, action, options?.method)
return page
.waitForResponse(matcher, { timeout: options?.timeout ?? 30_000 })
.then(() => {})
.catch((error) => {
const trimmedBasePath = basePath.replace(/^\/+|\/+$/g, '')
const message = `Error waiting for response: ${error}. Method: ${options?.method}, URL contains: ${trimmedBasePath}/(default|${ref})/${action}`
if (options?.soft) {
console.warn(`[soft-wait] ${message}`)
const fallback = options?.fallbackWaitMs ?? 0
if (fallback > 0) {
return page.waitForTimeout(fallback).then(() => {})
}
return
} else {
console.error(message)
throw error
}
})
}
type Options = {
method?: HttpMethod
timeout?: number
// When true, do not throw on timeout/error; optionally wait fallbackWaitMs and continue
soft?: boolean
fallbackWaitMs?: number
}
export async function waitForTableToLoad(page: Page, ref: string, schema?: string) {
const tableSchema = schema || 'public'
return await waitForApiResponse(page, 'pg-meta', ref, `query?key=entity-types-${tableSchema}-`)
}
export async function waitForGridDataToLoad(page: Page, ref: string) {
return await waitForApiResponse(page, 'pg-meta', ref, 'query?key=table-rows-')
}
export async function waitForDatabaseToLoad(page: Page, ref: string, schema?: string) {
const databaseSchema = schema || 'public'
return await waitForApiResponse(page, 'pg-meta', ref, `query?key=entity-types-${databaseSchema}-`)
}
export async function waitForSchemaVisualizerToLoad(page: Page, ref: string, schema?: string) {
const databaseSchema = schema || 'public'
return await waitForApiResponse(
page,
'pg-meta',
ref,
`query?key=project:default-schema:${schema ?? 'public'}-infinite_tables`
)
}