Skip to content

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

feat(studio): add useInfiniteTablesQuery hook for paginated tables (#46285)

Charis426b0183af56
diff --git a/apps/studio/data/tables/keys.ts b/apps/studio/data/tables/keys.ts
index 9d842f69d31..87c5603922e 100644
--- a/apps/studio/data/tables/keys.ts
+++ b/apps/studio/data/tables/keys.ts
@@ -2,6 +2,15 @@ export const tableKeys = {
names: (projectRef: string | undefined) => ['projects', projectRef, 'table-names'] as const,
list: (projectRef: string | undefined, schema?: string, includeColumns?: boolean) =>
['projects', projectRef, 'tables', schema, includeColumns].filter(Boolean),
+ infiniteList: (
+ projectRef: string | undefined,
+ schema?: string,
+ includeColumns?: boolean,
+ pageSize?: number
+ ) =>
+ ['projects', projectRef, 'tables', 'infinite', schema, includeColumns, pageSize].filter(
+ (part) => part !== undefined && part !== null && part !== ''
+ ),
retrieve: (projectRef: string | undefined, name: string, schema: string) =>
['projects', projectRef, 'table', schema, name].filter(Boolean),
}
diff --git a/apps/studio/data/tables/tables-query.ts b/apps/studio/data/tables/tables-query.ts
index b03d71816c8..3d6aa93fdb3 100644
--- a/apps/studio/data/tables/tables-query.ts
+++ b/apps/studio/data/tables/tables-query.ts
@@ -1,13 +1,14 @@
-import type { PGTable } from '@supabase/pg-meta'
+import { getTablesPaginatedSql, type PGTable } from '@supabase/pg-meta'
import { DEFAULT_PLATFORM_APPLICATION_NAME } from '@supabase/pg-meta/src/constants'
-import { useQuery, useQueryClient } from '@tanstack/react-query'
+import { InfiniteData, useInfiniteQuery, useQuery, useQueryClient } from '@tanstack/react-query'
import { sortBy } from 'lodash'
import { useCallback } from 'react'
import { tableKeys } from './keys'
import { get, handleError } from '@/data/fetchers'
+import { executeSql } from '@/data/sql/execute-sql-query'
import type { SafePostgresTable } from '@/lib/postgres-types'
-import type { ResponseError, UseCustomQueryOptions } from '@/types'
+import type { ResponseError, UseCustomInfiniteQueryOptions, UseCustomQueryOptions } from '@/types'
export type TablesVariables = {
projectRef?: string
@@ -123,3 +124,74 @@ export function usePrefetchTables({
[connectionString, projectRef, queryClient]
)
}
+
+export type InfiniteTablesVariables = Pick<
+ TablesVariables,
+ 'projectRef' | 'connectionString' | 'schema' | 'includeColumns'
+> & {
+ pageSize?: number
+}
+
+export async function getTablesPage(
+ {
+ projectRef,
+ connectionString,
+ schema,
+ includeColumns = false,
+ limit,
+ afterOid,
+ }: Pick<TablesVariables, 'projectRef' | 'connectionString' | 'schema' | 'includeColumns'> & {
+ limit: number
+ afterOid: number
+ },
+ signal?: AbortSignal
+) {
+ if (!projectRef) {
+ throw new Error('projectRef is required')
+ }
+
+ const sql = getTablesPaginatedSql({ schema, includeColumns, limit, afterOid })
+
+ const { result } = await executeSql(
+ {
+ projectRef,
+ connectionString,
+ sql,
+ queryKey: tableKeys
+ .infiniteList(projectRef, schema, includeColumns, limit)
+ .concat([afterOid]),
+ },
+ signal
+ )
+
+ return result as SafePostgresTable[]
+}
+
+export const useInfiniteTablesQuery = <TData = InfiniteData<TablesData>>(
+ { projectRef, connectionString, schema, includeColumns, pageSize = 50 }: InfiniteTablesVariables,
+ {
+ enabled = true,
+ ...options
+ }: UseCustomInfiniteQueryOptions<TablesData, TablesError, TData, readonly unknown[], number> = {}
+) => {
+ return useInfiniteQuery({
+ queryKey: tableKeys.infiniteList(projectRef, schema, includeColumns, pageSize),
+ queryFn: ({ signal, pageParam }) =>
+ getTablesPage(
+ {
+ projectRef,
+ connectionString,
+ schema,
+ includeColumns,
+ limit: pageSize,
+ afterOid: pageParam,
+ },
+ signal
+ ),
+ enabled: enabled && typeof projectRef !== 'undefined',
+ initialPageParam: 0,
+ getNextPageParam: (lastPage) =>
+ lastPage.length < pageSize ? undefined : lastPage[lastPage.length - 1].id,
+ ...options,
+ })
+}
diff --git a/packages/pg-meta/src/sql/columns.ts b/packages/pg-meta/src/sql/columns.ts
index 1d81d4d5932..cd3c8a3e0ac 100644
--- a/packages/pg-meta/src/sql/columns.ts
+++ b/packages/pg-meta/src/sql/columns.ts
@@ -1,6 +1,29 @@
-import { safeSql } from '../pg-format'
+import { safeSql, type SafeSqlFragment } from '../pg-format'
-export const COLUMNS_SQL = /* SQL */ safeSql`
+// Columns of the underlying pg_class scan that callers are allowed to filter
+// on. The map owns the actual aliased reference (`c.oid` etc.), so callers
+// never need to know the internal aliases — they just pick a key.
+const COLUMNS_FILTER_COLUMNS = {
+ oid: safeSql`c.oid`,
+} as const
+
+export type ColumnsFilterColumn = keyof typeof COLUMNS_FILTER_COLUMNS
+
+export type ColumnsFilter = {
+ column: ColumnsFilterColumn
+ // Everything to the right of the column reference — e.g.
+ // safeSql`IN (SELECT oid FROM page)` or safeSql`= ${literal(123)}`
+ predicate: SafeSqlFragment
+}
+
+// `filter`, if provided, is appended to the WHERE clause as
+// `AND <column-ref> <predicate>`.
+export const getColumnsSql = ({ filter }: { filter?: ColumnsFilter } = {}): SafeSqlFragment => {
+ const filterClause = filter
+ ? safeSql`AND ${COLUMNS_FILTER_COLUMNS[filter.column]} ${filter.predicate}`
+ : safeSql``
+
+ return /* SQL */ safeSql`
-- Adapted from information_schema.columns
SELECT
@@ -113,4 +136,8 @@ WHERE
'SELECT, INSERT, UPDATE, REFERENCES'
)
)
+ ${filterClause}
`
+}
+
+export const COLUMNS_SQL = getColumnsSql()
diff --git a/packages/pg-meta/src/sql/studio/database/index.ts b/packages/pg-meta/src/sql/studio/database/index.ts
index 380e941f0b1..48e84d36ea3 100644
--- a/packages/pg-meta/src/sql/studio/database/index.ts
+++ b/packages/pg-meta/src/sql/studio/database/index.ts
@@ -13,6 +13,7 @@ export * from './privileges'
export * from './queues'
export * from './rows'
export * from './table-definition'
+export * from './tables-paginated'
export * from './triggers'
export * from './types'
export * from './vault'
diff --git a/packages/pg-meta/src/sql/studio/database/tables-paginated.ts b/packages/pg-meta/src/sql/studio/database/tables-paginated.ts
new file mode 100644
index 00000000000..de5d986e7b0
--- /dev/null
+++ b/packages/pg-meta/src/sql/studio/database/tables-paginated.ts
@@ -0,0 +1,198 @@
+import { DEFAULT_SYSTEM_SCHEMAS } from '../../../constants'
+import { coalesceRowsToArray, filterByList } from '../../../helpers'
+import { literal, safeSql, type SafeSqlFragment } from '../../../pg-format'
+import { getColumnsSql } from '../../columns'
+
+// Cursor-paginated tables list ordered by c.oid (backed by pg_class_oid_index —
+// unique, always present, indexed). Pagination is by `where c.oid > $afterOid`
+// instead of OFFSET so deep pages stay O(limit) rather than O(offset + limit).
+// Pass afterOid = 0 for the first page; subsequent pages pass the largest `id`
+// returned by the previous page.
+//
+// Structure is deliberately not built on top of the existing `TABLES_SQL`
+// constant: that query GROUPs over the whole catalog and joins relationships
+// with an OR predicate that fans out across every (source, target) pair, so
+// wrapping it as `select * from (TABLES_SQL) ... limit N` still pays the full
+// cost before LIMIT applies. Here the `page` CTE picks the OIDs for the
+// requested page first (cheap — pg_class index scan), and every enrichment CTE
+// downstream is constrained to that small set.
+export const getTablesPaginatedSql = ({
+ schema,
+ includeColumns = false,
+ limit,
+ afterOid,
+}: {
+ schema?: string
+ includeColumns?: boolean
+ limit: number
+ afterOid: number
+}): SafeSqlFragment => {
+ const filter = filterByList(
+ schema ? [schema] : undefined,
+ undefined,
+ schema ? undefined : DEFAULT_SYSTEM_SCHEMAS
+ )
+ const schemaFilter = filter ? safeSql`and nc.nspname ${filter}` : safeSql``
+
+ const columnsCte = includeColumns
+ ? safeSql`, columns as (${getColumnsSql({
+ filter: { column: 'oid', predicate: safeSql`in (select oid from page)` },
+ })})`
+ : safeSql``
+
+ const columnsSelect = includeColumns
+ ? safeSql`, ${coalesceRowsToArray('columns', safeSql`columns.table_id = tables.id`)}`
+ : safeSql``
+
+ return safeSql`
+ with page as (
+ select
+ c.oid,
+ c.relname,
+ c.relrowsecurity,
+ c.relforcerowsecurity,
+ c.relreplident,
+ nc.nspname as schema,
+ -- Computed once here so the final select can reference it for both the
+ -- raw byte count and pg_size_pretty without re-walking heap+toast+indexes.
+ pg_total_relation_size(c.oid) as bytes_raw
+ from pg_namespace nc
+ join pg_class c on nc.oid = c.relnamespace
+ where c.relkind in ('r', 'p')
+ and not pg_is_other_temp_schema(nc.oid)
+ and c.oid > ${literal(afterOid)}
+ and (
+ pg_has_role(c.relowner, 'USAGE')
+ or has_table_privilege(
+ c.oid,
+ 'SELECT, INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES, TRIGGER'
+ )
+ or has_any_column_privilege(c.oid, 'SELECT, INSERT, UPDATE, REFERENCES')
+ )
+ ${schemaFilter}
+ order by c.oid
+ limit ${literal(limit)}
+ ),
+ page_primary_keys as (
+ select
+ c.oid::int8 as table_id,
+ jsonb_agg(
+ jsonb_build_object(
+ 'table_id', c.oid::int8,
+ 'schema', n.nspname,
+ 'table_name', c.relname,
+ 'name', a.attname
+ )
+ order by array_position(i.indkey, a.attnum)
+ ) as primary_keys
+ from pg_index i
+ join pg_class c on i.indrelid = c.oid
+ join pg_namespace n on c.relnamespace = n.oid
+ join pg_attribute a on a.attrelid = c.oid and a.attnum = any(i.indkey)
+ where i.indisprimary
+ and c.oid in (select oid from page)
+ group by c.oid
+ ),
+ -- Two-armed UNION ALL keyed by table_id so the downstream join is a plain
+ -- equi-join (see tables CTE below). The previous shape used an OR across
+ -- (source_oid, target_oid), which planners can't decompose into two index
+ -- probes. The target-side arm skips self-referential FKs so they aren't
+ -- emitted twice.
+ page_relationships as (
+ select
+ csa.oid::int8 as table_id,
+ c.oid::int8 as id,
+ c.conname as constraint_name,
+ nsa.nspname as source_schema,
+ csa.relname as source_table_name,
+ sa.attname as source_column_name,
+ nta.nspname as target_table_schema,
+ cta.relname as target_table_name,
+ ta.attname as target_column_name
+ from pg_constraint c
+ join pg_class csa on csa.oid = c.conrelid
+ join pg_namespace nsa on nsa.oid = csa.relnamespace
+ -- Pair conkey/confkey by ordinal so composite FKs don't fan out into a
+ -- cross-product of (source_col, target_col) rows.
+ join lateral unnest(c.conkey, c.confkey) as fk(src_attnum, tgt_attnum) on true
+ join pg_attribute sa on sa.attrelid = c.conrelid and sa.attnum = fk.src_attnum
+ join pg_class cta on cta.oid = c.confrelid
+ join pg_namespace nta on nta.oid = cta.relnamespace
+ join pg_attribute ta on ta.attrelid = c.confrelid and ta.attnum = fk.tgt_attnum
+ where c.contype = 'f'
+ and csa.oid in (select oid from page)
+ union all
+ select
+ cta.oid::int8 as table_id,
+ c.oid::int8 as id,
+ c.conname as constraint_name,
+ nsa.nspname as source_schema,
+ csa.relname as source_table_name,
+ sa.attname as source_column_name,
+ nta.nspname as target_table_schema,
+ cta.relname as target_table_name,
+ ta.attname as target_column_name
+ from pg_constraint c
+ join pg_class csa on csa.oid = c.conrelid
+ join pg_namespace nsa on nsa.oid = csa.relnamespace
+ join lateral unnest(c.conkey, c.confkey) as fk(src_attnum, tgt_attnum) on true
+ join pg_attribute sa on sa.attrelid = c.conrelid and sa.attnum = fk.src_attnum
+ join pg_class cta on cta.oid = c.confrelid
+ join pg_namespace nta on nta.oid = cta.relnamespace
+ join pg_attribute ta on ta.attrelid = c.confrelid and ta.attnum = fk.tgt_attnum
+ where c.contype = 'f'
+ and cta.oid in (select oid from page)
+ and cta.oid <> csa.oid
+ ),
+ tables as (
+ select
+ p.oid::int8 as id,
+ p.schema as schema,
+ p.relname as name,
+ p.relrowsecurity as rls_enabled,
+ p.relforcerowsecurity as rls_forced,
+ case
+ when p.relreplident = 'd' then 'DEFAULT'
+ when p.relreplident = 'i' then 'INDEX'
+ when p.relreplident = 'f' then 'FULL'
+ else 'NOTHING'
+ end as replica_identity,
+ p.bytes_raw::int8 as bytes,
+ pg_size_pretty(p.bytes_raw) as size,
+ pg_stat_get_live_tuples(p.oid) as live_rows_estimate,
+ pg_stat_get_dead_tuples(p.oid) as dead_rows_estimate,
+ obj_description(p.oid) as comment,
+ coalesce(pk.primary_keys, '[]'::jsonb) as primary_keys,
+ coalesce(
+ jsonb_agg(
+ jsonb_build_object(
+ 'id', r.id,
+ 'constraint_name', r.constraint_name,
+ 'source_schema', r.source_schema,
+ 'source_table_name', r.source_table_name,
+ 'source_column_name', r.source_column_name,
+ 'target_table_schema', r.target_table_schema,
+ 'target_table_name', r.target_table_name,
+ 'target_column_name', r.target_column_name
+ )
+ ) filter (where r.id is not null),
+ '[]'::jsonb
+ ) as relationships
+ from page p
+ left join page_primary_keys pk on pk.table_id = p.oid
+ left join page_relationships r on r.table_id = p.oid
+ group by
+ p.oid,
+ p.schema,
+ p.relname,
+ p.relrowsecurity,
+ p.relforcerowsecurity,
+ p.relreplident,
+ p.bytes_raw,
+ pk.primary_keys
+ )${columnsCte}
+ select tables.*${columnsSelect}
+ from tables
+ order by tables.id
+ `
+}
diff --git a/packages/pg-meta/test/sql/studio/tables-paginated.test.ts b/packages/pg-meta/test/sql/studio/tables-paginated.test.ts
new file mode 100644
index 00000000000..bacde07b0bf
--- /dev/null
+++ b/packages/pg-meta/test/sql/studio/tables-paginated.test.ts
@@ -0,0 +1,334 @@
+import { afterAll, expect, test } from 'vitest'
+
+import pgMeta, { getTablesPaginatedSql } from '../../../src'
+import { cleanupRoot, createTestDatabase } from '../../db/utils'
+
+afterAll(async () => {
+ await cleanupRoot()
+})
+
+type Row = {
+ id: number
+ schema: string
+ name: string
+ rls_enabled: boolean
+ rls_forced: boolean
+ replica_identity: string
+ bytes: number
+ size: string
+ live_rows_estimate: number
+ dead_rows_estimate: number
+ comment: string | null
+ primary_keys: Array<{ table_id: number; schema: string; table_name: string; name: string }>
+ relationships: Array<{
+ id: number
+ constraint_name: string
+ source_schema: string
+ source_table_name: string
+ source_column_name: string
+ target_table_schema: string
+ target_table_name: string
+ target_column_name: string
+ }>
+ columns?: Array<{ table_id: number; name: string }>
+}
+
+const withTestDatabase = (
+ name: string,
+ fn: (db: Awaited<ReturnType<typeof createTestDatabase>>) => Promise<void>
+) => {
+ test(name, async () => {
+ const db = await createTestDatabase()
+ try {
+ await fn(db)
+ } finally {
+ await db.cleanup()
+ }
+ })
+}
+
+withTestDatabase('returns public tables ordered by oid', async ({ executeQuery }) => {
+ const sql = getTablesPaginatedSql({ schema: 'public', limit: 100, afterOid: 0 })
+ const rows = await executeQuery<Row[]>(sql)
+
+ expect(rows.length).toBeGreaterThan(0)
+ // Every row is in `public`
+ expect(rows.every((r) => r.schema === 'public')).toBe(true)
+ // Strictly increasing OIDs
+ for (let i = 1; i < rows.length; i++) {
+ expect(rows[i].id).toBeGreaterThan(rows[i - 1].id)
+ }
+ // Seed contains these base tables
+ const names = rows.map((r) => r.name)
+ for (const expected of ['users', 'todos', 'user_details', 'category', 'memes']) {
+ expect(names).toContain(expected)
+ }
+ // Views / materialized views excluded (relkind filter)
+ expect(names).not.toContain('todos_view')
+ expect(names).not.toContain('todos_matview')
+})
+
+withTestDatabase(
+ 'excludes system schemas when no schema filter given',
+ async ({ executeQuery }) => {
+ const sql = getTablesPaginatedSql({ limit: 500, afterOid: 0 })
+ const rows = await executeQuery<Row[]>(sql)
+
+ expect(rows.length).toBeGreaterThan(0)
+ for (const r of rows) {
+ expect(r.schema).not.toBe('pg_catalog')
+ expect(r.schema).not.toBe('information_schema')
+ expect(r.schema).not.toBe('pg_toast')
+ }
+ }
+)
+
+withTestDatabase('cursor pagination has no overlap and no gap', async ({ executeQuery }) => {
+ // Fetch the full list first as ground truth.
+ const fullSql = getTablesPaginatedSql({ schema: 'public', limit: 1000, afterOid: 0 })
+ const all = await executeQuery<Row[]>(fullSql)
+ expect(all.length).toBeGreaterThanOrEqual(4)
+
+ // Walk pages of size 3 using cursor pagination, collect all rows, compare.
+ const pageSize = 3
+ const collected: Row[] = []
+ let cursor = 0
+ // Safety bound — far more pages than the seed could ever produce.
+ for (let i = 0; i < 50; i++) {
+ const pageSql = getTablesPaginatedSql({
+ schema: 'public',
+ limit: pageSize,
+ afterOid: cursor,
+ })
+ const page = await executeQuery<Row[]>(pageSql)
+ collected.push(...page)
+ if (page.length < pageSize) break
+ cursor = page[page.length - 1].id
+ }
+
+ expect(collected.map((r) => r.id)).toEqual(all.map((r) => r.id))
+})
+
+withTestDatabase('short last page signals end of pagination', async ({ executeQuery }) => {
+ const fullSql = getTablesPaginatedSql({ schema: 'public', limit: 1000, afterOid: 0 })
+ const all = await executeQuery<Row[]>(fullSql)
+
+ // Choose a page size strictly larger than the dataset so the first page is
+ // necessarily the last page.
+ const pageSize = all.length + 5
+ const sql = getTablesPaginatedSql({ schema: 'public', limit: pageSize, afterOid: 0 })
+ const page = await executeQuery<Row[]>(sql)
+
+ expect(page.length).toBeLessThan(pageSize)
+ expect(page.length).toBe(all.length)
+})
+
+withTestDatabase('schema filter restricts to the requested schema', async ({ executeQuery }) => {
+ await executeQuery(`
+ create schema if not exists other_schema;
+ create table other_schema.widgets (id bigint primary key);
+ `)
+
+ const publicSql = getTablesPaginatedSql({ schema: 'public', limit: 500, afterOid: 0 })
+ const publicRows = await executeQuery<Row[]>(publicSql)
+ expect(publicRows.every((r) => r.schema === 'public')).toBe(true)
+ expect(publicRows.map((r) => r.name)).not.toContain('widgets')
+
+ const otherSql = getTablesPaginatedSql({ schema: 'other_schema', limit: 500, afterOid: 0 })
+ const otherRows = await executeQuery<Row[]>(otherSql)
+ expect(otherRows.map((r) => ({ schema: r.schema, name: r.name }))).toEqual([
+ { schema: 'other_schema', name: 'widgets' },
+ ])
+})
+
+withTestDatabase('primary keys are populated per table', async ({ executeQuery }) => {
+ const sql = getTablesPaginatedSql({ schema: 'public', limit: 100, afterOid: 0 })
+ const rows = await executeQuery<Row[]>(sql)
+
+ const users = rows.find((r) => r.name === 'users')!
+ expect(users.primary_keys).toEqual([
+ { table_id: users.id, schema: 'public', table_name: 'users', name: 'id' },
+ ])
+
+ // users_audit has no primary key in the seed.
+ const usersAudit = rows.find((r) => r.name === 'users_audit')!
+ expect(usersAudit.primary_keys).toEqual([])
+})
+
+withTestDatabase(
+ 'composite FK pairs source and target columns by ordinal position',
+ async ({ executeQuery }) => {
+ // A composite FK with N columns must produce exactly N relationship rows,
+ // each pairing source column k with target column k. The naive
+ // `attnum = any(conkey)` + `attnum = any(confkey)` shape produces an N*N
+ // cross-product with mismatched pairings.
+ await executeQuery(`
+ create table public.composite_parent (
+ a int,
+ b int,
+ primary key (a, b)
+ );
+ create table public.composite_child (
+ id bigint primary key,
+ pa int not null,
+ pb int not null,
+ foreign key (pa, pb) references public.composite_parent (a, b)
+ );
+ `)
+
+ const sql = getTablesPaginatedSql({ schema: 'public', limit: 500, afterOid: 0 })
+ const rows = await executeQuery<Row[]>(sql)
+
+ const child = rows.find((r) => r.name === 'composite_child')!
+ const childRels = child.relationships.filter((r) => r.target_table_name === 'composite_parent')
+
+ expect(childRels).toHaveLength(2)
+ expect(childRels).toContainEqual(
+ expect.objectContaining({
+ source_table_name: 'composite_child',
+ source_column_name: 'pa',
+ target_table_name: 'composite_parent',
+ target_column_name: 'a',
+ })
+ )
+ expect(childRels).toContainEqual(
+ expect.objectContaining({
+ source_table_name: 'composite_child',
+ source_column_name: 'pb',
+ target_table_name: 'composite_parent',
+ target_column_name: 'b',
+ })
+ )
+ // No cross-product pairings.
+ expect(childRels).not.toContainEqual(
+ expect.objectContaining({ source_column_name: 'pa', target_column_name: 'b' })
+ )
+ expect(childRels).not.toContainEqual(
+ expect.objectContaining({ source_column_name: 'pb', target_column_name: 'a' })
+ )
+
+ // The parent side (target-arm of the UNION) must also pair correctly.
+ const parent = rows.find((r) => r.name === 'composite_parent')!
+ const parentRels = parent.relationships.filter((r) => r.source_table_name === 'composite_child')
+ expect(parentRels).toHaveLength(2)
+ expect(parentRels).toContainEqual(
+ expect.objectContaining({ source_column_name: 'pa', target_column_name: 'a' })
+ )
+ expect(parentRels).toContainEqual(
+ expect.objectContaining({ source_column_name: 'pb', target_column_name: 'b' })
+ )
+ }
+)
+
+withTestDatabase(
+ 'relationships populate both source and target sides',
+ async ({ executeQuery }) => {
+ const sql = getTablesPaginatedSql({ schema: 'public', limit: 100, afterOid: 0 })
+ const rows = await executeQuery<Row[]>(sql)
+
+ // `todos."user-id"` references `users.id` — show up on both sides.
+ const todos = rows.find((r) => r.name === 'todos')!
+ expect(todos.relationships).toContainEqual(
+ expect.objectContaining({
+ source_table_name: 'todos',
+ source_column_name: 'user-id',
+ target_table_name: 'users',
+ target_column_name: 'id',
+ })
+ )
+
+ const users = rows.find((r) => r.name === 'users')!
+ expect(users.relationships).toContainEqual(
+ expect.objectContaining({
+ source_table_name: 'todos',
+ target_table_name: 'users',
+ })
+ )
+
+ // Tables without FKs should still have an empty array, not null.
+ const empty = rows.find((r) => r.name === 'empty')!
+ expect(empty.relationships).toEqual([])
+ }
+)
+
+withTestDatabase('includeColumns: false omits the columns field', async ({ executeQuery }) => {
+ const sql = getTablesPaginatedSql({
+ schema: 'public',
+ limit: 10,
+ afterOid: 0,
+ includeColumns: false,
+ })
+ const rows = await executeQuery<Row[]>(sql)
+
+ expect(rows.length).toBeGreaterThan(0)
+ for (const r of rows) {
+ expect(r).not.toHaveProperty('columns')
+ }
+})
+
+withTestDatabase('includeColumns: true returns columns per row', async ({ executeQuery }) => {
+ const sql = getTablesPaginatedSql({
+ schema: 'public',
+ limit: 100,
+ afterOid: 0,
+ includeColumns: true,
+ })
+ const rows = await executeQuery<Row[]>(sql)
+
+ const users = rows.find((r) => r.name === 'users')!
+ expect(Array.isArray(users.columns)).toBe(true)
+ const columnNames = users.columns!.map((c) => c.name).sort()
+ expect(columnNames).toEqual(['id', 'name', 'status'])
+ // Columns are scoped to the table.
+ expect(users.columns!.every((c) => c.table_id === users.id)).toBe(true)
+
+ // Tables without columns return an empty array, not null.
+ const empty = rows.find((r) => r.name === 'empty')!
+ expect(empty.columns).toEqual([])
+})
+
+withTestDatabase('afterOid skips tables with smaller oids', async ({ executeQuery }) => {
+ const fullSql = getTablesPaginatedSql({ schema: 'public', limit: 1000, afterOid: 0 })
+ const all = await executeQuery<Row[]>(fullSql)
+ expect(all.length).toBeGreaterThanOrEqual(3)
+
+ const cursor = all[1].id
+ const afterSql = getTablesPaginatedSql({ schema: 'public', limit: 1000, afterOid: cursor })
+ const after = await executeQuery<Row[]>(afterSql)
+
+ expect(after.map((r) => r.id)).toEqual(all.slice(2).map((r) => r.id))
+ // Strictly greater than the cursor — `c.oid > afterOid`, not `>=`.
+ expect(after.every((r) => r.id > cursor)).toBe(true)
+})
+
+// Output shape parity with `pgMeta.tables.list()` — uses the same pgTableZod the
+// non-paginated path validates against, so the two queries can't drift.
+withTestDatabase('output parses as PGTable[] (with columns)', async ({ executeQuery }) => {
+ const sql = getTablesPaginatedSql({
+ schema: 'public',
+ limit: 100,
+ afterOid: 0,
+ includeColumns: true,
+ })
+ const rows = await executeQuery(sql)
+ const { zod } = pgMeta.tables.list({ includeColumns: true })
+
+ const parsed = zod.parse(rows)
+ expect(parsed.length).toBe(rows.length)
+ expect(parsed.length).toBeGreaterThan(0)
+})
+
+withTestDatabase('output parses as PGTable[] (without columns)', async ({ executeQuery }) => {
+ const sql = getTablesPaginatedSql({
+ schema: 'public',
+ limit: 100,
+ afterOid: 0,
+ includeColumns: false,
+ })
+ const rows = await executeQuery(sql)
+ const { zod } = pgMeta.tables.list({ includeColumns: false })
+
+ const parsed = zod.parse(rows)
+ expect(parsed.length).toBe(rows.length)
+ expect(parsed.length).toBeGreaterThan(0)
+})