Skip to content

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

chore(pg-meta): migrate columns (#33724)

Andrew Valleteaue823a352a489
diff --git a/packages/pg-meta/package.json b/packages/pg-meta/package.json
index d47f1e32210..b431ac4586f 100644
--- a/packages/pg-meta/package.json
+++ b/packages/pg-meta/package.json
@@ -11,7 +11,7 @@
"test": "run-s db:clean db:run test:run db:clean",
"db:clean": "cd test/db && docker compose down",
"db:run": "cd test/db && docker compose up --detach --wait",
- "test:run": "vitest run",
+ "test:run": "vitest run --coverage",
"test:update": "vitest run --update"
},
"dependencies": {
@@ -19,6 +19,7 @@
},
"devDependencies": {
"@types/pg": "^8.11.11",
+ "@vitest/coverage-v8": "2.1.8",
"npm-run-all": "^4.1.5",
"pg": "^8.13.1",
"postgres-array": "^3.0.2",
diff --git a/packages/pg-meta/src/helpers.ts b/packages/pg-meta/src/helpers.ts
index c550ceb33d3..5dda0d3de33 100644
--- a/packages/pg-meta/src/helpers.ts
+++ b/packages/pg-meta/src/helpers.ts
@@ -1,5 +1,18 @@
import { literal } from './pg-format'
+export const coalesceRowsToArray = (source: string, filter: string) => {
+ return `
+COALESCE(
+ (
+ SELECT
+ array_agg(row_to_json(${source})) FILTER (WHERE ${filter})
+ FROM
+ ${source}
+ ),
+ '{}'
+) AS ${source}`
+}
+
export function filterByList(include?: string[], exclude?: string[], defaultExclude?: string[]) {
if (defaultExclude) {
exclude = defaultExclude.concat(exclude ?? [])
@@ -11,3 +24,7 @@ export function filterByList(include?: string[], exclude?: string[], defaultExcl
}
return ''
}
+
+export function exceptionIdentifierNotFound(entityName: string, whereClause: string) {
+ return `raise exception 'Cannot find ${entityName} with: %', ${literal(whereClause)};`
+}
diff --git a/packages/pg-meta/src/index.ts b/packages/pg-meta/src/index.ts
index e146c002e07..ec13dcef50e 100644
--- a/packages/pg-meta/src/index.ts
+++ b/packages/pg-meta/src/index.ts
@@ -1,7 +1,12 @@
import roles from './pg-meta-roles'
+import columns from './pg-meta-columns'
import schemas from './pg-meta-schemas'
+import * as tables from './pg-meta-tables'
import * as functions from './pg-meta-functions'
import tablePrivileges from './pg-meta-table-privileges'
+import materializedViews from './pg-meta-materialized-views'
+import foreignTables from './pg-meta-foreign-tables'
+import views from './pg-meta-views'
import policies from './pg-meta-policies'
import triggers from './pg-meta-triggers'
import types from './pg-meta-types'
@@ -11,9 +16,14 @@ import columnPrivileges from './pg-meta-column-privileges'
export default {
roles,
+ columns,
schemas,
+ tables,
functions,
tablePrivileges,
+ materializedViews,
+ foreignTables,
+ views,
policies,
triggers,
types,
diff --git a/packages/pg-meta/src/pg-meta-columns.ts b/packages/pg-meta/src/pg-meta-columns.ts
new file mode 100644
index 00000000000..1be182cbb8a
--- /dev/null
+++ b/packages/pg-meta/src/pg-meta-columns.ts
@@ -0,0 +1,324 @@
+import { DEFAULT_SYSTEM_SCHEMAS } from './constants'
+import { filterByList } from './helpers'
+import { ident, literal } from './pg-format'
+import { COLUMNS_SQL } from './sql/columns'
+import { z } from 'zod'
+
+const pgColumnZod = z.object({
+ id: z.string(),
+ table_id: z.number(),
+ schema: z.string(),
+ table: z.string(),
+ name: z.string(),
+ ordinal_position: z.number(),
+ data_type: z.string(),
+ format: z.string(),
+ is_identity: z.boolean(),
+ identity_generation: z.string().nullable(),
+ is_generated: z.boolean(),
+ is_nullable: z.boolean(),
+ is_updatable: z.boolean(),
+ is_unique: z.boolean(),
+ check: z.string().nullable(),
+ default_value: z.any().nullable(),
+ enums: z.array(z.string()),
+ comment: z.string().nullable(),
+})
+
+export const pgColumnArrayZod = z.array(pgColumnZod)
+const pgColumnOptionalZod = z.optional(pgColumnZod)
+
+export type PGColumn = z.infer<typeof pgColumnZod>
+
+function list({
+ tableId,
+ includeSystemSchemas = false,
+ includedSchemas,
+ excludedSchemas,
+ limit,
+ offset,
+}: {
+ tableId?: number
+ includeSystemSchemas?: boolean
+ includedSchemas?: string[]
+ excludedSchemas?: string[]
+ limit?: number
+ offset?: number
+} = {}): {
+ sql: string
+ zod: typeof pgColumnArrayZod
+} {
+ let sql = `
+with
+ columns as (${COLUMNS_SQL})
+select
+ *
+from
+ columns
+where
+ true
+`
+
+ const filter = filterByList(
+ includedSchemas,
+ excludedSchemas,
+ !includeSystemSchemas ? DEFAULT_SYSTEM_SCHEMAS : undefined
+ )
+
+ if (filter) {
+ sql += ` and schema ${filter}`
+ }
+ if (tableId !== undefined) {
+ sql += ` and table_id = ${literal(tableId)} `
+ }
+ if (limit) {
+ sql = `${sql} limit ${limit}`
+ }
+ if (offset) {
+ sql = `${sql} offset ${offset}`
+ }
+ return {
+ sql,
+ zod: pgColumnArrayZod,
+ }
+}
+
+type ColumnIdentifier =
+ | Pick<PGColumn, 'id'>
+ | {
+ schema: string
+ table: string
+ name: string
+ }
+
+function getIdentifierWhereClause(identifier: ColumnIdentifier) {
+ if ('id' in identifier && identifier.id) {
+ return `${ident('id')} = ${literal(identifier.id)}`
+ } else if ('name' in identifier && identifier.name && identifier.schema && identifier.table) {
+ return `schema = ${literal(identifier.schema)} AND ${ident('table')} = ${literal(identifier.table)} AND name = ${literal(identifier.name)}`
+ }
+ throw new Error('Must provide either id or schema, name and table')
+}
+
+function retrieve(identifier: ColumnIdentifier): {
+ sql: string
+ zod: typeof pgColumnOptionalZod
+} {
+ const sql = `WITH columns AS (${COLUMNS_SQL}) SELECT * FROM columns WHERE ${getIdentifierWhereClause(identifier)};`
+ return {
+ sql,
+ zod: pgColumnOptionalZod,
+ }
+}
+
+function create({
+ table_id,
+ name,
+ type,
+ default_value,
+ default_value_format = 'literal',
+ is_identity = false,
+ identity_generation = 'BY DEFAULT',
+ is_nullable,
+ is_primary_key = false,
+ is_unique = false,
+ comment,
+ check,
+}: {
+ table_id: number
+ name: string
+ type: string
+ default_value?: any
+ default_value_format?: 'expression' | 'literal'
+ is_identity?: boolean
+ identity_generation?: 'BY DEFAULT' | 'ALWAYS'
+ is_nullable?: boolean
+ is_primary_key?: boolean
+ is_unique?: boolean
+ comment?: string
+ check?: string
+}): { sql: string } {
+ let defaultValueClause = ''
+ if (is_identity) {
+ if (default_value !== undefined) {
+ throw new Error('Columns cannot both be identity and have a default value')
+ }
+ defaultValueClause = `GENERATED ${identity_generation} AS IDENTITY`
+ } else if (default_value !== undefined) {
+ const formattedDefault =
+ // Here we must wrap the litteral value into a String in case it receive a direct number to quote and escape
+ // for the execute(format()) call. Maybe we should change the `default_value` to only accept a string instead ?
+ default_value_format === 'expression' ? default_value : `'${literal(String(default_value))}'`
+ defaultValueClause = `DEFAULT ${formattedDefault}`
+ }
+
+ const constraints: string[] = []
+ if (is_nullable === false) constraints.push('NOT NULL')
+ if (is_primary_key) constraints.push('PRIMARY KEY')
+ if (is_unique) constraints.push('UNIQUE')
+ if (check) constraints.push(`CHECK (${check})`)
+
+ const sql = `
+DO $$
+DECLARE
+ v_schema name;
+ v_table name;
+BEGIN
+ SELECT n.nspname, c.relname INTO v_schema, v_table
+ FROM pg_class c
+ JOIN pg_namespace n ON n.oid = c.relnamespace
+ WHERE c.oid = ${literal(table_id)};
+
+ IF v_schema IS NULL THEN
+ RAISE EXCEPTION 'Table with id % not found', ${literal(table_id)};
+ END IF;
+
+ execute(format(
+ 'ALTER TABLE %I.%I ADD COLUMN %I %s ${defaultValueClause} ${constraints.join(' ')}',
+ v_schema,
+ v_table,
+ ${literal(name)},
+ ${literal(type)}
+ ));
+
+ ${comment ? `execute(format('COMMENT ON COLUMN %I.%I.%I IS %L', v_schema, v_table, ${literal(name)}, quote_ident(${literal(comment)})));` : ''}
+END $$;`
+
+ return { sql }
+}
+
+function update(
+ id: string,
+ {
+ name,
+ type,
+ drop_default = false,
+ default_value,
+ default_value_format = 'literal',
+ is_identity,
+ identity_generation = 'BY DEFAULT',
+ is_nullable,
+ is_unique,
+ comment,
+ check,
+ }: {
+ name?: string
+ type?: string
+ drop_default?: boolean
+ default_value?: any
+ default_value_format?: 'expression' | 'literal'
+ is_identity?: boolean
+ identity_generation?: 'BY DEFAULT' | 'ALWAYS'
+ is_nullable?: boolean
+ is_unique?: boolean
+ comment?: string
+ check?: string | null
+ }
+): { sql: string } {
+ if (is_identity) {
+ if (default_value !== undefined) {
+ throw new Error('Columns cannot both be identity and have a default value')
+ }
+ }
+ const sql = `
+DO $$
+DECLARE
+ v_schema name;
+ v_table name;
+ v_column name;
+ v_attnum int2;
+ r record;
+BEGIN
+ WITH RECURSIVE column_info AS (
+ ${COLUMNS_SQL}
+ )
+ SELECT
+ schema,
+ ${ident('table')},
+ name,
+ ordinal_position::int2
+ INTO v_schema, v_table, v_column, v_attnum
+ FROM column_info
+ WHERE ${getIdentifierWhereClause({ id })};
+
+ IF v_schema IS NULL THEN
+ RAISE EXCEPTION 'Column with id % not found', ${literal(id)};
+ END IF;
+
+ ${is_nullable !== undefined ? `execute(format('ALTER TABLE %I.%I ALTER COLUMN %I ${is_nullable ? 'DROP NOT NULL' : 'SET NOT NULL'}', v_schema, v_table, v_column));` : ''}
+
+ ${type ? `execute(format('ALTER TABLE %I.%I ALTER COLUMN %I TYPE %I USING %I::%I', v_schema, v_table, v_column, ${literal(type)}, v_column, ${literal(type)}));` : ''}
+
+ ${drop_default ? `execute(format('ALTER TABLE %I.%I ALTER COLUMN %I DROP DEFAULT', v_schema, v_table, v_column));` : ''}
+
+ ${default_value !== undefined ? `execute(format('ALTER TABLE %I.%I ALTER COLUMN %I SET DEFAULT %s', v_schema, v_table, v_column, ${default_value_format === 'expression' ? default_value : literal(default_value)}));` : ''}
+
+ ${is_identity !== undefined ? `execute(format('ALTER TABLE %I.%I ALTER COLUMN %I ${is_identity ? `ADD GENERATED ${identity_generation} AS IDENTITY` : 'DROP IDENTITY IF EXISTS'}', v_schema, v_table, v_column));` : ''}
+
+ ${is_unique !== undefined ? `execute(format('ALTER TABLE %I.%I ${is_unique ? 'ADD UNIQUE' : 'DROP CONSTRAINT IF EXISTS %I_key'}', v_schema, v_table, ${is_unique ? `(${literal(name || 'v_column')})` : 'v_column'}));` : ''}
+
+ ${comment !== undefined ? `execute(format('COMMENT ON COLUMN %I.%I.%I IS %L', v_schema, v_table, v_column, ${literal(comment)}));` : ''}
+
+ ${
+ check !== undefined
+ ? `
+ -- Drop existing check constraint if any
+ FOR r IN (
+ SELECT conname
+ FROM pg_constraint
+ WHERE conrelid = format('%I.%I', v_schema, v_table)::regclass
+ AND contype = 'c'
+ AND conkey = ARRAY[v_attnum]
+ ) LOOP
+ EXECUTE format('ALTER TABLE %I.%I DROP CONSTRAINT %I', v_schema, v_table, r.conname);
+ END LOOP;
+ -- Create the new constraints if mentionned
+ ${check !== null ? `execute(format('ALTER TABLE %I.%I ADD CONSTRAINT %I CHECK (%s)', v_schema, v_table, v_column || '_check', ${literal(check)}));` : ''}
+ `
+ : ''
+ }
+ ${name ? `execute(format('ALTER TABLE %I.%I RENAME COLUMN %I TO %I', v_schema, v_table, v_column, ${literal(name)}));` : ''}
+END $$;`
+
+ return { sql }
+}
+
+function remove(id: string, { cascade = false } = {}): { sql: string } {
+ const sql = `
+DO $$
+DECLARE
+ v_schema name;
+ v_table name;
+ v_column name;
+BEGIN
+ WITH RECURSIVE column_info AS (
+ ${COLUMNS_SQL}
+ )
+ SELECT schema, ${ident('table')}, name
+ INTO v_schema, v_table, v_column
+ FROM column_info
+ WHERE id = ${literal(id)};
+
+ IF v_schema IS NULL THEN
+ RAISE EXCEPTION 'Column with id % not found', ${literal(id)};
+ END IF;
+
+ EXECUTE format(
+ 'ALTER TABLE %I.%I DROP COLUMN %I ${cascade ? 'CASCADE' : 'RESTRICT'}',
+ v_schema,
+ v_table,
+ v_column
+ );
+END $$;`
+
+ return { sql }
+}
+
+export default {
+ list,
+ retrieve,
+ create,
+ update,
+ remove,
+ zod: pgColumnZod,
+}
diff --git a/packages/pg-meta/src/pg-meta-foreign-tables.ts b/packages/pg-meta/src/pg-meta-foreign-tables.ts
new file mode 100644
index 00000000000..e8093fa6a14
--- /dev/null
+++ b/packages/pg-meta/src/pg-meta-foreign-tables.ts
@@ -0,0 +1,105 @@
+import { literal, ident } from './pg-format'
+import { z } from 'zod'
+import { DEFAULT_SYSTEM_SCHEMAS } from './constants'
+import { filterByList, coalesceRowsToArray } from './helpers'
+import { FOREIGN_TABLES_SQL } from './sql/foreign-tables'
+import { COLUMNS_SQL } from './sql/columns'
+import { pgColumnArrayZod } from './pg-meta-columns'
+
+export const pgForeignTableZod = z.object({
+ id: z.number(),
+ schema: z.string(),
+ name: z.string(),
+ comment: z.string().nullable(),
+ columns: pgColumnArrayZod.optional(),
+})
+
+export type PGForeignTable = z.infer<typeof pgForeignTableZod>
+
+export const pgForeignTableArrayZod = z.array(pgForeignTableZod)
+export const pgForeignTableOptionalZod = z.optional(pgForeignTableZod)
+
+type ForeignTableWithoutColumns = Omit<PGForeignTable, 'columns'>
+type ForeignTableWithColumns = PGForeignTable
+
+type ForeignTableBasedOnIncludeColumns<T extends boolean | undefined> = T extends true
+ ? ForeignTableWithColumns
+ : ForeignTableWithoutColumns
+
+export function list<T extends boolean | undefined = true>(
+ {
+ includeSystemSchemas = false,
+ includedSchemas,
+ excludedSchemas,
+ limit,
+ offset,
+ includeColumns = true as T,
+ }: {
+ includeSystemSchemas?: boolean
+ includedSchemas?: string[]
+ excludedSchemas?: string[]
+ limit?: number
+ offset?: number
+ includeColumns?: T
+ } = {} as any
+): {
+ sql: string
+ zod: z.ZodType<ForeignTableBasedOnIncludeColumns<T>[]>
+} {
+ let sql = generateEnrichedForeignTablesSql({ includeColumns })
+ const filter = filterByList(
+ includedSchemas,
+ excludedSchemas,
+ !includeSystemSchemas ? DEFAULT_SYSTEM_SCHEMAS : undefined
+ )
+ if (filter) {
+ sql += ` where schema ${filter}`
+ }
+ if (limit) {
+ sql += ` limit ${limit}`
+ }
+ if (offset) {
+ sql += ` offset ${offset}`
+ }
+ return {
+ sql,
+ zod: pgForeignTableArrayZod,
+ }
+}
+
+type ForeignTableIdentifier = Pick<PGForeignTable, 'id'> | Pick<PGForeignTable, 'name' | 'schema'>
+
+function getIdentifierWhereClause(identifier: ForeignTableIdentifier): string {
+ if ('id' in identifier && identifier.id) {
+ return `${ident('id')} = ${literal(identifier.id)}`
+ }
+ if ('name' in identifier && identifier.name && identifier.schema) {
+ return `${ident('name')} = ${literal(identifier.name)} and ${ident('schema')} = ${literal(identifier.schema)}`
+ }
+ throw new Error('Must provide either id or name and schema')
+}
+
+export function retrieve(identifier: ForeignTableIdentifier): {
+ sql: string
+ zod: typeof pgForeignTableOptionalZod
+} {
+ const sql = `${generateEnrichedForeignTablesSql({ includeColumns: true })} where ${getIdentifierWhereClause(identifier)};`
+ return {
+ sql,
+ zod: pgForeignTableOptionalZod,
+ }
+}
+
+const generateEnrichedForeignTablesSql = ({ includeColumns }: { includeColumns?: boolean }) => `
+with foreign_tables as (${FOREIGN_TABLES_SQL})
+ ${includeColumns ? `, columns as (${COLUMNS_SQL})` : ''}
+select
+ *
+ ${includeColumns ? `, ${coalesceRowsToArray('columns', 'columns.table_id = foreign_tables.id')}` : ''}
+from foreign_tables`
+
+export default {
+ list,
+ retrieve,
+ zod: pgForeignTableZod,
+}
diff --git a/packages/pg-meta/src/pg-meta-materialized-views.ts b/packages/pg-meta/src/pg-meta-materialized-views.ts
new file mode 100644
index 00000000000..2fd2f4fed6c
--- /dev/null
+++ b/packages/pg-meta/src/pg-meta-materialized-views.ts
@@ -0,0 +1,110 @@
+import { literal, ident } from './pg-format'
+import { z } from 'zod'
+import { DEFAULT_SYSTEM_SCHEMAS } from './constants'
+import { filterByList, coalesceRowsToArray } from './helpers'
+import { MATERIALIZED_VIEWS_SQL } from './sql/materialized-views'
+import { COLUMNS_SQL } from './sql/columns'
+import { pgColumnArrayZod } from './pg-meta-columns'
+
+export const pgMaterializedViewZod = z.object({
+ id: z.number(),
+ schema: z.string(),
+ name: z.string(),
+ is_populated: z.boolean(),
+ comment: z.string().nullable(),
+ columns: pgColumnArrayZod.optional(),
+})
+
+export type PGMaterializedView = z.infer<typeof pgMaterializedViewZod>
+
+export const pgMaterializedViewArrayZod = z.array(pgMaterializedViewZod)
+export const pgMaterializedViewOptionalZod = z.optional(pgMaterializedViewZod)
+
+type MaterializedViewWithoutColumns = Omit<PGMaterializedView, 'columns'>
+type MaterializedViewWithColumns = PGMaterializedView
+
+type MaterializedViewBasedOnIncludeColumns<T extends boolean | undefined> = T extends true
+ ? MaterializedViewWithColumns
+ : MaterializedViewWithoutColumns
+
+export function list<T extends boolean | undefined = true>(
+ {
+ includeSystemSchemas = false,
+ includedSchemas,
+ excludedSchemas,
+ limit,
+ offset,
+ includeColumns = true as T,
+ }: {
+ includeSystemSchemas?: boolean
+ includedSchemas?: string[]
+ excludedSchemas?: string[]
+ limit?: number
+ offset?: number
+ includeColumns?: T
+ } = {} as any
+): {
+ sql: string
+ zod: z.ZodType<MaterializedViewBasedOnIncludeColumns<T>[]>
+} {
+ let sql = generateEnrichedMaterializedViewsSql({ includeColumns })
+ const filter = filterByList(
+ includedSchemas,
+ excludedSchemas,
+ !includeSystemSchemas ? DEFAULT_SYSTEM_SCHEMAS : undefined
+ )
+ if (filter) {
+ sql += ` where schema ${filter}`
+ }
+ if (limit) {
+ sql += ` limit ${limit}`
+ }
+ if (offset) {
+ sql += ` offset ${offset}`
+ }
+ return {
+ sql,
+ zod: pgMaterializedViewArrayZod,
+ }
+}
+
+type MaterializedViewIdentifier =
+ | Pick<PGMaterializedView, 'id'>
+ | Pick<PGMaterializedView, 'name' | 'schema'>
+
+function getIdentifierWhereClause(identifier: MaterializedViewIdentifier): string {
+ if ('id' in identifier && identifier.id) {
+ return `${ident('id')} = ${literal(identifier.id)}`
+ }
+ if ('name' in identifier && identifier.name && identifier.schema) {
+ return `${ident('name')} = ${literal(identifier.name)} and ${ident('schema')} = ${literal(identifier.schema)}`
+ }
+ throw new Error('Must provide either id or name and schema')
+}
+
+export function retrieve(identifier: MaterializedViewIdentifier): {
+ sql: string
+ zod: typeof pgMaterializedViewOptionalZod
+} {
+ let whereClause = getIdentifierWhereClause(identifier)
+
+ const sql = `${generateEnrichedMaterializedViewsSql({ includeColumns: true })} where ${whereClause};`
+ return {
+ sql,
+ zod: pgMaterializedViewOptionalZod,
+ }
+}
+
+const generateEnrichedMaterializedViewsSql = ({ includeColumns }: { includeColumns?: boolean }) => `
+with materialized_views as (${MATERIALIZED_VIEWS_SQL})
+ ${includeColumns ? `, columns as (${COLUMNS_SQL})` : ''}
+select
+ *
+ ${includeColumns ? `, ${coalesceRowsToArray('columns', 'columns.table_id = materialized_views.id')}` : ''}
+from materialized_views`
+
+export default {
+ list,
+ retrieve,
+ zod: pgMaterializedViewZod,
+}
diff --git a/packages/pg-meta/src/pg-meta-tables.ts b/packages/pg-meta/src/pg-meta-tables.ts
new file mode 100644
index 00000000000..c1c73994bd9
--- /dev/null
+++ b/packages/pg-meta/src/pg-meta-tables.ts
@@ -0,0 +1,300 @@
+import { z } from 'zod'
+import { coalesceRowsToArray, exceptionIdentifierNotFound, filterByList } from './helpers'
+import { TABLES_SQL } from './sql/tables'
+import { COLUMNS_SQL } from './sql/columns'
+import { DEFAULT_SYSTEM_SCHEMAS } from './constants'
+import { ident, literal } from './pg-format'
+import { pgColumnArrayZod } from './pg-meta-columns'
+
+const pgTablePrimaryKeyZod = z.object({
+ table_id: z.number(),
+ name: z.string(),
+ schema: z.string(),
+ table_name: z.string(),
+})
+
+const pgTableRelationshipZod = z.object({
+ id: z.number(),
+ constraint_name: z.string(),
+ source_schema: z.string(),
+ source_table_name: z.string(),
+ source_column_name: z.string(),
+ target_table_schema: z.string(),
+ target_table_name: z.string(),
+ target_column_name: z.string(),
+})
+
+const pgTableZod = z.object({
+ id: z.number(),
+ schema: z.string(),
+ name: z.string(),
+ rls_enabled: z.boolean(),
+ rls_forced: z.boolean(),
+ replica_identity: z.enum(['DEFAULT', 'INDEX', 'FULL', 'NOTHING']),
+ bytes: z.number(),
+ size: z.string(),
+ live_rows_estimate: z.number(),
+ dead_rows_estimate: z.number(),
+ comment: z.string().nullable(),
+ primary_keys: z.array(pgTablePrimaryKeyZod),
+ relationships: z.array(pgTableRelationshipZod),
+ columns: pgColumnArrayZod.optional(),
+})
+
+const pgTableArrayZod = z.array(pgTableZod)
+
+export type PGTable = z.infer<typeof pgTableZod>
+
+type TableWithoutColumns = Omit<PGTable, 'columns'>
+type TableWithColumns = PGTable
+
+type TableBasedOnIncludeColumns<T extends boolean | undefined> = T extends true
+ ? TableWithColumns
+ : TableWithoutColumns
+
+type TableIdentifier = Pick<PGTable, 'id'> | Pick<PGTable, 'name' | 'schema'>
+
+function getIdentifierWhereClause(identifier: TableIdentifier): string {
+ if ('id' in identifier && identifier.id) {
+ return `${ident('id')} = ${literal(identifier.id)}`
+ }
+ if ('name' in identifier && identifier.name && identifier.schema) {
+ return `${ident('name')} = ${literal(identifier.name)} and ${ident('schema')} = ${literal(identifier.schema)}`
+ }
+ throw new Error('Must provide either id or name and schema')
+}
+
+function list<T extends boolean | undefined = true>(
+ {
+ includeSystemSchemas = false,
+ includedSchemas,
+ excludedSchemas,
+ limit,
+ offset,
+ includeColumns = true as T,
+ }: {
+ includeSystemSchemas?: boolean
+ includedSchemas?: string[]
+ excludedSchemas?: string[]
+ limit?: number
+ offset?: number
+ includeColumns?: T
+ } = {} as any
+): {
+ sql: string
+ zod: z.ZodType<TableBasedOnIncludeColumns<T>[]>
+} {
+ let sql = generateEnrichedTablesSql({ includeColumns })
+ const filter = filterByList(
+ includedSchemas,
+ excludedSchemas,
+ !includeSystemSchemas ? DEFAULT_SYSTEM_SCHEMAS : undefined
+ )
+ if (filter) {
+ sql += ` where schema ${filter}`
+ }
+ if (limit) {
+ sql += ` limit ${limit}`
+ }
+ if (offset) {
+ sql += ` offset ${offset}`
+ }
+ return {
+ sql,
+ zod: pgTableArrayZod,
+ }
+}
+
+function retrieve(identifier: TableIdentifier): {
+ sql: string
+ zod: z.ZodType<PGTable | undefined>
+} {
+ let whereClause = getIdentifierWhereClause(identifier)
+
+ const sql = `${generateEnrichedTablesSql({ includeColumns: true })} where ${whereClause};`
+ return {
+ sql,
+ zod: pgTableZod.optional(),
+ }
+}
+
+type TableRemoveParams = { cascade: boolean }
+function remove(
+ identifier: TableIdentifier,
+ params: TableRemoveParams = { cascade: false }
+): { sql: string } {
+ const whereClause = getIdentifierWhereClause(identifier)
+ const sql = `
+ do $$
+ declare
+ old record;
+ begin
+ with tables as (${generateEnrichedTablesSql({ includeColumns: false })})
+ select * into old from tables where ${whereClause};
+ if old is null then
+ ${exceptionIdentifierNotFound('table', whereClause)}
+ end if;
+ execute format('drop table %I.%I ${params.cascade ? 'cascade' : 'restrict'}', old.schema, old.name);
+ end
+ $$;
+ `
+ return { sql }
+}
+
+const generateEnrichedTablesSql = ({ includeColumns }: { includeColumns?: boolean }) => `
+ with tables as (${TABLES_SQL})
+ ${includeColumns ? `, columns as (${COLUMNS_SQL})` : ''}
+ select
+ *
+ ${includeColumns ? `, ${coalesceRowsToArray('columns', 'columns.table_id = tables.id')}` : ''}
+ from tables`
+
+type TableCreateParams = {
+ name: string
+ schema?: string
+ comment?: string
+}
+
+function create({ name, schema = 'public', comment }: TableCreateParams): { sql: string } {
+ const sql = `
+do $$
+begin
+ execute format('create table %I.%I ()', ${literal(schema)}, ${literal(name)});
+ ${
+ comment === undefined
+ ? ''
+ : `
+ execute format('comment on table %I.%I is %L', ${literal(schema)}, ${literal(name)}, ${literal(comment)});`
+ }
+end
+$$;`
+
+ return { sql }
+}
+
+type TableUpdateParams = {
+ name?: string
+ schema?: string
+ rls_enabled?: boolean
+ rls_forced?: boolean
+ replica_identity?: 'DEFAULT' | 'INDEX' | 'FULL' | 'NOTHING'
+ replica_identity_index?: string
+ primary_keys?: Array<{ name: string }>
+ comment?: string
+}
+
+function update(
+ identifier: TableIdentifier,
+ {
+ name,
+ schema,
+ rls_enabled,
+ rls_forced,
+ replica_identity,
+ replica_identity_index,
+ primary_keys,
+ comment,
+ }: TableUpdateParams
+): { sql: string } {
+ const sql = `
+DO $$
+DECLARE
+ v_table record;
+ r record;
+BEGIN
+ WITH tables AS (
+ ${generateEnrichedTablesSql({ includeColumns: false })}
+ )
+ SELECT *
+ INTO v_table
+ FROM tables
+ WHERE ${getIdentifierWhereClause(identifier)};
+
+ IF v_table IS NULL THEN
+ ${exceptionIdentifierNotFound('table', getIdentifierWhereClause(identifier))}
+ END IF;
+
+ ${
+ rls_enabled !== undefined
+ ? `execute format('ALTER TABLE %I.%I %s ROW LEVEL SECURITY',
+ v_table.schema, v_table.name,
+ CASE WHEN ${literal(rls_enabled)} THEN 'ENABLE' ELSE 'DISABLE' END);`
+ : ''
+ }
+
+ ${
+ rls_forced !== undefined
+ ? `execute format('ALTER TABLE %I.%I %s FORCE ROW LEVEL SECURITY',
+ v_table.schema, v_table.name,
+ CASE WHEN ${literal(rls_forced)} THEN '' ELSE 'NO' END);`
+ : ''
+ }
+
+ ${
+ replica_identity !== undefined
+ ? `execute format('ALTER TABLE %I.%I REPLICA IDENTITY %s%s',
+ v_table.schema, v_table.name,
+ ${literal(replica_identity)},
+ CASE WHEN ${literal(replica_identity)} = 'INDEX'
+ THEN format(' USING INDEX %I', ${literal(replica_identity_index!)})
+ ELSE '' END);`
+ : ''
+ }
+
+ ${
+ primary_keys !== undefined
+ ? `
+ -- Drop existing primary key if any
+ FOR r IN (
+ SELECT conname
+ FROM pg_constraint
+ WHERE conrelid = format('%I.%I', v_table.schema, v_table.name)::regclass
+ AND contype = 'p'
+ ) LOOP
+ execute format('ALTER TABLE %I.%I DROP CONSTRAINT %I',
+ v_table.schema, v_table.name, r.conname);
+ END LOOP;
+
+ ${
+ primary_keys.length > 0
+ ? `execute format('ALTER TABLE %I.%I ADD PRIMARY KEY (%s)',
+ v_table.schema, v_table.name,
+ ${literal(primary_keys.map((pk) => pk.name).join(', '))});`
+ : ''
+ }`
+ : ''
+ }
+
+ ${
+ comment !== undefined
+ ? `execute format('COMMENT ON TABLE %I.%I IS %L',
+ v_table.schema, v_table.name,
+ ${literal(comment)});`
+ : ''
+ }
+
+ ${
+ schema !== undefined
+ ? `execute format('ALTER TABLE %I.%I SET SCHEMA %I',
+ v_table.schema, v_table.name,
+ ${literal(schema)});`
+ : ''
+ }
+
+ ${
+ name !== undefined
+ ? `
+ if ${literal(name)} != v_table.name then
+ execute format('ALTER TABLE %I.%I RENAME TO %I',
+ ${schema !== undefined ? literal(schema) : 'v_table.schema'},
+ v_table.name,
+ ${literal(name)});
+ end if;`
+ : ''
+ }
+END $$;`
+
+ return { sql }
+}
+
+export { list, retrieve, remove, create, update }
diff --git a/packages/pg-meta/src/pg-meta-views.ts b/packages/pg-meta/src/pg-meta-views.ts
new file mode 100644
index 00000000000..7db45e321d4
--- /dev/null
+++ b/packages/pg-meta/src/pg-meta-views.ts
@@ -0,0 +1,108 @@
+import { literal, ident } from './pg-format'
+import { z } from 'zod'
+import { DEFAULT_SYSTEM_SCHEMAS } from './constants'
+import { filterByList, coalesceRowsToArray } from './helpers'
+import { VIEWS_SQL } from './sql/views'
+import { COLUMNS_SQL } from './sql/columns'
+import { pgColumnArrayZod } from './pg-meta-columns'
+
+export const pgViewZod = z.object({
+ id: z.number(),
+ schema: z.string(),
+ name: z.string(),
+ is_updatable: z.boolean(),
+ comment: z.string().nullable(),
+ columns: pgColumnArrayZod.optional(),
+})
+
+export type PGView = z.infer<typeof pgViewZod>
+
+export const pgViewArrayZod = z.array(pgViewZod)
+export const pgViewOptionalZod = z.optional(pgViewZod)
+
+type ViewWithoutColumns = Omit<PGView, 'columns'>
+type ViewWithColumns = PGView
+
+type ViewBasedOnIncludeColumns<T extends boolean | undefined> = T extends true
+ ? ViewWithColumns
+ : ViewWithoutColumns
+
+export function list<T extends boolean | undefined = true>(
+ {
+ includeSystemSchemas = false,
+ includedSchemas,
+ excludedSchemas,
+ limit,
+ offset,
+ includeColumns = true as T,
+ }: {
+ includeSystemSchemas?: boolean
+ includedSchemas?: string[]
+ excludedSchemas?: string[]
+ limit?: number
+ offset?: number
+ includeColumns?: T
+ } = {} as any
+): {
+ sql: string
+ zod: z.ZodType<ViewBasedOnIncludeColumns<T>[]>
+} {
+ let sql = generateEnrichedViewsSql({ includeColumns })
+ const filter = filterByList(
+ includedSchemas,
+ excludedSchemas,
+ !includeSystemSchemas ? DEFAULT_SYSTEM_SCHEMAS : undefined
+ )
+ if (filter) {
+ sql += ` where schema ${filter}`
+ }
+ if (limit) {
+ sql += ` limit ${limit}`
+ }
+ if (offset) {
+ sql += ` offset ${offset}`
+ }
+ return {
+ sql,
+ zod: pgViewArrayZod,
+ }
+}
+
+type ViewIdentifier = Pick<PGView, 'id'> | Pick<PGView, 'name' | 'schema'>
+
+function getIdentifierWhereClause(identifier: ViewIdentifier): string {
+ if ('id' in identifier && identifier.id) {
+ return `${ident('id')} = ${literal(identifier.id)}`
+ }
+ if ('name' in identifier && identifier.name && identifier.schema) {
+ return `${ident('name')} = ${literal(identifier.name)} and ${ident('schema')} = ${literal(identifier.schema)}`
+ }
+ throw new Error('Must provide either id or name and schema')
+}
+
+export function retrieve(identifier: ViewIdentifier): {
+ sql: string
+ zod: typeof pgViewOptionalZod
+} {
+ let whereClause = getIdentifierWhereClause(identifier)
+
+ const sql = `${generateEnrichedViewsSql({ includeColumns: true })} where ${whereClause};`
+ return {
+ sql,
+ zod: pgViewOptionalZod,
+ }
+}
+
+const generateEnrichedViewsSql = ({ includeColumns }: { includeColumns?: boolean }) => `
+with views as (${VIEWS_SQL})
+ ${includeColumns ? `, columns as (${COLUMNS_SQL})` : ''}
+select
+ *
+ ${includeColumns ? `, ${coalesceRowsToArray('columns', 'columns.table_id = views.id')}` : ''}
+from views`
+
+export default {
+ list,
+ retrieve,
+ zod: pgViewZod,
+}
diff --git a/packages/pg-meta/src/sql/columns.ts b/packages/pg-meta/src/sql/columns.ts
new file mode 100644
index 00000000000..251f8f99ec0
--- /dev/null
+++ b/packages/pg-meta/src/sql/columns.ts
@@ -0,0 +1,113 @@
+export const COLUMNS_SQL = /* SQL */ `
+-- Adapted from information_schema.columns
+
+SELECT
+ c.oid :: int8 AS table_id,
+ nc.nspname AS schema,
+ c.relname AS table,
+ (c.oid || '.' || a.attnum) AS id,
+ a.attnum AS ordinal_position,
+ a.attname AS name,
+ CASE
+ WHEN a.atthasdef THEN pg_get_expr(ad.adbin, ad.adrelid)
+ ELSE NULL
+ END AS default_value,
+ CASE
+ WHEN t.typtype = 'd' THEN CASE
+ WHEN bt.typelem <> 0 :: oid
+ AND bt.typlen = -1 THEN 'ARRAY'
+ WHEN nbt.nspname = 'pg_catalog' THEN format_type(t.typbasetype, NULL)
+ ELSE 'USER-DEFINED'
+ END
+ ELSE CASE
+ WHEN t.typelem <> 0 :: oid
+ AND t.typlen = -1 THEN 'ARRAY'
+ WHEN nt.nspname = 'pg_catalog' THEN format_type(a.atttypid, NULL)
+ ELSE 'USER-DEFINED'
+ END
+ END AS data_type,
+ COALESCE(bt.typname, t.typname) AS format,
+ a.attidentity IN ('a', 'd') AS is_identity,
+ CASE
+ a.attidentity
+ WHEN 'a' THEN 'ALWAYS'
+ WHEN 'd' THEN 'BY DEFAULT'
+ ELSE NULL
+ END AS identity_generation,
+ a.attgenerated IN ('s') AS is_generated,
+ NOT (
+ a.attnotnull
+ OR t.typtype = 'd' AND t.typnotnull
+ ) AS is_nullable,
+ (
+ c.relkind IN ('r', 'p')
+ OR c.relkind IN ('v', 'f') AND pg_column_is_updatable(c.oid, a.attnum, FALSE)
+ ) AS is_updatable,
+ uniques.table_id IS NOT NULL AS is_unique,
+ check_constraints.definition AS "check",
+ array_to_json(
+ array(
+ SELECT
+ enumlabel
+ FROM
+ pg_catalog.pg_enum enums
+ WHERE
+ enums.enumtypid = coalesce(bt.oid, t.oid)
+ OR enums.enumtypid = coalesce(bt.typelem, t.typelem)
+ ORDER BY
+ enums.enumsortorder
+ )
+ ) AS enums,
+ col_description(c.oid, a.attnum) AS comment
+FROM
+ pg_attribute a
+ LEFT JOIN pg_attrdef ad ON a.attrelid = ad.adrelid
+ AND a.attnum = ad.adnum
+ JOIN (
+ pg_class c
+ JOIN pg_namespace nc ON c.relnamespace = nc.oid
+ ) ON a.attrelid = c.oid
+ JOIN (
+ pg_type t
+ JOIN pg_namespace nt ON t.typnamespace = nt.oid
+ ) ON a.atttypid = t.oid
+ LEFT JOIN (
+ pg_type bt
+ JOIN pg_namespace nbt ON bt.typnamespace = nbt.oid
+ ) ON t.typtype = 'd'
+ AND t.typbasetype = bt.oid
+ LEFT JOIN (
+ SELECT DISTINCT ON (table_id, ordinal_position)
+ conrelid AS table_id,
+ conkey[1] AS ordinal_position
+ FROM pg_catalog.pg_constraint
+ WHERE contype = 'u' AND cardinality(conkey) = 1
+ ) AS uniques ON uniques.table_id = c.oid AND uniques.ordinal_position = a.attnum
+ LEFT JOIN (
+ -- We only select the first column check
+ SELECT DISTINCT ON (table_id, ordinal_position)
+ conrelid AS table_id,
+ conkey[1] AS ordinal_position,
+ substring(
+ pg_get_constraintdef(pg_constraint.oid, true),
+ 8,
+ length(pg_get_constraintdef(pg_constraint.oid, true)) - 8
+ ) AS "definition"
+ FROM pg_constraint
+ WHERE contype = 'c' AND cardinality(conkey) = 1
+ ORDER BY table_id, ordinal_position, oid asc
+ ) AS check_constraints ON check_constraints.table_id = c.oid AND check_constraints.ordinal_position = a.attnum
+WHERE
+ NOT pg_is_other_temp_schema(nc.oid)
+ AND a.attnum > 0
+ AND NOT a.attisdropped
+ AND (c.relkind IN ('r', 'v', 'm', 'f', 'p'))
+ AND (
+ pg_has_role(c.relowner, 'USAGE')
+ OR has_column_privilege(
+ c.oid,
+ a.attnum,
+ 'SELECT, INSERT, UPDATE, REFERENCES'
+ )
+ )
+`
diff --git a/packages/pg-meta/src/sql/foreign-tables.ts b/packages/pg-meta/src/sql/foreign-tables.ts
new file mode 100644
index 00000000000..2268bf7d24c
--- /dev/null
+++ b/packages/pg-meta/src/sql/foreign-tables.ts
@@ -0,0 +1,12 @@
+export const FOREIGN_TABLES_SQL = /* SQL */ `
+select
+ c.oid::int8 as id,
+ n.nspname as schema,
+ c.relname as name,
+ obj_description(c.oid) as comment
+from
+ pg_class c
+ join pg_namespace n on n.oid = c.relnamespace
+where
+ c.relkind = 'f'
+`
diff --git a/packages/pg-meta/src/sql/materialized-views.ts b/packages/pg-meta/src/sql/materialized-views.ts
new file mode 100644
index 00000000000..995127c93b7
--- /dev/null
+++ b/packages/pg-meta/src/sql/materialized-views.ts
@@ -0,0 +1,13 @@
+export const MATERIALIZED_VIEWS_SQL = /* SQL */ `
+select
+ c.oid::int8 as id,
+ n.nspname as schema,
+ c.relname as name,
+ c.relispopulated as is_populated,
+ obj_description(c.oid) as comment
+from
+ pg_class c
+ join pg_namespace n on n.oid = c.relnamespace
+where
+ c.relkind = 'm'
+`
diff --git a/packages/pg-meta/src/sql/tables.ts b/packages/pg-meta/src/sql/tables.ts
new file mode 100644
index 00000000000..3b08a0ae71c
--- /dev/null
+++ b/packages/pg-meta/src/sql/tables.ts
@@ -0,0 +1,100 @@
+export const TABLES_SQL = /* SQL */ `
+SELECT
+ c.oid :: int8 AS id,
+ nc.nspname AS schema,
+ c.relname AS name,
+ c.relrowsecurity AS rls_enabled,
+ c.relforcerowsecurity AS rls_forced,
+ CASE
+ WHEN c.relreplident = 'd' THEN 'DEFAULT'
+ WHEN c.relreplident = 'i' THEN 'INDEX'
+ WHEN c.relreplident = 'f' THEN 'FULL'
+ ELSE 'NOTHING'
+ END AS replica_identity,
+ pg_total_relation_size(format('%I.%I', nc.nspname, c.relname)) :: int8 AS bytes,
+ pg_size_pretty(
+ pg_total_relation_size(format('%I.%I', nc.nspname, c.relname))
+ ) AS size,
+ pg_stat_get_live_tuples(c.oid) AS live_rows_estimate,
+ pg_stat_get_dead_tuples(c.oid) AS dead_rows_estimate,
+ obj_description(c.oid) AS comment,
+ coalesce(pk.primary_keys, '[]') as primary_keys,
+ coalesce(
+ jsonb_agg(relationships) filter (where relationships is not null),
+ '[]'
+ ) as relationships
+FROM
+ pg_namespace nc
+ JOIN pg_class c ON nc.oid = c.relnamespace
+ left join (
+ select
+ table_id,
+ jsonb_agg(_pk.*) as primary_keys
+ from (
+ select
+ n.nspname as schema,
+ c.relname as table_name,
+ a.attname as name,
+ c.oid :: int8 as table_id
+ from
+ pg_index i,
+ pg_class c,
+ pg_attribute a,
+ pg_namespace n
+ where
+ i.indrelid = c.oid
+ and c.relnamespace = n.oid
+ and a.attrelid = c.oid
+ and a.attnum = any (i.indkey)
+ and i.indisprimary
+ ) as _pk
+ group by table_id
+ ) as pk
+ on pk.table_id = c.oid
+ left join (
+ select
+ 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_attribute sa
+ join pg_class csa on sa.attrelid = csa.oid
+ join pg_namespace nsa on csa.relnamespace = nsa.oid
+ ) on sa.attrelid = c.conrelid and sa.attnum = any (c.conkey)
+ join (
+ pg_attribute ta
+ join pg_class cta on ta.attrelid = cta.oid
+ join pg_namespace nta on cta.relnamespace = nta.oid
+ ) on ta.attrelid = c.confrelid and ta.attnum = any (c.confkey)
+ where
+ c.contype = 'f'
+ ) as relationships
+ on (relationships.source_schema = nc.nspname and relationships.source_table_name = c.relname)
+ or (relationships.target_table_schema = nc.nspname and relationships.target_table_name = c.relname)
+WHERE
+ c.relkind IN ('r', 'p')
+ AND NOT pg_is_other_temp_schema(nc.oid)
+ 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')
+ )
+group by
+ c.oid,
+ c.relname,
+ c.relrowsecurity,
+ c.relforcerowsecurity,
+ c.relreplident,
+ nc.nspname,
+ pk.primary_keys
+`
diff --git a/packages/pg-meta/src/sql/views.ts b/packages/pg-meta/src/sql/views.ts
new file mode 100644
index 00000000000..1dfcbdc0d02
--- /dev/null
+++ b/packages/pg-meta/src/sql/views.ts
@@ -0,0 +1,13 @@
+export const VIEWS_SQL = /* SQL */ `
+SELECT
+ c.oid :: int8 AS id,
+ n.nspname AS schema,
+ c.relname AS name,
+ (pg_relation_is_updatable(c.oid, false) & 20) = 20 AS is_updatable,
+ obj_description(c.oid) AS comment
+FROM
+ pg_class c
+ JOIN pg_namespace n ON n.oid = c.relnamespace
+WHERE
+ c.relkind = 'v'
+`
diff --git a/packages/pg-meta/test/columns.test.ts b/packages/pg-meta/test/columns.test.ts
new file mode 100644
index 00000000000..f2088abb7ea
--- /dev/null
+++ b/packages/pg-meta/test/columns.test.ts
@@ -0,0 +1,875 @@
+import { test, beforeAll, afterAll, expect } from 'vitest'
+import pgMeta from '../src/index'
+import { createTestDatabase, cleanupRoot } from './db/utils'
+
+beforeAll(async () => {
+ // Any global setup if needed
+})
+
+afterAll(async () => {
+ await cleanupRoot()
+})
+
+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('list columns', async ({ executeQuery }) => {
+ const { sql, zod } = await pgMeta.columns.list()
+ const res = zod.parse(await executeQuery(sql))
+
+ const userIdColumn = res.find(({ name }) => name === 'user-id')
+ expect(userIdColumn).toMatchInlineSnapshot(
+ {
+ id: expect.stringMatching(/^\d+\.3$/),
+ table_id: expect.any(Number),
+ },
+ `
+ {
+ "check": null,
+ "comment": null,
+ "data_type": "bigint",
+ "default_value": null,
+ "enums": [],
+ "format": "int8",
+ "id": StringMatching /\\^\\\\d\\+\\\\\\.3\\$/,
+ "identity_generation": null,
+ "is_generated": false,
+ "is_identity": false,
+ "is_nullable": false,
+ "is_unique": false,
+ "is_updatable": true,
+ "name": "user-id",
+ "ordinal_position": 3,
+ "schema": "public",
+ "table": "todos",
+ "table_id": Any<Number>,
+ }
+ `
+ )
+})
+
+withTestDatabase('list columns from a single table', async ({ executeQuery }) => {
+ // Create test table
+ await executeQuery('CREATE TABLE t (c1 text, c2 text)')
+
+ // Get the table ID directly
+ const tableId = Number(
+ (
+ await executeQuery(
+ "SELECT oid FROM pg_class WHERE relname = 't' AND relnamespace = (SELECT oid FROM pg_namespace WHERE nspname = 'public')"
+ )
+ )[0].oid
+ )
+ const testTable = { id: tableId, name: 't', schema: 'public' }
+
+ // List columns
+ const { sql, zod } = await pgMeta.columns.list({ tableId: testTable.id })
+ const res = zod.parse(await executeQuery(sql))
+
+ expect(res).toMatchInlineSnapshot(
+ [
+ {
+ id: expect.stringMatching(/^\d+\.\d+$/),
+ table_id: expect.any(Number),
+ },
+ {
+ id: expect.stringMatching(/^\d+\.\d+$/),
+ table_id: expect.any(Number),
+ },
+ ],
+ `
+ [
+ {
+ "check": null,
+ "comment": null,
+ "data_type": "text",
+ "default_value": null,
+ "enums": [],
+ "format": "text",
+ "id": StringMatching /\\^\\\\d\\+\\\\\\.\\\\d\\+\\$/,
+ "identity_generation": null,
+ "is_generated": false,
+ "is_identity": false,
+ "is_nullable": true,
+ "is_unique": false,
+ "is_updatable": true,
+ "name": "c1",
+ "ordinal_position": 1,
+ "schema": "public",
+ "table": "t",
+ "table_id": Any<Number>,
+ },
+ {
+ "check": null,
+ "comment": null,
+ "data_type": "text",
+ "default_value": null,
+ "enums": [],
+ "format": "text",
+ "id": StringMatching /\\^\\\\d\\+\\\\\\.\\\\d\\+\\$/,
+ "identity_generation": null,
+ "is_generated": false,
+ "is_identity": false,
+ "is_nullable": true,
+ "is_unique": false,
+ "is_updatable": true,
+ "name": "c2",
+ "ordinal_position": 2,
+ "schema": "public",
+ "table": "t",
+ "table_id": Any<Number>,
+ },
+ ]
+ `
+ )
+})
+
+withTestDatabase('list columns with included schemas', async ({ executeQuery }) => {
+ const { sql, zod } = await pgMeta.columns.list({
+ includedSchemas: ['public'],
+ })
+ const res = zod.parse(await executeQuery(sql))
+
+ expect(res.length).toBeGreaterThan(0)
+ res.forEach((column) => {
+ expect(column.schema).toBe('public')
+ })
+})
+
+withTestDatabase('list columns with excluded schemas', async ({ executeQuery }) => {
+ const { sql, zod } = await pgMeta.columns.list({
+ excludedSchemas: ['public'],
+ })
+ const res = zod.parse(await executeQuery(sql))
+
+ res.forEach((column) => {
+ expect(column.schema).not.toBe('public')
+ })
+})
+
+withTestDatabase(
+ 'list columns with excluded schemas and include System Schemas',
+ async ({ executeQuery }) => {
+ const { sql, zod } = await pgMeta.columns.list({
+ excludedSchemas: ['public'],
+ includeSystemSchemas: true,
+ })
+ const res = zod.parse(await executeQuery(sql))
+
+ expect(res.length).toBeGreaterThan(0)
+ res.forEach((column) => {
+ expect(column.schema).not.toBe('public')
+ })
+ }
+)
+
+withTestDatabase('retrieve, create, update, delete column', async ({ executeQuery }) => {
+ // Create test table using pure SQL
+ await executeQuery('CREATE TABLE t ()')
+
+ // Get table ID
+ const tableId = Number(
+ (
+ await executeQuery(
+ "SELECT oid FROM pg_class WHERE relname = 't' AND relnamespace = (SELECT oid FROM pg_namespace WHERE nspname = 'public')"
+ )
+ )[0].oid
+ )
+
+ // Create column
+ const { sql: createColumnSql } = await pgMeta.columns.create({
+ table_id: tableId,
+ name: 'c',
+ type: 'int2',
+ default_value: 42,
+ comment: 'foo',
+ })
+ await executeQuery(createColumnSql)
+
+ // Retrieve and verify created column
+ const { sql: retrieveSql, zod: retrieveZod } = await pgMeta.columns.retrieve({
+ schema: 'public',
+ table: 't',
+ name: 'c',
+ })
+ let column = retrieveZod.parse((await executeQuery(retrieveSql))[0])
+ expect(column).toMatchInlineSnapshot(
+ {
+ id: expect.stringMatching(/^\d+\.1$/),
+ table_id: expect.any(Number),
+ },
+ `
+ {
+ "check": null,
+ "comment": "foo",
+ "data_type": "smallint",
+ "default_value": "'42'::smallint",
+ "enums": [],
+ "format": "int2",
+ "id": StringMatching /\\^\\\\d\\+\\\\\\.1\\$/,
+ "identity_generation": null,
+ "is_generated": false,
+ "is_identity": false,
+ "is_nullable": true,
+ "is_unique": false,
+ "is_updatable": true,
+ "name": "c",
+ "ordinal_position": 1,
+ "schema": "public",
+ "table": "t",
+ "table_id": Any<Number>,
+ }
+ `
+ )
+
+ // Update column
+ const { sql: updateSql } = await pgMeta.columns.update(column!.id, {
+ name: 'c1',
+ type: 'int4',
+ drop_default: true,
+ is_identity: true,
+ identity_generation: 'ALWAYS',
+ is_nullable: false,
+ comment: 'bar',
+ })
+ await executeQuery(updateSql)
+
+ // Verify updated column
+ const { sql: retrieveUpdatedSql, zod: retrieveUpdatedZod } = await pgMeta.columns.retrieve({
+ schema: 'public',
+ table: 't',
+ name: 'c1',
+ })
+ column = retrieveUpdatedZod.parse((await executeQuery(retrieveUpdatedSql))[0])
+ expect(column).toMatchInlineSnapshot(
+ {
+ id: expect.stringMatching(/^\d+\.1$/),
+ table_id: expect.any(Number),
+ },
+ `
+ {
+ "check": null,
+ "comment": "bar",
+ "data_type": "integer",
+ "default_value": null,
+ "enums": [],
+ "format": "int4",
+ "id": StringMatching /\\^\\\\d\\+\\\\\\.1\\$/,
+ "identity_generation": "ALWAYS",
+ "is_generated": false,
+ "is_identity": true,
+ "is_nullable": false,
+ "is_unique": false,
+ "is_updatable": true,
+ "name": "c1",
+ "ordinal_position": 1,
+ "schema": "public",
+ "table": "t",
+ "table_id": Any<Number>,
+ }
+ `
+ )
+
+ // Remove column
+ const { sql: removeSql } = await pgMeta.columns.remove(column!.id)
+ await executeQuery(removeSql)
+
+ // Verify column was removed
+ const { sql: retrieveRemovedSql, zod: retrieveRemovedZod } = await pgMeta.columns.retrieve({
+ schema: 'public',
+ table: 't',
+ name: 'c1',
+ })
+ const removedColumn = retrieveRemovedZod.parse((await executeQuery(retrieveRemovedSql))[0])
+ expect(removedColumn).toBeUndefined()
+})
+
+withTestDatabase('enum column with quoted name', async ({ executeQuery }) => {
+ await executeQuery('CREATE TYPE "T" AS ENUM (\'v\'); CREATE TABLE t ( c "T" );')
+
+ const { sql, zod } = await pgMeta.columns.list()
+ const res = zod.parse(await executeQuery(sql))
+
+ expect(res.find(({ table }) => table === 't')).toMatchInlineSnapshot(
+ {
+ id: expect.stringMatching(/^\d+\.1$/),
+ table_id: expect.any(Number),
+ },
+ `
+ {
+ "check": null,
+ "comment": null,
+ "data_type": "USER-DEFINED",
+ "default_value": null,
+ "enums": [
+ "v",
+ ],
+ "format": "T",
+ "id": StringMatching /\\^\\\\d\\+\\\\\\.1\\$/,
+ "identity_generation": null,
+ "is_generated": false,
+ "is_identity": false,
+ "is_nullable": true,
+ "is_unique": false,
+ "is_updatable": true,
+ "name": "c",
+ "ordinal_position": 1,
+ "schema": "public",
+ "table": "t",
+ "table_id": Any<Number>,
+ }
+ `
+ )
+})
+
+withTestDatabase('primary key column', async ({ executeQuery }) => {
+ // Create test table using pure SQL
+ await executeQuery('CREATE TABLE t ()')
+
+ // Get table ID
+ const tableId = Number(
+ (
+ await executeQuery(
+ "SELECT oid FROM pg_class WHERE relname = 't' AND relnamespace = (SELECT oid FROM pg_namespace WHERE nspname = 'public')"
+ )
+ )[0].oid
+ )
+
+ // Create column with primary key
+ const { sql: createColumnSql } = await pgMeta.columns.create({
+ table_id: tableId,
+ name: 'c',
+ type: 'int2',
+ is_primary_key: true,
+ })
+ await executeQuery(createColumnSql)
+
+ // Verify primary key using pure SQL
+ const primaryKeyResult = await executeQuery(`
+ SELECT a.attname
+ FROM pg_index i
+ JOIN pg_attribute a ON a.attrelid = i.indrelid
+ AND a.attnum = ANY(i.indkey)
+ WHERE i.indrelid = 't'::regclass
+ AND i.indisprimary;
+ `)
+
+ expect(primaryKeyResult).toMatchInlineSnapshot(`
+ [
+ {
+ "attname": "c",
+ },
+ ]
+ `)
+})
+
+withTestDatabase('unique column', async ({ executeQuery }) => {
+ // Create test table using pure SQL
+ await executeQuery('CREATE TABLE t ()')
+
+ // Get table ID
+ const tableId = Number(
+ (
+ await executeQuery(
+ "SELECT oid FROM pg_class WHERE relname = 't' AND relnamespace = (SELECT oid FROM pg_namespace WHERE nspname = 'public')"
+ )
+ )[0].oid
+ )
+
+ // Create column with unique constraint
+ const { sql: createColumnSql } = await pgMeta.columns.create({
+ table_id: tableId,
+ name: 'c',
+ type: 'int2',
+ is_unique: true,
+ })
+ await executeQuery(createColumnSql)
+
+ // Verify unique constraint using pure SQL
+ const uniqueResult = await executeQuery(`
+ SELECT a.attname
+ FROM pg_index i
+ JOIN pg_constraint c ON c.conindid = i.indexrelid
+ JOIN pg_attribute a ON a.attrelid = i.indrelid
+ AND a.attnum = ANY(i.indkey)
+ WHERE i.indrelid = 't'::regclass
+ AND i.indisunique;
+ `)
+
+ expect(uniqueResult).toMatchInlineSnapshot(`
+ [
+ {
+ "attname": "c",
+ },
+ ]
+ `)
+})
+
+withTestDatabase('array column', async ({ executeQuery }) => {
+ // Create test table using pure SQL
+ await executeQuery('CREATE TABLE t ()')
+
+ // Get table ID
+ const tableId = Number(
+ (
+ await executeQuery(
+ "SELECT oid FROM pg_class WHERE relname = 't' AND relnamespace = (SELECT oid FROM pg_namespace WHERE nspname = 'public')"
+ )
+ )[0].oid
+ )
+
+ // Create array column
+ const { sql: createColumnSql } = await pgMeta.columns.create({
+ table_id: tableId,
+ name: 'c',
+ type: 'int2[]',
+ })
+ await executeQuery(createColumnSql)
+
+ // Retrieve and verify the created column
+ const { sql: retrieveSql, zod: retrieveZod } = await pgMeta.columns.retrieve({
+ schema: 'public',
+ table: 't',
+ name: 'c',
+ })
+ const column = retrieveZod.parse((await executeQuery(retrieveSql))[0])
+
+ expect(column).toMatchInlineSnapshot(
+ {
+ id: expect.stringMatching(/^\d+\.1$/),
+ table_id: expect.any(Number),
+ },
+ `
+ {
+ "check": null,
+ "comment": null,
+ "data_type": "ARRAY",
+ "default_value": null,
+ "enums": [],
+ "format": "_int2",
+ "id": StringMatching /\\^\\\\d\\+\\\\\\.1\\$/,
+ "identity_generation": null,
+ "is_generated": false,
+ "is_identity": false,
+ "is_nullable": true,
+ "is_unique": false,
+ "is_updatable": true,
+ "name": "c",
+ "ordinal_position": 1,
+ "schema": "public",
+ "table": "t",
+ "table_id": Any<Number>,
+ }
+ `
+ )
+})
+
+withTestDatabase('column with default value', async ({ executeQuery }) => {
+ // Create test table using pure SQL
+ await executeQuery('CREATE TABLE t ()')
+
+ // Get table ID
+ const tableId = Number(
+ (
+ await executeQuery(
+ "SELECT oid FROM pg_class WHERE relname = 't' AND relnamespace = (SELECT oid FROM pg_namespace WHERE nspname = 'public')"
+ )
+ )[0].oid
+ )
+
+ // Create column with default value
+ const { sql: createColumnSql } = await pgMeta.columns.create({
+ table_id: tableId,
+ name: 'c',
+ type: 'timestamptz',
+ default_value: 'NOW()',
+ default_value_format: 'expression',
+ })
+ await executeQuery(createColumnSql)
+
+ // Retrieve and verify the created column
+ const { sql: retrieveSql, zod: retrieveZod } = await pgMeta.columns.retrieve({
+ schema: 'public',
+ table: 't',
+ name: 'c',
+ })
+ const column = retrieveZod.parse((await executeQuery(retrieveSql))[0])
+
+ expect(column).toMatchInlineSnapshot(
+ {
+ id: expect.stringMatching(/^\d+\.1$/),
+ table_id: expect.any(Number),
+ },
+ `
+ {
+ "check": null,
+ "comment": null,
+ "data_type": "timestamp with time zone",
+ "default_value": "now()",
+ "enums": [],
+ "format": "timestamptz",
+ "id": StringMatching /\\^\\\\d\\+\\\\\\.1\\$/,
+ "identity_generation": null,
+ "is_generated": false,
+ "is_identity": false,
+ "is_nullable": true,
+ "is_unique": false,
+ "is_updatable": true,
+ "name": "c",
+ "ordinal_position": 1,
+ "schema": "public",
+ "table": "t",
+ "table_id": Any<Number>,
+ }
+ `
+ )
+})
+
+// https://github.com/supabase/supabase/issues/3553
+withTestDatabase('alter column to type with uppercase', async ({ executeQuery }) => {
+ // Setup: Create table and type
+ await executeQuery('CREATE TABLE t ()')
+ await executeQuery('CREATE TYPE "T" AS ENUM ()')
+
+ // Get table ID
+ const tableId = Number(
+ (
+ await executeQuery(
+ "SELECT oid FROM pg_class WHERE relname = 't' AND relnamespace = (SELECT oid FROM pg_namespace WHERE nspname = 'public')"
+ )
+ )[0].oid
+ )
+
+ // Create and then update column
+ const { sql: createSql } = await pgMeta.columns.create({
+ table_id: tableId,
+ name: 'c',
+ type: 'text',
+ is_unique: false,
+ })
+ await executeQuery(createSql)
+
+ // Get column ID
+ const { sql: retrieveSql, zod: retrieveZod } = await pgMeta.columns.retrieve({
+ schema: 'public',
+ table: 't',
+ name: 'c',
+ })
+ const column = retrieveZod.parse((await executeQuery(retrieveSql))[0])
+
+ // Update column
+ const { sql: updateSql } = await pgMeta.columns.update(column!.id, { type: 'T' })
+ await executeQuery(updateSql)
+
+ // Verify updated column
+ const { sql: verifySQL, zod: verifyZod } = await pgMeta.columns.retrieve({
+ schema: 'public',
+ table: 't',
+ name: 'c',
+ })
+ const updatedColumn = verifyZod.parse((await executeQuery(verifySQL))[0])
+
+ expect(updatedColumn).toMatchInlineSnapshot(
+ {
+ id: expect.stringMatching(/^\d+\.1$/),
+ table_id: expect.any(Number),
+ },
+ `
+ {
+ "check": null,
+ "comment": null,
+ "data_type": "USER-DEFINED",
+ "default_value": null,
+ "enums": [],
+ "format": "T",
+ "id": StringMatching /\\^\\\\d\\+\\\\\\.1\\$/,
+ "identity_generation": null,
+ "is_generated": false,
+ "is_identity": false,
+ "is_nullable": true,
+ "is_unique": false,
+ "is_updatable": true,
+ "name": "c",
+ "ordinal_position": 1,
+ "schema": "public",
+ "table": "t",
+ "table_id": Any<Number>,
+ }
+ `
+ )
+})
+
+withTestDatabase('enums are populated in enum array columns', async ({ executeQuery }) => {
+ // Setup: Create type and table
+ await executeQuery(`CREATE TYPE test_enum AS ENUM ('a')`)
+ await executeQuery('CREATE TABLE t ()')
+
+ // Get table ID
+ const tableId = Number(
+ (
+ await executeQuery(
+ "SELECT oid FROM pg_class WHERE relname = 't' AND relnamespace = (SELECT oid FROM pg_namespace WHERE nspname = 'public')"
+ )
+ )[0].oid
+ )
+
+ // Create column
+ const { sql: createSql } = await pgMeta.columns.create({
+ table_id: tableId,
+ name: 'c',
+ type: '_test_enum',
+ })
+ await executeQuery(createSql)
+
+ // Verify created column
+ const { sql: verifySql, zod: verifyZod } = await pgMeta.columns.retrieve({
+ schema: 'public',
+ table: 't',
+ name: 'c',
+ })
+ const column = verifyZod.parse((await executeQuery(verifySql))[0])
+
+ expect(column).toMatchInlineSnapshot(
+ {
+ id: expect.stringMatching(/^\d+\.1$/),
+ table_id: expect.any(Number),
+ },
+ `
+ {
+ "check": null,
+ "comment": null,
+ "data_type": "ARRAY",
+ "default_value": null,
+ "enums": [
+ "a",
+ ],
+ "format": "_test_enum",
+ "id": StringMatching /\\^\\\\d\\+\\\\\\.1\\$/,
+ "identity_generation": null,
+ "is_generated": false,
+ "is_identity": false,
+ "is_nullable": true,
+ "is_unique": false,
+ "is_updatable": true,
+ "name": "c",
+ "ordinal_position": 1,
+ "schema": "public",
+ "table": "t",
+ "table_id": Any<Number>,
+ }
+ `
+ )
+})
+
+withTestDatabase('drop with cascade', async ({ executeQuery }) => {
+ // Setup table with generated column
+ await executeQuery(`
+ create table public.t (
+ id int8 primary key,
+ t_id int8 generated always as (id) stored
+ );
+ `)
+
+ // Retrieve column
+ const { sql: retrieveSql, zod: retrieveZod } = await pgMeta.columns.retrieve({
+ schema: 'public',
+ table: 't',
+ name: 'id',
+ })
+ const column = retrieveZod.parse((await executeQuery(retrieveSql))[0])
+
+ // Remove column with cascade
+ const { sql: removeSql } = await pgMeta.columns.remove(column!.id, { cascade: true })
+ await executeQuery(removeSql)
+
+ // Verify original column was removed
+ const { sql: verifyIdSql, zod: verifyIdZod } = await pgMeta.columns.retrieve({
+ schema: 'public',
+ table: 't',
+ name: 'id',
+ })
+ const removedColumn = verifyIdZod.parse((await executeQuery(verifyIdSql))[0])
+ expect(removedColumn).toBeUndefined()
+
+ // Verify dependent column was also removed
+ const { sql: verifyTIdSql, zod: verifyTIdZod } = await pgMeta.columns.retrieve({
+ schema: 'public',
+ table: 't',
+ name: 't_id',
+ })
+ const dependentColumn = verifyTIdZod.parse((await executeQuery(verifyTIdSql))[0])
+ expect(dependentColumn).toBeUndefined()
+})
+
+withTestDatabase('column with multiple checks', async ({ executeQuery }) => {
+ // Setup table with multiple check constraints
+ await executeQuery('create table t(c int8 check (c != 0) check (c != -1))')
+
+ // List columns
+ const { sql, zod } = await pgMeta.columns.list()
+ const res = zod.parse(await executeQuery(sql))
+
+ const columns = res
+ .filter((c) => c.schema === 'public' && c.table === 't')
+ .map(({ id, table_id, ...c }) => c)
+
+ expect(columns).toMatchInlineSnapshot(`
+ [
+ {
+ "check": "c <> 0",
+ "comment": null,
+ "data_type": "bigint",
+ "default_value": null,
+ "enums": [],
+ "format": "int8",
+ "identity_generation": null,
+ "is_generated": false,
+ "is_identity": false,
+ "is_nullable": true,
+ "is_unique": false,
+ "is_updatable": true,
+ "name": "c",
+ "ordinal_position": 1,
+ "schema": "public",
+ "table": "t",
+ },
+ ]
+ `)
+})
+
+withTestDatabase('column with multiple unique constraints', async ({ executeQuery }) => {
+ // Setup table with multiple unique constraints
+ await executeQuery(`create table t(c int8 unique); alter table t add unique (c);`)
+
+ // List columns
+ const { sql, zod } = await pgMeta.columns.list()
+ const res = zod.parse(await executeQuery(sql))
+
+ const columns = res
+ .filter((c) => c.schema === 'public' && c.table === 't')
+ .map(({ id, table_id, ...c }) => c)
+
+ expect(columns).toMatchInlineSnapshot(`
+ [
+ {
+ "check": null,
+ "comment": null,
+ "data_type": "bigint",
+ "default_value": null,
+ "enums": [],
+ "format": "int8",
+ "identity_generation": null,
+ "is_generated": false,
+ "is_identity": false,
+ "is_nullable": true,
+ "is_unique": true,
+ "is_updatable": true,
+ "name": "c",
+ "ordinal_position": 1,
+ "schema": "public",
+ "table": "t",
+ },
+ ]
+ `)
+})
+
+withTestDatabase('dropping column checks', async ({ executeQuery }) => {
+ // Setup table with check constraint
+ await executeQuery(`create table public.t(c int8 check (c != 0))`)
+
+ // Retrieve column
+ const { sql: retrieveSql, zod: retrieveZod } = await pgMeta.columns.retrieve({
+ schema: 'public',
+ table: 't',
+ name: 'c',
+ })
+ const column = retrieveZod.parse((await executeQuery(retrieveSql))[0])
+
+ // Update column to remove check
+ const { sql: updateSql } = await pgMeta.columns.update(column!.id, { check: null })
+ await executeQuery(updateSql)
+
+ // Verify updated column
+ const { sql: verifySql, zod: verifyZod } = await pgMeta.columns.retrieve({
+ schema: 'public',
+ table: 't',
+ name: 'c',
+ })
+ const updatedColumn = verifyZod.parse((await executeQuery(verifySql))[0])
+
+ expect(updatedColumn!.check).toMatchInlineSnapshot(`null`)
+})
+
+withTestDatabase('column with fully-qualified type', async ({ executeQuery }) => {
+ // Setup: Create table and type in separate schema
+ await executeQuery(`
+ create table public.t();
+ create schema s;
+ create type s.my_type as enum ();
+ `)
+
+ // Get table ID using pure SQL
+ const tableId = Number(
+ (
+ await executeQuery(
+ "SELECT oid FROM pg_class WHERE relname = 't' AND relnamespace = (SELECT oid FROM pg_namespace WHERE nspname = 'public')"
+ )
+ )[0].oid
+ )
+
+ // Create column with fully-qualified type
+ const { sql: createColumnSql } = await pgMeta.columns.create({
+ table_id: tableId,
+ name: 'c',
+ type: 's.my_type',
+ })
+ await executeQuery(createColumnSql)
+
+ // Retrieve and verify the created column
+ const { sql: retrieveSql, zod: retrieveZod } = await pgMeta.columns.retrieve({
+ schema: 'public',
+ table: 't',
+ name: 'c',
+ })
+ const column = retrieveZod.parse((await executeQuery(retrieveSql))[0])
+
+ expect(column).toMatchInlineSnapshot(
+ {
+ id: expect.stringMatching(/^\d+\.1$/),
+ table_id: expect.any(Number),
+ },
+ `
+ {
+ "check": null,
+ "comment": null,
+ "data_type": "USER-DEFINED",
+ "default_value": null,
+ "enums": [],
+ "format": "my_type",
+ "id": StringMatching /\\^\\\\d\\+\\\\\\.1\\$/,
+ "identity_generation": null,
+ "is_generated": false,
+ "is_identity": false,
+ "is_nullable": true,
+ "is_unique": false,
+ "is_updatable": true,
+ "name": "c",
+ "ordinal_position": 1,
+ "schema": "public",
+ "table": "t",
+ "table_id": Any<Number>,
+ }
+ `
+ )
+})
diff --git a/packages/pg-meta/test/foreign-tables.test.ts b/packages/pg-meta/test/foreign-tables.test.ts
new file mode 100644
index 00000000000..2145ee96c05
--- /dev/null
+++ b/packages/pg-meta/test/foreign-tables.test.ts
@@ -0,0 +1,291 @@
+import { expect, test, beforeAll, afterAll } from 'vitest'
+import pgMeta from '../src/index'
+import { createTestDatabase, cleanupRoot } from './db/utils'
+
+beforeAll(async () => {
+ // Any global setup if needed
+})
+
+afterAll(async () => {
+ await cleanupRoot()
+})
+
+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('list foreign tables', async ({ executeQuery }) => {
+ const { sql: listSql, zod: listZod } = pgMeta.foreignTables.list()
+ const tables = listZod.parse(await executeQuery(listSql))
+ const foreignTable = tables.find(({ name }) => name === 'foreign_table')
+ expect(foreignTable).toMatchInlineSnapshot(
+ { id: expect.any(Number) },
+ `
+ {
+ "columns": [
+ {
+ "check": null,
+ "comment": null,
+ "data_type": "bigint",
+ "default_value": null,
+ "enums": [],
+ "format": "int8",
+ "id": "16451.1",
+ "identity_generation": null,
+ "is_generated": false,
+ "is_identity": false,
+ "is_nullable": false,
+ "is_unique": false,
+ "is_updatable": true,
+ "name": "id",
+ "ordinal_position": 1,
+ "schema": "public",
+ "table": "foreign_table",
+ "table_id": 16451,
+ },
+ {
+ "check": null,
+ "comment": null,
+ "data_type": "text",
+ "default_value": null,
+ "enums": [],
+ "format": "text",
+ "id": "16451.2",
+ "identity_generation": null,
+ "is_generated": false,
+ "is_identity": false,
+ "is_nullable": true,
+ "is_unique": false,
+ "is_updatable": true,
+ "name": "name",
+ "ordinal_position": 2,
+ "schema": "public",
+ "table": "foreign_table",
+ "table_id": 16451,
+ },
+ {
+ "check": null,
+ "comment": null,
+ "data_type": "USER-DEFINED",
+ "default_value": null,
+ "enums": [
+ "ACTIVE",
+ "INACTIVE",
+ ],
+ "format": "user_status",
+ "id": "16451.3",
+ "identity_generation": null,
+ "is_generated": false,
+ "is_identity": false,
+ "is_nullable": true,
+ "is_unique": false,
+ "is_updatable": true,
+ "name": "status",
+ "ordinal_position": 3,
+ "schema": "public",
+ "table": "foreign_table",
+ "table_id": 16451,
+ },
+ ],
+ "comment": null,
+ "id": Any<Number>,
+ "name": "foreign_table",
+ "schema": "public",
+ }
+ `
+ )
+})
+
+withTestDatabase('list foreign tables without columns', async ({ executeQuery }) => {
+ const { sql: listSql, zod: listZod } = pgMeta.foreignTables.list({ includeColumns: false })
+ const tables = listZod.parse(await executeQuery(listSql))
+ const foreignTable = tables.find(({ name }) => name === 'foreign_table')
+ expect(foreignTable).toMatchInlineSnapshot(
+ { id: expect.any(Number) },
+ `
+ {
+ "comment": null,
+ "id": Any<Number>,
+ "name": "foreign_table",
+ "schema": "public",
+ }
+ `
+ )
+})
+
+withTestDatabase('retrieve foreign table by name', async ({ executeQuery }) => {
+ const { sql: retrieveSql, zod: retrieveZod } = pgMeta.foreignTables.retrieve({
+ name: 'foreign_table',
+ schema: 'public',
+ })
+ const table = retrieveZod.parse((await executeQuery(retrieveSql))[0])
+ expect(table).toMatchInlineSnapshot(
+ { id: expect.any(Number) },
+ `
+ {
+ "columns": [
+ {
+ "check": null,
+ "comment": null,
+ "data_type": "bigint",
+ "default_value": null,
+ "enums": [],
+ "format": "int8",
+ "id": "16451.1",
+ "identity_generation": null,
+ "is_generated": false,
+ "is_identity": false,
+ "is_nullable": false,
+ "is_unique": false,
+ "is_updatable": true,
+ "name": "id",
+ "ordinal_position": 1,
+ "schema": "public",
+ "table": "foreign_table",
+ "table_id": 16451,
+ },
+ {
+ "check": null,
+ "comment": null,
+ "data_type": "text",
+ "default_value": null,
+ "enums": [],
+ "format": "text",
+ "id": "16451.2",
+ "identity_generation": null,
+ "is_generated": false,
+ "is_identity": false,
+ "is_nullable": true,
+ "is_unique": false,
+ "is_updatable": true,
+ "name": "name",
+ "ordinal_position": 2,
+ "schema": "public",
+ "table": "foreign_table",
+ "table_id": 16451,
+ },
+ {
+ "check": null,
+ "comment": null,
+ "data_type": "USER-DEFINED",
+ "default_value": null,
+ "enums": [
+ "ACTIVE",
+ "INACTIVE",
+ ],
+ "format": "user_status",
+ "id": "16451.3",
+ "identity_generation": null,
+ "is_generated": false,
+ "is_identity": false,
+ "is_nullable": true,
+ "is_unique": false,
+ "is_updatable": true,
+ "name": "status",
+ "ordinal_position": 3,
+ "schema": "public",
+ "table": "foreign_table",
+ "table_id": 16451,
+ },
+ ],
+ "comment": null,
+ "id": Any<Number>,
+ "name": "foreign_table",
+ "schema": "public",
+ }
+ `
+ )
+})
+
+withTestDatabase('retrieve foreign table by id', async ({ executeQuery }) => {
+ const { sql: retrieveSql, zod: retrieveZod } = pgMeta.foreignTables.retrieve({
+ id: 16451,
+ })
+ const table = retrieveZod.parse((await executeQuery(retrieveSql))[0])
+ expect(table).toMatchInlineSnapshot(
+ { id: expect.any(Number) },
+ `
+ {
+ "columns": [
+ {
+ "check": null,
+ "comment": null,
+ "data_type": "bigint",
+ "default_value": null,
+ "enums": [],
+ "format": "int8",
+ "id": "16451.1",
+ "identity_generation": null,
+ "is_generated": false,
+ "is_identity": false,
+ "is_nullable": false,
+ "is_unique": false,
+ "is_updatable": true,
+ "name": "id",
+ "ordinal_position": 1,
+ "schema": "public",
+ "table": "foreign_table",
+ "table_id": 16451,
+ },
+ {
+ "check": null,
+ "comment": null,
+ "data_type": "text",
+ "default_value": null,
+ "enums": [],
+ "format": "text",
+ "id": "16451.2",
+ "identity_generation": null,
+ "is_generated": false,
+ "is_identity": false,
+ "is_nullable": true,
+ "is_unique": false,
+ "is_updatable": true,
+ "name": "name",
+ "ordinal_position": 2,
+ "schema": "public",
+ "table": "foreign_table",
+ "table_id": 16451,
+ },
+ {
+ "check": null,
+ "comment": null,
+ "data_type": "USER-DEFINED",
+ "default_value": null,
+ "enums": [
+ "ACTIVE",
+ "INACTIVE",
+ ],
+ "format": "user_status",
+ "id": "16451.3",
+ "identity_generation": null,
+ "is_generated": false,
+ "is_identity": false,
+ "is_nullable": true,
+ "is_unique": false,
+ "is_updatable": true,
+ "name": "status",
+ "ordinal_position": 3,
+ "schema": "public",
+ "table": "foreign_table",
+ "table_id": 16451,
+ },
+ ],
+ "comment": null,
+ "id": Any<Number>,
+ "name": "foreign_table",
+ "schema": "public",
+ }
+ `
+ )
+})
diff --git a/packages/pg-meta/test/materialized-views.test.ts b/packages/pg-meta/test/materialized-views.test.ts
new file mode 100644
index 00000000000..01120b31b2e
--- /dev/null
+++ b/packages/pg-meta/test/materialized-views.test.ts
@@ -0,0 +1,286 @@
+import { expect, test, beforeAll, afterAll } from 'vitest'
+import pgMeta from '../src/index'
+import { createTestDatabase, cleanupRoot } from './db/utils'
+
+beforeAll(async () => {
+ // Any global setup if needed
+})
+
+afterAll(async () => {
+ await cleanupRoot()
+})
+
+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('list materialized views', async ({ executeQuery }) => {
+ const { sql: listSql, zod: listZod } = pgMeta.materializedViews.list()
+ const views = listZod.parse(await executeQuery(listSql))
+ const todosMaterializedView = views.find(({ name }) => name === 'todos_matview')
+ expect(todosMaterializedView).toMatchInlineSnapshot(
+ { id: expect.any(Number) },
+ `
+ {
+ "columns": [
+ {
+ "check": null,
+ "comment": null,
+ "data_type": "bigint",
+ "default_value": null,
+ "enums": [],
+ "format": "int8",
+ "id": "16431.1",
+ "identity_generation": null,
+ "is_generated": false,
+ "is_identity": false,
+ "is_nullable": true,
+ "is_unique": false,
+ "is_updatable": false,
+ "name": "id",
+ "ordinal_position": 1,
+ "schema": "public",
+ "table": "todos_matview",
+ "table_id": 16431,
+ },
+ {
+ "check": null,
+ "comment": null,
+ "data_type": "text",
+ "default_value": null,
+ "enums": [],
+ "format": "text",
+ "id": "16431.2",
+ "identity_generation": null,
+ "is_generated": false,
+ "is_identity": false,
+ "is_nullable": true,
+ "is_unique": false,
+ "is_updatable": false,
+ "name": "details",
+ "ordinal_position": 2,
+ "schema": "public",
+ "table": "todos_matview",
+ "table_id": 16431,
+ },
+ {
+ "check": null,
+ "comment": null,
+ "data_type": "bigint",
+ "default_value": null,
+ "enums": [],
+ "format": "int8",
+ "id": "16431.3",
+ "identity_generation": null,
+ "is_generated": false,
+ "is_identity": false,
+ "is_nullable": true,
+ "is_unique": false,
+ "is_updatable": false,
+ "name": "user-id",
+ "ordinal_position": 3,
+ "schema": "public",
+ "table": "todos_matview",
+ "table_id": 16431,
+ },
+ ],
+ "comment": null,
+ "id": Any<Number>,
+ "is_populated": true,
+ "name": "todos_matview",
+ "schema": "public",
+ }
+ `
+ )
+})
+
+withTestDatabase('list materialized views without columns', async ({ executeQuery }) => {
+ const { sql: listSql, zod: listZod } = pgMeta.materializedViews.list({ includeColumns: false })
+ const views = listZod.parse(await executeQuery(listSql))
+ const todosMaterializedView = views.find(({ name }) => name === 'todos_matview')
+ expect(todosMaterializedView).toMatchInlineSnapshot(
+ { id: expect.any(Number) },
+ `
+ {
+ "comment": null,
+ "id": Any<Number>,
+ "is_populated": true,
+ "name": "todos_matview",
+ "schema": "public",
+ }
+ `
+ )
+})
+
+withTestDatabase('retrieve materialized view by name', async ({ executeQuery }) => {
+ const { sql: retrieveSql, zod: retrieveZod } = pgMeta.materializedViews.retrieve({
+ name: 'todos_matview',
+ schema: 'public',
+ })
+ const view = retrieveZod.parse((await executeQuery(retrieveSql))[0])
+ expect(view).toMatchInlineSnapshot(
+ { id: expect.any(Number) },
+ `
+ {
+ "columns": [
+ {
+ "check": null,
+ "comment": null,
+ "data_type": "bigint",
+ "default_value": null,
+ "enums": [],
+ "format": "int8",
+ "id": "16431.1",
+ "identity_generation": null,
+ "is_generated": false,
+ "is_identity": false,
+ "is_nullable": true,
+ "is_unique": false,
+ "is_updatable": false,
+ "name": "id",
+ "ordinal_position": 1,
+ "schema": "public",
+ "table": "todos_matview",
+ "table_id": 16431,
+ },
+ {
+ "check": null,
+ "comment": null,
+ "data_type": "text",
+ "default_value": null,
+ "enums": [],
+ "format": "text",
+ "id": "16431.2",
+ "identity_generation": null,
+ "is_generated": false,
+ "is_identity": false,
+ "is_nullable": true,
+ "is_unique": false,
+ "is_updatable": false,
+ "name": "details",
+ "ordinal_position": 2,
+ "schema": "public",
+ "table": "todos_matview",
+ "table_id": 16431,
+ },
+ {
+ "check": null,
+ "comment": null,
+ "data_type": "bigint",
+ "default_value": null,
+ "enums": [],
+ "format": "int8",
+ "id": "16431.3",
+ "identity_generation": null,
+ "is_generated": false,
+ "is_identity": false,
+ "is_nullable": true,
+ "is_unique": false,
+ "is_updatable": false,
+ "name": "user-id",
+ "ordinal_position": 3,
+ "schema": "public",
+ "table": "todos_matview",
+ "table_id": 16431,
+ },
+ ],
+ "comment": null,
+ "id": Any<Number>,
+ "is_populated": true,
+ "name": "todos_matview",
+ "schema": "public",
+ }
+ `
+ )
+})
+
+withTestDatabase('retrieve materialized view by id', async ({ executeQuery }) => {
+ const { sql: retrieveSql, zod: retrieveZod } = pgMeta.materializedViews.retrieve({
+ id: 16431,
+ })
+ const view = retrieveZod.parse((await executeQuery(retrieveSql))[0])
+ expect(view).toMatchInlineSnapshot(
+ { id: expect.any(Number) },
+ `
+ {
+ "columns": [
+ {
+ "check": null,
+ "comment": null,
+ "data_type": "bigint",
+ "default_value": null,
+ "enums": [],
+ "format": "int8",
+ "id": "16431.1",
+ "identity_generation": null,
+ "is_generated": false,
+ "is_identity": false,
+ "is_nullable": true,
+ "is_unique": false,
+ "is_updatable": false,
+ "name": "id",
+ "ordinal_position": 1,
+ "schema": "public",
+ "table": "todos_matview",
+ "table_id": 16431,
+ },
+ {
+ "check": null,
+ "comment": null,
+ "data_type": "text",
+ "default_value": null,
+ "enums": [],
+ "format": "text",
+ "id": "16431.2",
+ "identity_generation": null,
+ "is_generated": false,
+ "is_identity": false,
+ "is_nullable": true,
+ "is_unique": false,
+ "is_updatable": false,
+ "name": "details",
+ "ordinal_position": 2,
+ "schema": "public",
+ "table": "todos_matview",
+ "table_id": 16431,
+ },
+ {
+ "check": null,
+ "comment": null,
+ "data_type": "bigint",
+ "default_value": null,
+ "enums": [],
+ "format": "int8",
+ "id": "16431.3",
+ "identity_generation": null,
+ "is_generated": false,
+ "is_identity": false,
+ "is_nullable": true,
+ "is_unique": false,
+ "is_updatable": false,
+ "name": "user-id",
+ "ordinal_position": 3,
+ "schema": "public",
+ "table": "todos_matview",
+ "table_id": 16431,
+ },
+ ],
+ "comment": null,
+ "id": Any<Number>,
+ "is_populated": true,
+ "name": "todos_matview",
+ "schema": "public",
+ }
+ `
+ )
+})
diff --git a/packages/pg-meta/test/tables.test.ts b/packages/pg-meta/test/tables.test.ts
new file mode 100644
index 00000000000..119fd13d809
--- /dev/null
+++ b/packages/pg-meta/test/tables.test.ts
@@ -0,0 +1,1485 @@
+import { expect, test, beforeAll, afterAll } from 'vitest'
+import pgMeta from '../src/index'
+import { createTestDatabase, cleanupRoot } from './db/utils'
+
+beforeAll(async () => {
+ // Any global setup if needed
+})
+
+afterAll(async () => {
+ await cleanupRoot()
+})
+
+const cleanNondet = (x: any) => {
+ const { columns, primary_keys, relationships, ...rest2 } = x
+
+ return {
+ columns: columns.map(({ id, table_id, ...rest }: any) => rest),
+ primary_keys: primary_keys.map(({ table_id, ...rest }: any) => rest),
+ relationships: relationships.map(({ id, ...rest }: any) => rest),
+ ...rest2,
+ }
+}
+
+type TestDb = Awaited<ReturnType<typeof createTestDatabase>>
+
+const withTestDatabase = (name: string, fn: (db: TestDb) => Promise<void>) => {
+ test(name, async () => {
+ const db = await createTestDatabase()
+ try {
+ await fn(db)
+ } finally {
+ await db.cleanup()
+ }
+ })
+}
+
+/** Original tests ported from postgres-meta */
+withTestDatabase('list tables', async ({ executeQuery }) => {
+ const { sql, zod } = await pgMeta.tables.list()
+ const res = zod.parse(await executeQuery(sql))
+
+ const { columns, primary_keys, relationships, ...rest } = res.find(
+ ({ name }) => name === 'users'
+ )!
+
+ expect({
+ columns: columns!.map(({ id, table_id, ...rest }) => rest),
+ primary_keys: primary_keys.map(({ table_id, ...rest }) => rest),
+ relationships: relationships.map(({ id, ...rest }) => rest),
+ ...rest,
+ }).toMatchInlineSnapshot(
+ {
+ bytes: expect.any(Number),
+ dead_rows_estimate: expect.any(Number),
+ id: expect.any(Number),
+ live_rows_estimate: expect.any(Number),
+ size: expect.any(String),
+ },
+ `
+ {
+ "bytes": Any<Number>,
+ "columns": [
+ {
+ "check": null,
+ "comment": null,
+ "data_type": "bigint",
+ "default_value": null,
+ "enums": [],
+ "format": "int8",
+ "identity_generation": "BY DEFAULT",
+ "is_generated": false,
+ "is_identity": true,
+ "is_nullable": false,
+ "is_unique": false,
+ "is_updatable": true,
+ "name": "id",
+ "ordinal_position": 1,
+ "schema": "public",
+ "table": "users",
+ },
+ {
+ "check": null,
+ "comment": null,
+ "data_type": "text",
+ "default_value": null,
+ "enums": [],
+ "format": "text",
+ "identity_generation": null,
+ "is_generated": false,
+ "is_identity": false,
+ "is_nullable": true,
+ "is_unique": false,
+ "is_updatable": true,
+ "name": "name",
+ "ordinal_position": 2,
+ "schema": "public",
+ "table": "users",
+ },
+ {
+ "check": null,
+ "comment": null,
+ "data_type": "USER-DEFINED",
+ "default_value": "'ACTIVE'::user_status",
+ "enums": [
+ "ACTIVE",
+ "INACTIVE",
+ ],
+ "format": "user_status",
+ "identity_generation": null,
+ "is_generated": false,
+ "is_identity": false,
+ "is_nullable": true,
+ "is_unique": false,
+ "is_updatable": true,
+ "name": "status",
+ "ordinal_position": 3,
+ "schema": "public",
+ "table": "users",
+ },
+ ],
+ "comment": null,
+ "dead_rows_estimate": Any<Number>,
+ "id": Any<Number>,
+ "live_rows_estimate": Any<Number>,
+ "name": "users",
+ "primary_keys": [
+ {
+ "name": "id",
+ "schema": "public",
+ "table_name": "users",
+ },
+ ],
+ "relationships": [
+ {
+ "constraint_name": "todos_user-id_fkey",
+ "source_column_name": "user-id",
+ "source_schema": "public",
+ "source_table_name": "todos",
+ "target_column_name": "id",
+ "target_table_name": "users",
+ "target_table_schema": "public",
+ },
+ {
+ "constraint_name": "user_details_user_id_fkey",
+ "source_column_name": "user_id",
+ "source_schema": "public",
+ "source_table_name": "user_details",
+ "target_column_name": "id",
+ "target_table_name": "users",
+ "target_table_schema": "public",
+ },
+ ],
+ "replica_identity": "DEFAULT",
+ "rls_enabled": false,
+ "rls_forced": false,
+ "schema": "public",
+ "size": Any<String>,
+ }
+ `
+ )
+})
+
+withTestDatabase('list tables without columns', async ({ executeQuery }) => {
+ const { sql, zod } = await pgMeta.tables.list({ includeColumns: false })
+ const res = zod.parse(await executeQuery(sql))
+
+ //@ts-expect-error columns doesn't exist at type level if includeColumns is false
+ const { columns, primary_keys, relationships, ...rest } = res.find(
+ ({ name }) => name === 'users'
+ )!
+
+ expect({
+ primary_keys: primary_keys.map(({ table_id, ...rest }) => rest),
+ relationships: relationships.map(({ id, ...rest }) => rest),
+ ...rest,
+ }).toMatchInlineSnapshot(
+ {
+ bytes: expect.any(Number),
+ dead_rows_estimate: expect.any(Number),
+ id: expect.any(Number),
+ live_rows_estimate: expect.any(Number),
+ size: expect.any(String),
+ },
+ `
+ {
+ "bytes": Any<Number>,
+ "comment": null,
+ "dead_rows_estimate": Any<Number>,
+ "id": Any<Number>,
+ "live_rows_estimate": Any<Number>,
+ "name": "users",
+ "primary_keys": [
+ {
+ "name": "id",
+ "schema": "public",
+ "table_name": "users",
+ },
+ ],
+ "relationships": [
+ {
+ "constraint_name": "todos_user-id_fkey",
+ "source_column_name": "user-id",
+ "source_schema": "public",
+ "source_table_name": "todos",
+ "target_column_name": "id",
+ "target_table_name": "users",
+ "target_table_schema": "public",
+ },
+ {
+ "constraint_name": "user_details_user_id_fkey",
+ "source_column_name": "user_id",
+ "source_schema": "public",
+ "source_table_name": "user_details",
+ "target_column_name": "id",
+ "target_table_name": "users",
+ "target_table_schema": "public",
+ },
+ ],
+ "replica_identity": "DEFAULT",
+ "rls_enabled": false,
+ "rls_forced": false,
+ "schema": "public",
+ "size": Any<String>,
+ }
+ `
+ )
+})
+
+withTestDatabase('list tables with included schemas', async ({ executeQuery }) => {
+ const { sql, zod } = await pgMeta.tables.list({
+ includedSchemas: ['public'],
+ })
+ const res = zod.parse(await executeQuery(sql))
+
+ expect(res.length).toBeGreaterThan(0)
+
+ res.forEach((table) => {
+ expect(table.schema).toBe('public')
+ })
+})
+
+withTestDatabase('list tables with excluded schemas', async ({ executeQuery }) => {
+ const { sql, zod } = await pgMeta.tables.list({
+ excludedSchemas: ['public'],
+ })
+ const res = zod.parse(await executeQuery(sql))
+
+ res.forEach((table) => {
+ expect(table.schema).not.toBe('public')
+ })
+})
+
+withTestDatabase(
+ 'list tables with excluded schemas and include System Schemas',
+ async ({ executeQuery }) => {
+ const { sql, zod } = await pgMeta.tables.list({
+ excludedSchemas: ['public'],
+ includeSystemSchemas: true,
+ })
+ const res = zod.parse(await executeQuery(sql))
+
+ expect(res.length).toBeGreaterThan(0)
+
+ res.forEach((table) => {
+ expect(table.schema).not.toBe('public')
+ })
+ }
+)
+
+withTestDatabase('create, retrieve, update, and delete table', async ({ executeQuery }) => {
+ // Create table
+ const { sql: createSql } = await pgMeta.tables.create({
+ name: 'test',
+ comment: 'foo',
+ })
+ await executeQuery(createSql)
+
+ // Retrieve the created table
+ const { sql: retrieveSql, zod: retrieveZod } = await pgMeta.tables.retrieve({
+ name: 'test',
+ schema: 'public',
+ })
+ const retrieveRes = retrieveZod.parse((await executeQuery(retrieveSql))[0])
+
+ expect(retrieveRes).toMatchInlineSnapshot(
+ {
+ bytes: expect.any(Number),
+ dead_rows_estimate: expect.any(Number),
+ id: expect.any(Number),
+ live_rows_estimate: expect.any(Number),
+ size: expect.any(String),
+ },
+ `
+ {
+ "bytes": Any<Number>,
+ "columns": [],
+ "comment": "foo",
+ "dead_rows_estimate": Any<Number>,
+ "id": Any<Number>,
+ "live_rows_estimate": Any<Number>,
+ "name": "test",
+ "primary_keys": [],
+ "relationships": [],
+ "replica_identity": "DEFAULT",
+ "rls_enabled": false,
+ "rls_forced": false,
+ "schema": "public",
+ "size": Any<String>,
+ }
+ `
+ )
+
+ // Update table
+ const { sql: updateSql } = await pgMeta.tables.update(
+ { id: retrieveRes!.id },
+ {
+ name: 'test a',
+ rls_enabled: true,
+ rls_forced: true,
+ replica_identity: 'NOTHING',
+ comment: 'foo',
+ }
+ )
+ await executeQuery(updateSql)
+
+ // Retrieve the updated table
+ const { sql: retrieveUpdatedSql, zod: retrieveUpdatedZod } = await pgMeta.tables.retrieve({
+ name: 'test a',
+ schema: 'public',
+ })
+ const updateRes = retrieveUpdatedZod.parse((await executeQuery(retrieveUpdatedSql))[0])
+
+ expect(updateRes).toMatchInlineSnapshot(
+ {
+ bytes: expect.any(Number),
+ dead_rows_estimate: expect.any(Number),
+ id: expect.any(Number),
+ live_rows_estimate: expect.any(Number),
+ size: expect.any(String),
+ },
+ `
+ {
+ "bytes": Any<Number>,
+ "columns": [],
+ "comment": "foo",
+ "dead_rows_estimate": Any<Number>,
+ "id": Any<Number>,
+ "live_rows_estimate": Any<Number>,
+ "name": "test a",
+ "primary_keys": [],
+ "relationships": [],
+ "replica_identity": "NOTHING",
+ "rls_enabled": true,
+ "rls_forced": true,
+ "schema": "public",
+ "size": Any<String>,
+ }
+ `
+ )
+
+ // Remove table
+ const { sql: removeSql } = await pgMeta.tables.remove({
+ id: updateRes!.id,
+ })
+ await executeQuery(removeSql)
+
+ // Verify table is deleted
+ const { sql: verifyDeleteSql } = await pgMeta.tables.retrieve({
+ id: updateRes!.id,
+ })
+ const verifyDeleteRes = await executeQuery(verifyDeleteSql)
+ expect(verifyDeleteRes).toHaveLength(0)
+})
+
+withTestDatabase('update with name unchanged', async ({ executeQuery }) => {
+ // Create table
+ const { sql: createSql } = await pgMeta.tables.create({ name: 't' })
+ await executeQuery(createSql)
+
+ // Get the created table
+ const { sql: retrieveSql, zod: retrieveZod } = await pgMeta.tables.retrieve({
+ name: 't',
+ schema: 'public',
+ })
+ const table = retrieveZod.parse((await executeQuery(retrieveSql))[0])
+
+ // Update table with same name
+ const { sql: updateSql } = await pgMeta.tables.update({ id: table!.id }, { name: 't' })
+ await executeQuery(updateSql)
+
+ // Verify update
+ const { sql: verifySQL, zod: verifyZod } = await pgMeta.tables.retrieve({
+ name: 't',
+ schema: 'public',
+ })
+ const res = verifyZod.parse((await executeQuery(verifySQL))[0])
+
+ expect(res).toMatchInlineSnapshot(
+ {
+ bytes: expect.any(Number),
+ dead_rows_estimate: expect.any(Number),
+ id: expect.any(Number),
+ live_rows_estimate: expect.any(Number),
+ size: expect.any(String),
+ },
+ `
+ {
+ "bytes": Any<Number>,
+ "columns": [],
+ "comment": null,
+ "dead_rows_estimate": Any<Number>,
+ "id": Any<Number>,
+ "live_rows_estimate": Any<Number>,
+ "name": "t",
+ "primary_keys": [],
+ "relationships": [],
+ "replica_identity": "DEFAULT",
+ "rls_enabled": false,
+ "rls_forced": false,
+ "schema": "public",
+ "size": Any<String>,
+ }
+ `
+ )
+})
+
+withTestDatabase("allow ' in comments", async ({ executeQuery }) => {
+ // Create table with single quote in comment
+ const { sql: createSql } = await pgMeta.tables.create({
+ name: 't',
+ comment: "'",
+ })
+ await executeQuery(createSql)
+
+ // Verify creation
+ const { sql: retrieveSql, zod: retrieveZod } = await pgMeta.tables.retrieve({
+ name: 't',
+ schema: 'public',
+ })
+ const res = retrieveZod.parse((await executeQuery(retrieveSql))[0])
+
+ expect(res).toMatchInlineSnapshot(
+ {
+ bytes: expect.any(Number),
+ dead_rows_estimate: expect.any(Number),
+ id: expect.any(Number),
+ live_rows_estimate: expect.any(Number),
+ size: expect.any(String),
+ },
+ `
+ {
+ "bytes": Any<Number>,
+ "columns": [],
+ "comment": "'",
+ "dead_rows_estimate": Any<Number>,
+ "id": Any<Number>,
+ "live_rows_estimate": Any<Number>,
+ "name": "t",
+ "primary_keys": [],
+ "relationships": [],
+ "replica_identity": "DEFAULT",
+ "rls_enabled": false,
+ "rls_forced": false,
+ "schema": "public",
+ "size": Any<String>,
+ }
+ `
+ )
+})
+
+withTestDatabase('primary keys', async ({ executeQuery }) => {
+ // Create table with columns
+ const { sql: createSql } = await pgMeta.tables.create({ name: 't' })
+ await executeQuery(createSql)
+ await executeQuery(`
+ ALTER TABLE t
+ ADD COLUMN c bigint,
+ ADD COLUMN cc text
+ `)
+
+ // Get the created table
+ const { sql: retrieveSql, zod: retrieveZod } = await pgMeta.tables.retrieve({
+ name: 't',
+ schema: 'public',
+ })
+ const table = retrieveZod.parse((await executeQuery(retrieveSql))[0])
+
+ // Update table with primary keys
+ const { sql: updateSql } = await pgMeta.tables.update(
+ { id: table!.id },
+ { primary_keys: [{ name: 'c' }, { name: 'cc' }] }
+ )
+ await executeQuery(updateSql)
+
+ // Verify update
+ const { sql: verifySQL, zod: verifyZod } = await pgMeta.tables.retrieve({
+ name: 't',
+ schema: 'public',
+ })
+ const res = verifyZod.parse((await executeQuery(verifySQL))[0])
+
+ expect(cleanNondet(res)).toMatchInlineSnapshot(
+ {
+ bytes: expect.any(Number),
+ dead_rows_estimate: expect.any(Number),
+ id: expect.any(Number),
+ live_rows_estimate: expect.any(Number),
+ size: expect.any(String),
+ },
+ `
+ {
+ "bytes": Any<Number>,
+ "columns": [
+ {
+ "check": null,
+ "comment": null,
+ "data_type": "bigint",
+ "default_value": null,
+ "enums": [],
+ "format": "int8",
+ "identity_generation": null,
+ "is_generated": false,
+ "is_identity": false,
+ "is_nullable": false,
+ "is_unique": false,
+ "is_updatable": true,
+ "name": "c",
+ "ordinal_position": 1,
+ "schema": "public",
+ "table": "t",
+ },
+ {
+ "check": null,
+ "comment": null,
+ "data_type": "text",
+ "default_value": null,
+ "enums": [],
+ "format": "text",
+ "identity_generation": null,
+ "is_generated": false,
+ "is_identity": false,
+ "is_nullable": false,
+ "is_unique": false,
+ "is_updatable": true,
+ "name": "cc",
+ "ordinal_position": 2,
+ "schema": "public",
+ "table": "t",
+ },
+ ],
+ "comment": null,
+ "dead_rows_estimate": Any<Number>,
+ "id": Any<Number>,
+ "live_rows_estimate": Any<Number>,
+ "name": "t",
+ "primary_keys": [
+ {
+ "name": "c",
+ "schema": "public",
+ "table_name": "t",
+ },
+ {
+ "name": "cc",
+ "schema": "public",
+ "table_name": "t",
+ },
+ ],
+ "relationships": [],
+ "replica_identity": "DEFAULT",
+ "rls_enabled": false,
+ "rls_forced": false,
+ "schema": "public",
+ "size": Any<String>,
+ }
+ `
+ )
+})
+
+// /** Additional tests */
+withTestDatabase('retrieve table by id', async ({ executeQuery }) => {
+ const { sql, zod } = await pgMeta.tables.retrieve({ id: 16510 })
+ const res = zod.parse((await executeQuery(sql))[0])
+
+ expect(res).toMatchInlineSnapshot(
+ {
+ bytes: expect.any(Number),
+ dead_rows_estimate: expect.any(Number),
+ id: expect.any(Number),
+ live_rows_estimate: expect.any(Number),
+ size: expect.any(String),
+ },
+ `
+ {
+ "bytes": Any<Number>,
+ "columns": [
+ {
+ "check": null,
+ "comment": null,
+ "data_type": "text",
+ "default_value": null,
+ "enums": [],
+ "format": "text",
+ "id": "16510.2",
+ "identity_generation": null,
+ "is_generated": false,
+ "is_identity": false,
+ "is_nullable": false,
+ "is_unique": false,
+ "is_updatable": true,
+ "name": "name",
+ "ordinal_position": 2,
+ "schema": "public",
+ "table": "memes",
+ "table_id": 16510,
+ },
+ {
+ "check": null,
+ "comment": null,
+ "data_type": "integer",
+ "default_value": null,
+ "enums": [],
+ "format": "int4",
+ "id": "16510.3",
+ "identity_generation": null,
+ "is_generated": false,
+ "is_identity": false,
+ "is_nullable": true,
+ "is_unique": false,
+ "is_updatable": true,
+ "name": "category",
+ "ordinal_position": 3,
+ "schema": "public",
+ "table": "memes",
+ "table_id": 16510,
+ },
+ {
+ "check": null,
+ "comment": null,
+ "data_type": "jsonb",
+ "default_value": null,
+ "enums": [],
+ "format": "jsonb",
+ "id": "16510.4",
+ "identity_generation": null,
+ "is_generated": false,
+ "is_identity": false,
+ "is_nullable": true,
+ "is_unique": false,
+ "is_updatable": true,
+ "name": "metadata",
+ "ordinal_position": 4,
+ "schema": "public",
+ "table": "memes",
+ "table_id": 16510,
+ },
+ {
+ "check": null,
+ "comment": null,
+ "data_type": "timestamp without time zone",
+ "default_value": null,
+ "enums": [],
+ "format": "timestamp",
+ "id": "16510.5",
+ "identity_generation": null,
+ "is_generated": false,
+ "is_identity": false,
+ "is_nullable": false,
+ "is_unique": false,
+ "is_updatable": true,
+ "name": "created_at",
+ "ordinal_position": 5,
+ "schema": "public",
+ "table": "memes",
+ "table_id": 16510,
+ },
+ {
+ "check": null,
+ "comment": null,
+ "data_type": "integer",
+ "default_value": "nextval('memes_id_seq'::regclass)",
+ "enums": [],
+ "format": "int4",
+ "id": "16510.1",
+ "identity_generation": null,
+ "is_generated": false,
+ "is_identity": false,
+ "is_nullable": false,
+ "is_unique": false,
+ "is_updatable": true,
+ "name": "id",
+ "ordinal_position": 1,
+ "schema": "public",
+ "table": "memes",
+ "table_id": 16510,
+ },
+ {
+ "check": null,
+ "comment": null,
+ "data_type": "USER-DEFINED",
+ "default_value": "'old'::meme_status",
+ "enums": [
+ "new",
+ "old",
+ "retired",
+ ],
+ "format": "meme_status",
+ "id": "16510.6",
+ "identity_generation": null,
+ "is_generated": false,
+ "is_identity": false,
+ "is_nullable": true,
+ "is_unique": false,
+ "is_updatable": true,
+ "name": "status",
+ "ordinal_position": 6,
+ "schema": "public",
+ "table": "memes",
+ "table_id": 16510,
+ },
+ ],
+ "comment": null,
+ "dead_rows_estimate": Any<Number>,
+ "id": Any<Number>,
+ "live_rows_estimate": Any<Number>,
+ "name": "memes",
+ "primary_keys": [
+ {
+ "name": "id",
+ "schema": "public",
+ "table_id": 16510,
+ "table_name": "memes",
+ },
+ ],
+ "relationships": [
+ {
+ "constraint_name": "memes_category_fkey",
+ "id": 16519,
+ "source_column_name": "category",
+ "source_schema": "public",
+ "source_table_name": "memes",
+ "target_column_name": "id",
+ "target_table_name": "category",
+ "target_table_schema": "public",
+ },
+ ],
+ "replica_identity": "DEFAULT",
+ "rls_enabled": false,
+ "rls_forced": false,
+ "schema": "public",
+ "size": Any<String>,
+ }
+ `
+ )
+})
+
+withTestDatabase('retrieve table by name and schema', async ({ executeQuery }) => {
+ const { sql, zod } = await pgMeta.tables.retrieve({ name: 'memes', schema: 'public' })
+ const res = zod.parse((await executeQuery(sql))[0])
+
+ expect(res).toMatchInlineSnapshot(
+ {
+ bytes: expect.any(Number),
+ dead_rows_estimate: expect.any(Number),
+ id: expect.any(Number),
+ live_rows_estimate: expect.any(Number),
+ size: expect.any(String),
+ },
+ `
+ {
+ "bytes": Any<Number>,
+ "columns": [
+ {
+ "check": null,
+ "comment": null,
+ "data_type": "text",
+ "default_value": null,
+ "enums": [],
+ "format": "text",
+ "id": "16510.2",
+ "identity_generation": null,
+ "is_generated": false,
+ "is_identity": false,
+ "is_nullable": false,
+ "is_unique": false,
+ "is_updatable": true,
+ "name": "name",
+ "ordinal_position": 2,
+ "schema": "public",
+ "table": "memes",
+ "table_id": 16510,
+ },
+ {
+ "check": null,
+ "comment": null,
+ "data_type": "integer",
+ "default_value": null,
+ "enums": [],
+ "format": "int4",
+ "id": "16510.3",
+ "identity_generation": null,
+ "is_generated": false,
+ "is_identity": false,
+ "is_nullable": true,
+ "is_unique": false,
+ "is_updatable": true,
+ "name": "category",
+ "ordinal_position": 3,
+ "schema": "public",
+ "table": "memes",
+ "table_id": 16510,
+ },
+ {
+ "check": null,
+ "comment": null,
+ "data_type": "jsonb",
+ "default_value": null,
+ "enums": [],
+ "format": "jsonb",
+ "id": "16510.4",
+ "identity_generation": null,
+ "is_generated": false,
+ "is_identity": false,
+ "is_nullable": true,
+ "is_unique": false,
+ "is_updatable": true,
+ "name": "metadata",
+ "ordinal_position": 4,
+ "schema": "public",
+ "table": "memes",
+ "table_id": 16510,
+ },
+ {
+ "check": null,
+ "comment": null,
+ "data_type": "timestamp without time zone",
+ "default_value": null,
+ "enums": [],
+ "format": "timestamp",
+ "id": "16510.5",
+ "identity_generation": null,
+ "is_generated": false,
+ "is_identity": false,
+ "is_nullable": false,
+ "is_unique": false,
+ "is_updatable": true,
+ "name": "created_at",
+ "ordinal_position": 5,
+ "schema": "public",
+ "table": "memes",
+ "table_id": 16510,
+ },
+ {
+ "check": null,
+ "comment": null,
+ "data_type": "integer",
+ "default_value": "nextval('memes_id_seq'::regclass)",
+ "enums": [],
+ "format": "int4",
+ "id": "16510.1",
+ "identity_generation": null,
+ "is_generated": false,
+ "is_identity": false,
+ "is_nullable": false,
+ "is_unique": false,
+ "is_updatable": true,
+ "name": "id",
+ "ordinal_position": 1,
+ "schema": "public",
+ "table": "memes",
+ "table_id": 16510,
+ },
+ {
+ "check": null,
+ "comment": null,
+ "data_type": "USER-DEFINED",
+ "default_value": "'old'::meme_status",
+ "enums": [
+ "new",
+ "old",
+ "retired",
+ ],
+ "format": "meme_status",
+ "id": "16510.6",
+ "identity_generation": null,
+ "is_generated": false,
+ "is_identity": false,
+ "is_nullable": true,
+ "is_unique": false,
+ "is_updatable": true,
+ "name": "status",
+ "ordinal_position": 6,
+ "schema": "public",
+ "table": "memes",
+ "table_id": 16510,
+ },
+ ],
+ "comment": null,
+ "dead_rows_estimate": Any<Number>,
+ "id": Any<Number>,
+ "live_rows_estimate": Any<Number>,
+ "name": "memes",
+ "primary_keys": [
+ {
+ "name": "id",
+ "schema": "public",
+ "table_id": 16510,
+ "table_name": "memes",
+ },
+ ],
+ "relationships": [
+ {
+ "constraint_name": "memes_category_fkey",
+ "id": 16519,
+ "source_column_name": "category",
+ "source_schema": "public",
+ "source_table_name": "memes",
+ "target_column_name": "id",
+ "target_table_name": "category",
+ "target_table_schema": "public",
+ },
+ ],
+ "replica_identity": "DEFAULT",
+ "rls_enabled": false,
+ "rls_forced": false,
+ "schema": "public",
+ "size": Any<String>,
+ }
+ `
+ )
+})
+
+withTestDatabase('retrieve error if missing identifiers', async ({}) => {
+ await expect(async () => {
+ //@ts-expect-error use with missing params
+ await pgMeta.tables.retrieve({ name: 'memes' })
+ }).rejects.toThrow('Must provide either id or name and schema')
+})
+
+withTestDatabase('remove table by id', async ({ executeQuery }) => {
+ // First create a test table
+ await executeQuery(`
+ CREATE TABLE test_remove_table (
+ id SERIAL PRIMARY KEY,
+ name TEXT
+ );
+ `)
+
+ // Get the table's id
+ const { sql: listSql, zod: listZod } = await pgMeta.tables.list()
+ const tables = listZod.parse(await executeQuery(listSql))
+ const tableId = tables.find((t) => t.name === 'test_remove_table')!.id
+
+ // Remove the table
+ const { sql } = await pgMeta.tables.remove({ id: tableId })
+ await executeQuery(sql)
+
+ // Verify the table is gone
+ const tablesAfter = listZod.parse(await executeQuery(listSql))
+ expect(tablesAfter.find((t) => t.name === 'test_remove_table')).toBeUndefined()
+})
+
+withTestDatabase('remove table by name and schema', async ({ executeQuery }) => {
+ // First create a test table
+ await executeQuery(`
+ CREATE TABLE test_remove_table_2 (
+ id SERIAL PRIMARY KEY,
+ name TEXT
+ );
+ `)
+
+ // Remove the table
+ const { sql } = await pgMeta.tables.remove({
+ name: 'test_remove_table_2',
+ schema: 'public',
+ })
+ await executeQuery(sql)
+
+ // Verify the table is gone
+ const { sql: listSql, zod: listZod } = await pgMeta.tables.list()
+ const tables = listZod.parse(await executeQuery(listSql))
+ expect(tables.find((t) => t.name === 'test_remove_table_2')).toBeUndefined()
+})
+
+withTestDatabase('remove throws error for non-existent table', async ({ executeQuery }) => {
+ const { sql } = await pgMeta.tables.remove({
+ name: 'non_existent_table',
+ schema: 'public',
+ })
+
+ // With schema and name
+ await expect(executeQuery(sql)).rejects.toThrow(
+ `Failed to execute query: Cannot find table with: name = 'non_existent_table' and schema = 'public'`
+ )
+ await expect(
+ executeQuery(
+ pgMeta.tables.remove({
+ id: 999999,
+ }).sql
+ )
+ ).rejects.toThrow(`Failed to execute query: Cannot find table with: id = 999999`)
+})
+
+withTestDatabase('remove throws error with missing identifiers', async ({}) => {
+ await expect(async () => {
+ //@ts-expect-error use with missing params
+ await pgMeta.tables.remove({ name: 'some_table' })
+ }).rejects.toThrow('Must provide either id or name and schema')
+})
+
+withTestDatabase('update table - rename', async ({ executeQuery }) => {
+ // Create test table
+ const { sql: createSql } = await pgMeta.tables.create({ name: 'test_rename' })
+ await executeQuery(createSql)
+
+ // Update table name
+ const { sql: updateSql } = await pgMeta.tables.update(
+ { name: 'test_rename', schema: 'public' },
+ { name: 'test_renamed' }
+ )
+ await executeQuery(updateSql)
+
+ // Verify update
+ const { sql: retrieveSql, zod } = await pgMeta.tables.retrieve({
+ name: 'test_renamed',
+ schema: 'public',
+ })
+ const res = zod.parse((await executeQuery(retrieveSql))[0])
+ expect(res!.name).toBe('test_renamed')
+})
+
+withTestDatabase('update table - change schema', async ({ executeQuery }) => {
+ // Create test schema and table
+ await executeQuery('CREATE SCHEMA test_schema')
+ const { sql: createSql } = await pgMeta.tables.create({ name: 'test_schema_move' })
+ await executeQuery(createSql)
+
+ // Move table to new schema
+ const { sql: updateSql } = await pgMeta.tables.update(
+ { name: 'test_schema_move', schema: 'public' },
+ { schema: 'test_schema' }
+ )
+ await executeQuery(updateSql)
+
+ // Verify update
+ const { sql: retrieveSql, zod } = await pgMeta.tables.retrieve({
+ name: 'test_schema_move',
+ schema: 'test_schema',
+ })
+ const res = zod.parse((await executeQuery(retrieveSql))[0])
+ expect(res!.schema).toBe('test_schema')
+})
+
+withTestDatabase('update table - row level security', async ({ executeQuery }) => {
+ // Create test table
+ const { sql: createSql } = await pgMeta.tables.create({ name: 'test_rls' })
+ await executeQuery(createSql)
+
+ // Enable RLS
+ const { sql: updateSql } = await pgMeta.tables.update(
+ { name: 'test_rls', schema: 'public' },
+ { rls_enabled: true, rls_forced: true }
+ )
+ await executeQuery(updateSql)
+
+ // Verify update
+ const { sql: retrieveSql, zod } = await pgMeta.tables.retrieve({
+ name: 'test_rls',
+ schema: 'public',
+ })
+ const res = zod.parse((await executeQuery(retrieveSql))[0])
+ expect(res!.rls_enabled).toBe(true)
+ expect(res!.rls_forced).toBe(true)
+})
+
+withTestDatabase('update table - replica identity', async ({ executeQuery }) => {
+ // Create test table
+ const { sql: createSql } = await pgMeta.tables.create({ name: 'test_replica' })
+ await executeQuery(createSql)
+
+ // Change replica identity
+ const { sql: updateSql } = await pgMeta.tables.update(
+ { name: 'test_replica', schema: 'public' },
+ { replica_identity: 'NOTHING' }
+ )
+ await executeQuery(updateSql)
+
+ // Verify update
+ const { sql: retrieveSql, zod } = await pgMeta.tables.retrieve({
+ name: 'test_replica',
+ schema: 'public',
+ })
+ const res = zod.parse((await executeQuery(retrieveSql))[0])
+ expect(res!.replica_identity).toBe('NOTHING')
+})
+
+withTestDatabase('update table - primary keys', async ({ executeQuery }) => {
+ // Create test table with a column
+ const { sql: createSql } = await pgMeta.tables.create({ name: 'test_pk' })
+ await executeQuery(createSql)
+ await executeQuery('ALTER TABLE test_pk ADD COLUMN id INT')
+
+ // Add primary key
+ const { sql: updateSql } = await pgMeta.tables.update(
+ { name: 'test_pk', schema: 'public' },
+ { primary_keys: [{ name: 'id' }] }
+ )
+ await executeQuery(updateSql)
+
+ // Verify update
+ const { sql: retrieveSql, zod } = await pgMeta.tables.retrieve({
+ name: 'test_pk',
+ schema: 'public',
+ })
+ const res = zod.parse((await executeQuery(retrieveSql))[0])
+ expect(res!.primary_keys).toHaveLength(1)
+ expect(res!.primary_keys[0].name).toBe('id')
+})
+
+withTestDatabase('update table - remove primary keys', async ({ executeQuery }) => {
+ // Create test table with primary key
+ const { sql: createSql } = await pgMeta.tables.create({ name: 'test_pk_remove' })
+ await executeQuery(createSql)
+ await executeQuery('ALTER TABLE test_pk_remove ADD COLUMN id INT PRIMARY KEY')
+
+ // Remove primary key
+ const { sql: updateSql } = await pgMeta.tables.update(
+ { name: 'test_pk_remove', schema: 'public' },
+ { primary_keys: [] }
+ )
+ await executeQuery(updateSql)
+
+ // Verify update
+ const { sql: retrieveSql, zod } = await pgMeta.tables.retrieve({
+ name: 'test_pk_remove',
+ schema: 'public',
+ })
+ const res = zod.parse((await executeQuery(retrieveSql))[0])
+ expect(res!.primary_keys).toHaveLength(0)
+})
+
+withTestDatabase('update table - comment', async ({ executeQuery }) => {
+ // Create test table
+ const { sql: createSql } = await pgMeta.tables.create({ name: 'test_comment' })
+ await executeQuery(createSql)
+
+ // Add comment
+ const { sql: updateSql } = await pgMeta.tables.update(
+ { name: 'test_comment', schema: 'public' },
+ { comment: 'Test comment' }
+ )
+ await executeQuery(updateSql)
+
+ // Verify update
+ const { sql: retrieveSql, zod } = await pgMeta.tables.retrieve({
+ name: 'test_comment',
+ schema: 'public',
+ })
+ const res = zod.parse((await executeQuery(retrieveSql))[0])
+ expect(res!.comment).toBe('Test comment')
+})
+
+withTestDatabase('update table - multiple changes', async ({ executeQuery }) => {
+ // Create test table
+ const { sql: createSql } = await pgMeta.tables.create({ name: 'test_multiple' })
+ await executeQuery(createSql)
+ await executeQuery('ALTER TABLE test_multiple ADD COLUMN id INT')
+
+ // Make multiple changes
+ const { sql: updateSql } = await pgMeta.tables.update(
+ { name: 'test_multiple', schema: 'public' },
+ {
+ name: 'test_multiple_updated',
+ comment: 'Updated table',
+ rls_enabled: true,
+ primary_keys: [{ name: 'id' }],
+ replica_identity: 'FULL',
+ }
+ )
+ await executeQuery(updateSql)
+
+ // Verify all updates
+ const { sql: retrieveSql, zod } = await pgMeta.tables.retrieve({
+ name: 'test_multiple_updated',
+ schema: 'public',
+ })
+ const res = zod.parse((await executeQuery(retrieveSql))[0])
+ expect(res).toMatchObject({
+ name: 'test_multiple_updated',
+ comment: 'Updated table',
+ rls_enabled: true,
+ replica_identity: 'FULL',
+ primary_keys: [expect.objectContaining({ name: 'id' })],
+ })
+})
+
+withTestDatabase('update table - by id', async ({ executeQuery }) => {
+ // Create test table
+ const { sql: createSql } = await pgMeta.tables.create({ name: 'test_by_id' })
+ await executeQuery(createSql)
+
+ // Get table id
+ const { sql: retrieveSql, zod } = await pgMeta.tables.retrieve({
+ name: 'test_by_id',
+ schema: 'public',
+ })
+ const table = zod.parse((await executeQuery(retrieveSql))[0])
+
+ // Update by id
+ const { sql: updateSql } = await pgMeta.tables.update(
+ { id: table!.id },
+ { name: 'test_by_id_updated' }
+ )
+ await executeQuery(updateSql)
+
+ // Verify update
+ const { sql: verifySQL, zod: verifyZod } = await pgMeta.tables.retrieve({
+ name: 'test_by_id_updated',
+ schema: 'public',
+ })
+ const res = verifyZod.parse((await executeQuery(verifySQL))[0])
+ expect(res!.name).toBe('test_by_id_updated')
+})
+
+withTestDatabase('update table - error on non-existent table', async ({ executeQuery }) => {
+ const { sql: updateSql } = await pgMeta.tables.update(
+ { name: 'non_existent', schema: 'public' },
+ { name: 'new_name' }
+ )
+
+ await expect(executeQuery(updateSql)).rejects.toThrow()
+})
+
+withTestDatabase('update table - rename with schema change', async ({ executeQuery }) => {
+ // Create test schema and table
+ await executeQuery('CREATE SCHEMA test_schema')
+ const { sql: createSql } = await pgMeta.tables.create({ name: 'test_rename_schema' })
+ await executeQuery(createSql)
+
+ // Update both name and schema
+ const { sql: updateSql } = await pgMeta.tables.update(
+ { name: 'test_rename_schema', schema: 'public' },
+ {
+ name: 'test_renamed_schema',
+ schema: 'test_schema',
+ }
+ )
+ await executeQuery(updateSql)
+
+ // Verify update
+ const { sql: retrieveSql, zod } = await pgMeta.tables.retrieve({
+ name: 'test_renamed_schema',
+ schema: 'test_schema',
+ })
+ const res = zod.parse((await executeQuery(retrieveSql))[0])
+ expect(res!.name).toBe('test_renamed_schema')
+ expect(res!.schema).toBe('test_schema')
+})
+
+// Table creation test cases
+const tableCreationTests = [
+ {
+ name: 'create table with default schema',
+ input: {
+ name: 'test_table_1',
+ },
+ expectedSchema: 'public',
+ expectedComment: null,
+ },
+ {
+ name: 'create table with explicit public schema',
+ input: {
+ name: 'test_table_2',
+ schema: 'public',
+ },
+ expectedSchema: 'public',
+ expectedComment: null,
+ },
+ {
+ name: 'create table with custom schema',
+ input: {
+ name: 'test_table_3',
+ schema: 'custom_schema',
+ },
+ expectedSchema: 'custom_schema',
+ expectedComment: null,
+ beforeTest: async (
+ executeQuery: Awaited<ReturnType<typeof createTestDatabase>>['executeQuery']
+ ) => {
+ await executeQuery('CREATE SCHEMA IF NOT EXISTS custom_schema')
+ },
+ },
+ {
+ name: 'create table with comment',
+ input: {
+ name: 'test_table_4',
+ comment: 'Test comment',
+ },
+ expectedSchema: 'public',
+ expectedComment: 'Test comment',
+ },
+ {
+ name: 'create table with empty string comment',
+ input: {
+ name: 'test_table_5',
+ comment: '',
+ },
+ expectedSchema: 'public',
+ expectedComment: null, // PostgreSQL treats empty string comments as NULL
+ },
+ {
+ name: 'create table with null comment',
+ input: {
+ name: 'test_table_6',
+ comment: null,
+ },
+ expectedSchema: 'public',
+ expectedComment: null,
+ },
+ {
+ name: 'create table with uppercase name',
+ input: {
+ name: 'UPPERCASE_TABLE',
+ },
+ expectedSchema: 'public',
+ expectedComment: null,
+ },
+ {
+ name: 'create table with mixed case name',
+ input: {
+ name: 'MixedCase_Table_Name',
+ },
+ expectedSchema: 'public',
+ expectedComment: null,
+ },
+ {
+ name: 'create table with quoted name',
+ input: {
+ name: 'table "with" quotes',
+ },
+ expectedSchema: 'public',
+ expectedComment: null,
+ },
+ {
+ name: 'create table with special characters',
+ input: {
+ name: 'table$with#special@chars',
+ },
+ expectedSchema: 'public',
+ expectedComment: null,
+ },
+ {
+ name: 'create table with name at maximum length',
+ input: {
+ name: 'a'.repeat(63), // PostgreSQL has a 63-byte limit for identifiers
+ },
+ expectedSchema: 'public',
+ expectedComment: null,
+ },
+ {
+ name: 'create table with schema containing special characters',
+ input: {
+ name: 'normal_table',
+ schema: 'Special.Schema$Name',
+ },
+ expectedSchema: 'Special.Schema$Name',
+ expectedComment: null,
+ beforeTest: async (executeQuery: TestDb['executeQuery']) => {
+ await executeQuery('CREATE SCHEMA IF NOT EXISTS "Special.Schema$Name"')
+ },
+ },
+ {
+ name: 'create table with very long name',
+ input: {
+ name: 'a'.repeat(63),
+ },
+ expectedSchema: 'public',
+ expectedComment: null,
+ },
+ {
+ name: 'create table with special characters in name',
+ input: {
+ name: 'table,name',
+ },
+ expectedSchema: 'public',
+ expectedComment: null,
+ },
+]
+
+// SQL injection test cases
+const sqlInjectionTests = [
+ {
+ name: 'prevent SQL injection in table name',
+ input: {
+ name: "table_name'; DROP TABLE users; --",
+ },
+ },
+ {
+ name: 'prevent SQL injection in comment',
+ input: {
+ name: 'safe_table',
+ comment: "normal comment'; DROP TABLE users; --",
+ },
+ },
+]
+
+// Error test cases
+const errorTests = [
+ {
+ name: 'fail on duplicate table name',
+ input: { name: 'duplicate_table' },
+ setup: async (executeQuery: TestDb['executeQuery']) => {
+ await executeQuery(pgMeta.tables.create({ name: 'duplicate_table' }).sql)
+ },
+ expectedError: /relation.*already exists/,
+ },
+ {
+ name: 'fail on invalid schema',
+ input: { name: 'test_table', schema: 'nonexistent_schema' },
+ expectedError: /schema.*does not exist/,
+ },
+ {
+ name: 'fail on empty table name',
+ input: {
+ name: '',
+ },
+ expectedError: /zero-length delimited identifier/,
+ },
+ {
+ name: 'fail on schema name exceeding maximum length',
+ input: {
+ name: 'table',
+ schema: 'a'.repeat(64),
+ },
+ expectedError: /schema.*does not exist/,
+ },
+]
+
+// Generate individual test cases for successful table creation
+for (const testCase of tableCreationTests) {
+ withTestDatabase(testCase.name, async ({ executeQuery }) => {
+ if (testCase.beforeTest) {
+ await testCase.beforeTest(executeQuery)
+ }
+
+ //@ts-expect-error
+ const { sql } = pgMeta.tables.create(testCase.input)
+ await executeQuery(sql)
+
+ const { sql: listSql, zod: listZod } = await pgMeta.tables.list()
+ const tables = listZod.parse(await executeQuery(listSql))
+ const createdTable = tables.find((t) => t.name === testCase.input.name)
+
+ expect(createdTable).toBeDefined()
+ expect(createdTable?.schema).toBe(testCase.expectedSchema)
+ expect(createdTable?.comment).toBe(testCase.expectedComment)
+ })
+}
+
+// Generate individual test cases for SQL injection prevention
+for (const testCase of sqlInjectionTests) {
+ withTestDatabase(`create - ${testCase.name}`, async ({ executeQuery }) => {
+ const { sql } = pgMeta.tables.create(testCase.input)
+ await executeQuery(sql)
+
+ // Verify table was created with correct name
+ const { sql: listSql, zod: listZod } = await pgMeta.tables.list()
+ const tables = listZod.parse(await executeQuery(listSql))
+ expect(tables.find((t) => t.name === testCase.input.name)).toBeDefined()
+
+ // Verify users table still exists (wasn't dropped)
+ expect(tables.find((t) => t.name === 'users')).toBeDefined()
+ })
+}
+
+// Generate individual test cases for error conditions
+for (const testCase of errorTests) {
+ withTestDatabase(`create - ${testCase.name}`, async ({ executeQuery }) => {
+ if (testCase.setup) {
+ await testCase.setup(executeQuery)
+ }
+
+ const { sql } = pgMeta.tables.create(testCase.input)
+ await expect(executeQuery(sql)).rejects.toThrow(testCase.expectedError)
+ })
+}
\ No newline at end of file
diff --git a/packages/pg-meta/test/views.test.ts b/packages/pg-meta/test/views.test.ts
new file mode 100644
index 00000000000..1611772c694
--- /dev/null
+++ b/packages/pg-meta/test/views.test.ts
@@ -0,0 +1,286 @@
+import { expect, test, beforeAll, afterAll } from 'vitest'
+import pgMeta from '../src/index'
+import { createTestDatabase, cleanupRoot } from './db/utils'
+
+beforeAll(async () => {
+ // Any global setup if needed
+})
+
+afterAll(async () => {
+ await cleanupRoot()
+})
+
+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('list views', async ({ executeQuery }) => {
+ const { sql: listSql, zod: listZod } = pgMeta.views.list()
+ const views = listZod.parse(await executeQuery(listSql))
+ const todosView = views.find(({ name }) => name === 'todos_view')
+ expect(todosView).toMatchInlineSnapshot(
+ { id: expect.any(Number) },
+ `
+ {
+ "columns": [
+ {
+ "check": null,
+ "comment": null,
+ "data_type": "bigint",
+ "default_value": null,
+ "enums": [],
+ "format": "int8",
+ "id": "16423.1",
+ "identity_generation": null,
+ "is_generated": false,
+ "is_identity": false,
+ "is_nullable": true,
+ "is_unique": false,
+ "is_updatable": true,
+ "name": "id",
+ "ordinal_position": 1,
+ "schema": "public",
+ "table": "todos_view",
+ "table_id": 16423,
+ },
+ {
+ "check": null,
+ "comment": null,
+ "data_type": "text",
+ "default_value": null,
+ "enums": [],
+ "format": "text",
+ "id": "16423.2",
+ "identity_generation": null,
+ "is_generated": false,
+ "is_identity": false,
+ "is_nullable": true,
+ "is_unique": false,
+ "is_updatable": true,
+ "name": "details",
+ "ordinal_position": 2,
+ "schema": "public",
+ "table": "todos_view",
+ "table_id": 16423,
+ },
+ {
+ "check": null,
+ "comment": null,
+ "data_type": "bigint",
+ "default_value": null,
+ "enums": [],
+ "format": "int8",
+ "id": "16423.3",
+ "identity_generation": null,
+ "is_generated": false,
+ "is_identity": false,
+ "is_nullable": true,
+ "is_unique": false,
+ "is_updatable": true,
+ "name": "user-id",
+ "ordinal_position": 3,
+ "schema": "public",
+ "table": "todos_view",
+ "table_id": 16423,
+ },
+ ],
+ "comment": null,
+ "id": Any<Number>,
+ "is_updatable": true,
+ "name": "todos_view",
+ "schema": "public",
+ }
+ `
+ )
+})
+
+withTestDatabase('list views without columns', async ({ executeQuery }) => {
+ const { sql: listSql, zod: listZod } = pgMeta.views.list({ includeColumns: false })
+ const views = listZod.parse(await executeQuery(listSql))
+ const todosView = views.find(({ name }) => name === 'todos_view')
+ expect(todosView).toMatchInlineSnapshot(
+ { id: expect.any(Number) },
+ `
+ {
+ "comment": null,
+ "id": Any<Number>,
+ "is_updatable": true,
+ "name": "todos_view",
+ "schema": "public",
+ }
+ `
+ )
+})
+
+withTestDatabase('retrieve view by name', async ({ executeQuery }) => {
+ const { sql: retrieveSql, zod: retrieveZod } = pgMeta.views.retrieve({
+ name: 'todos_view',
+ schema: 'public',
+ })
+ const view = retrieveZod.parse((await executeQuery(retrieveSql))[0])
+ expect(view).toMatchInlineSnapshot(
+ { id: expect.any(Number) },
+ `
+ {
+ "columns": [
+ {
+ "check": null,
+ "comment": null,
+ "data_type": "bigint",
+ "default_value": null,
+ "enums": [],
+ "format": "int8",
+ "id": "16423.1",
+ "identity_generation": null,
+ "is_generated": false,
+ "is_identity": false,
+ "is_nullable": true,
+ "is_unique": false,
+ "is_updatable": true,
+ "name": "id",
+ "ordinal_position": 1,
+ "schema": "public",
+ "table": "todos_view",
+ "table_id": 16423,
+ },
+ {
+ "check": null,
+ "comment": null,
+ "data_type": "text",
+ "default_value": null,
+ "enums": [],
+ "format": "text",
+ "id": "16423.2",
+ "identity_generation": null,
+ "is_generated": false,
+ "is_identity": false,
+ "is_nullable": true,
+ "is_unique": false,
+ "is_updatable": true,
+ "name": "details",
+ "ordinal_position": 2,
+ "schema": "public",
+ "table": "todos_view",
+ "table_id": 16423,
+ },
+ {
+ "check": null,
+ "comment": null,
+ "data_type": "bigint",
+ "default_value": null,
+ "enums": [],
+ "format": "int8",
+ "id": "16423.3",
+ "identity_generation": null,
+ "is_generated": false,
+ "is_identity": false,
+ "is_nullable": true,
+ "is_unique": false,
+ "is_updatable": true,
+ "name": "user-id",
+ "ordinal_position": 3,
+ "schema": "public",
+ "table": "todos_view",
+ "table_id": 16423,
+ },
+ ],
+ "comment": null,
+ "id": Any<Number>,
+ "is_updatable": true,
+ "name": "todos_view",
+ "schema": "public",
+ }
+ `
+ )
+})
+
+withTestDatabase('retrieve view by id', async ({ executeQuery }) => {
+ const { sql: retrieveSql, zod: retrieveZod } = pgMeta.views.retrieve({
+ id: 16423,
+ })
+ const view = retrieveZod.parse((await executeQuery(retrieveSql))[0])
+ expect(view).toMatchInlineSnapshot(
+ { id: expect.any(Number) },
+ `
+ {
+ "columns": [
+ {
+ "check": null,
+ "comment": null,
+ "data_type": "bigint",
+ "default_value": null,
+ "enums": [],
+ "format": "int8",
+ "id": "16423.1",
+ "identity_generation": null,
+ "is_generated": false,
+ "is_identity": false,
+ "is_nullable": true,
+ "is_unique": false,
+ "is_updatable": true,
+ "name": "id",
+ "ordinal_position": 1,
+ "schema": "public",
+ "table": "todos_view",
+ "table_id": 16423,
+ },
+ {
+ "check": null,
+ "comment": null,
+ "data_type": "text",
+ "default_value": null,
+ "enums": [],
+ "format": "text",
+ "id": "16423.2",
+ "identity_generation": null,
+ "is_generated": false,
+ "is_identity": false,
+ "is_nullable": true,
+ "is_unique": false,
+ "is_updatable": true,
+ "name": "details",
+ "ordinal_position": 2,
+ "schema": "public",
+ "table": "todos_view",
+ "table_id": 16423,
+ },
+ {
+ "check": null,
+ "comment": null,
+ "data_type": "bigint",
+ "default_value": null,
+ "enums": [],
+ "format": "int8",
+ "id": "16423.3",
+ "identity_generation": null,
+ "is_generated": false,
+ "is_identity": false,
+ "is_nullable": true,
+ "is_unique": false,
+ "is_updatable": true,
+ "name": "user-id",
+ "ordinal_position": 3,
+ "schema": "public",
+ "table": "todos_view",
+ "table_id": 16423,
+ },
+ ],
+ "comment": null,
+ "id": Any<Number>,
+ "is_updatable": true,
+ "name": "todos_view",
+ "schema": "public",
+ }
+ `
+ )
+})
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index bc206a2b797..bbd9bf71605 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1481,6 +1481,9 @@ importers:
'@types/pg':
specifier: ^8.11.11
version: 8.11.11
+ '@vitest/coverage-v8':
+ specifier: 2.1.8
npm-run-all:
specifier: ^4.1.5
version: 4.1.5
@@ -3139,10 +3142,6 @@ packages:
resolution: {integrity: sha512-imAbBGkb+ebQyxKgzv5Hu2nmROxoDOXHh80evxdoXNOrvAnVx7zimzc1Oo5h9RlfV4vPXaE2iM5pOFbvOCClWA==}
engines: {node: '>=6.0.0'}
- '@jridgewell/[email protected]':
- resolution: {integrity: sha512-dSYZh7HhCDtCKm4QakX0xFpsRDqjjtZf/kjI/v3T3Nwt5r8/qz/M19F9ySyOqU94SXBmeG9ttTul+YnR4LOxFA==}
- engines: {node: '>=6.0.0'}
-
'@jridgewell/[email protected]':
resolution: {integrity: sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==}
engines: {node: '>=6.0.0'}
@@ -5651,9 +5650,6 @@ packages:
resolution: {integrity: sha512-vDg9PZ/zi+Nqp6boSOT7plNuthRugEKixDv5sFTIpkE89MmNtEArAShI4mxuX2+UrLEe9pxC1vm2cjm9YlWbJw==}
- '@types/[email protected]':
- resolution: {integrity: sha512-Fll2FZ1riMjNmlmJOdAyY5pUbkftXslB5DgEzlIuNaiWhXd00FhWxVC/r4yV/4wBb9JfImTu+jiSvXTkJ7F/gA==}
-
resolution: {integrity: sha512-ywP2X0DYtX3y08eFVx5fNIw7/uIv8hYUKgXoK8oayJlLnKcRfEYCxWMVE1XagUdVtCJlZT1AU4LXEABW+L1Peg==}
@@ -5868,6 +5864,15 @@ packages:
peerDependencies:
vite: ^4.2.0 || ^5.0.0
+ '@vitest/[email protected]':
+ resolution: {integrity: sha512-2Y7BPlKH18mAZYAW1tYByudlCYrQyl5RGvnnDYJKW5tCiO5qg3KSAy3XAxcxKz900a0ZXxWtKrMuZLe3lKBpJw==}
+ peerDependencies:
+ '@vitest/browser': 2.1.8
+ vitest: 2.1.8
+ peerDependenciesMeta:
+ '@vitest/browser':
+ optional: true
+
'@vitest/[email protected]':
resolution: {integrity: sha512-Nm5kJmYw6P2BxhJPkO3eKKhGYKRsnqJqf+r0yOGRKpEP+bSCBDsjXgiu1/5QFrnPMEgzfC38ZEjvCFgaNBC0Eg==}
@@ -8676,6 +8681,10 @@ packages:
resolution: {integrity: sha512-n3s8EwkdFIJCG3BPKBYvskgXGoy88ARzvegkitk60NxRdwltLOTaH7CUiMRXvwYorl0Q712iEjcWB+fK/MrWVw==}
engines: {node: '>=10'}
+ resolution: {integrity: sha512-yg2d+Em4KizZC5niWhQaIomgf5WlL4vOOjZ5xGCmF8SnPE/mDWWXgvRExdcpCgh9lLRRa1/fSYp2ymmbJ1pI+A==}
+ engines: {node: '>=10'}
+
resolution: {integrity: sha512-BewmUXImeuRk2YY0PVbxgKAysvhRPUQE0h5QRM++nVWyubKGV0l8qQ5op8+B2DOmwSe63Jivj0BjkPQVf8fP5g==}
engines: {node: '>=8'}
@@ -9178,6 +9187,9 @@ packages:
resolution: {integrity: sha512-ISQTe55T2ao7XtlAStud6qwYPZjE4GK1S/BeVPus4jrq6JuOnQ00YKQC581RWhR122W7msZV263KzVeLoqidyQ==}
engines: {node: '>=12'}
+ resolution: {integrity: sha512-L0WhttDl+2BOsybvEOLK7fW3UA0OQ0IQ2d6Zl2x/a6vVRs3bAY0ECOSHHeL5jD+SbOpOCUEi0y1DgHEn9Qn1AQ==}
+
resolution: {integrity: sha512-g3FeP20LNwhALb/6Cz6Dd4F2ngze0jz7tbzrD2wAV+o9FeNHe4rL+yK2md0J/fiSf1sa1ADhXqi5+oVwOM/eGw==}
engines: {node: '>=8'}
@@ -11998,6 +12010,10 @@ packages:
resolution: {integrity: sha512-cAGWPIyOHU6zlmg88jwm7VRyXnMN7iV68OGAbYDk/Mh/xC/pzVPlQtY6ngoIH/5/tciuhGfvESU8GrHrcxD56w==}
engines: {node: '>=8'}
+ resolution: {integrity: sha512-pFYqmTw68LXVjeWJMST4+borgQP2AyMNbg1BpZh9LbyhUeNkeaPF9gzfPGUAnSMV3qPYdWUwDIjjCLiSDOl7vg==}
+ engines: {node: '>=18'}
+
resolution: {integrity: sha512-N+8UisAXDGk8PFXP4HAzVR9nbfmVJ3zYLAWiTIoqC5v5isinhr+r5uaO8+7r3BMfuNIufIsA7RdpVgacC2cSpw==}
@@ -12063,6 +12079,10 @@ packages:
resolution: {integrity: sha512-al6n+QEANGFOMf/dmUMsuS5/r9B06uwlyNjZZql/zv8J7ybHCgoihBNORZCY2mzUuAnomQa2JdhyHKzZxPCrFA==}
engines: {node: ^18.0.0 || >=20.0.0}
+ resolution: {integrity: sha512-weEDEq7Z5eTHPDh4xjX789+fHfF+P8boiFB+0vbWzpbnbsEr/GRaohi/uMKxg8RZMXnl1ItAi/IUHWMsjDV7kQ==}
+ engines: {node: '>=14.0.0'}
+
resolution: {integrity: sha512-op4nsTR47R6p0vMUUoYl/a+ljLFVtlfaXkLQmqfLR1qHma1h/ysYk4hEXZ880bf2CYgTskvTa/e196Vd5dDQXw==}
engines: {node: '>=14.0.0'}
@@ -12824,18 +12844,6 @@ packages:
utf-8-validate:
optional: true
- resolution: {integrity: sha512-8VbfWfHLbbwu3+N6OKsOMpBdT4kXPDDB9cJk2bJ6mh9ucxdlnNvH1e+roYkKmN9Nxw2yjz7VzeO9oOz2zJ04Pw==}
- engines: {node: '>=10.0.0'}
- peerDependencies:
- bufferutil: ^4.0.1
- utf-8-validate: '>=5.0.2'
- peerDependenciesMeta:
- bufferutil:
- optional: true
- utf-8-validate:
- optional: true
-
resolution: {integrity: sha512-RKW2aJZMXeMxVpnZ6bck+RswznaxmzdULiBr6KY7XkTnW8uvt0iT9H5DkHUChXrc+uurzwa0rVI16n/Xzjdz1w==}
engines: {node: '>=10.0.0'}
@@ -13051,7 +13059,7 @@ snapshots:
'@ampproject/[email protected]':
dependencies:
- '@jridgewell/gen-mapping': 0.3.5
+ '@jridgewell/gen-mapping': 0.3.8
'@jridgewell/trace-mapping': 0.3.25
'@aws-crypto/[email protected]':
@@ -13498,8 +13506,8 @@ snapshots:
dependencies:
- '@babel/types': 7.24.7
- '@jridgewell/gen-mapping': 0.3.5
+ '@babel/types': 7.26.7
+ '@jridgewell/gen-mapping': 0.3.8
'@jridgewell/trace-mapping': 0.3.25
jsesc: 2.5.2
@@ -13538,21 +13546,21 @@ snapshots:
dependencies:
- '@babel/types': 7.24.7
+ '@babel/types': 7.26.7
dependencies:
'@babel/template': 7.24.7
- '@babel/types': 7.24.7
+ '@babel/types': 7.26.7
dependencies:
- '@babel/types': 7.24.7
+ '@babel/types': 7.26.7
dependencies:
'@babel/traverse': 7.24.7([email protected])
- '@babel/types': 7.24.7
+ '@babel/types': 7.26.7
transitivePeerDependencies:
- supports-color
@@ -13601,13 +13609,13 @@ snapshots:
dependencies:
'@babel/traverse': 7.24.7([email protected])
- '@babel/types': 7.24.7
+ '@babel/types': 7.26.7
transitivePeerDependencies:
- supports-color
dependencies:
- '@babel/types': 7.24.7
+ '@babel/types': 7.26.7
'@babel/[email protected]': {}
@@ -13624,7 +13632,7 @@ snapshots:
dependencies:
'@babel/template': 7.24.7
- '@babel/types': 7.24.7
+ '@babel/types': 7.26.7
dependencies:
@@ -13775,8 +13783,8 @@ snapshots:
dependencies:
'@babel/code-frame': 7.24.7
- '@babel/parser': 7.24.7
- '@babel/types': 7.24.7
+ '@babel/parser': 7.26.7
+ '@babel/types': 7.26.7
dependencies:
@@ -13847,8 +13855,7 @@ snapshots:
'@babel/helper-string-parser': 7.25.9
'@babel/helper-validator-identifier': 7.25.9
- optional: true
+ '@bcoe/[email protected]': {}
'@bundled-es-modules/[email protected]':
dependencies:
@@ -14502,7 +14509,7 @@ snapshots:
'@inquirer/figures': 1.0.7
'@inquirer/type': 2.0.0
'@types/mute-stream': 0.0.4
- '@types/node': 22.12.0
+ '@types/node': 22.13.4
'@types/wrap-ansi': 3.0.0
ansi-escapes: 4.3.2
cli-width: 4.1.0
@@ -14540,8 +14547,7 @@ snapshots:
resolve-from: 5.0.0
optional: true
- '@istanbuljs/[email protected]':
- optional: true
+ '@istanbuljs/[email protected]': {}
dependencies:
@@ -14731,10 +14737,7 @@ snapshots:
'@jridgewell/sourcemap-codec': 1.5.0
'@jridgewell/trace-mapping': 0.3.25
- '@jridgewell/[email protected]': {}
-
- '@jridgewell/[email protected]':
- optional: true
+ '@jridgewell/[email protected]': {}
'@jridgewell/[email protected]': {}
@@ -14747,7 +14750,7 @@ snapshots:
'@jridgewell/[email protected]':
dependencies:
- '@jridgewell/resolve-uri': 3.1.1
+ '@jridgewell/resolve-uri': 3.1.2
'@jridgewell/sourcemap-codec': 1.5.0
'@jridgewell/[email protected]':
@@ -17208,7 +17211,7 @@ snapshots:
'@supabase/node-fetch': 2.6.15
'@types/phoenix': 1.6.4
'@types/ws': 8.5.10
- ws: 8.18.0
+ ws: 8.18.1
transitivePeerDependencies:
- bufferutil
- utf-8-validate
@@ -17218,7 +17221,7 @@ snapshots:
'@supabase/node-fetch': 2.6.15
'@types/phoenix': 1.6.4
'@types/ws': 8.5.10
- ws: 8.18.0
+ ws: 8.18.1
transitivePeerDependencies:
- bufferutil
- utf-8-validate
@@ -17482,12 +17485,12 @@ snapshots:
dependencies:
- '@babel/types': 7.24.7
+ '@babel/types': 7.26.7
dependencies:
- '@babel/parser': 7.24.7
- '@babel/types': 7.24.7
+ '@babel/parser': 7.26.7
+ '@babel/types': 7.26.7
dependencies:
@@ -17514,7 +17517,7 @@ snapshots:
dependencies:
- '@types/node': 22.12.0
+ '@types/node': 22.13.4
'@types/[email protected]': {}
@@ -17767,15 +17770,15 @@ snapshots:
dependencies:
- '@types/node': 22.12.0
+ '@types/node': 22.13.4
dependencies:
- '@types/node': 22.12.0
+ '@types/node': 22.13.4
dependencies:
- '@types/node': 22.12.0
+ '@types/node': 22.13.4
form-data: 4.0.0
'@types/[email protected]': {}
@@ -17788,17 +17791,13 @@ snapshots:
dependencies:
undici-types: 5.26.5
- '@types/[email protected]':
- dependencies:
- undici-types: 6.20.0
-
dependencies:
undici-types: 6.20.0
dependencies:
- '@types/node': 22.12.0
+ '@types/node': 22.13.4
'@types/[email protected]': {}
@@ -17808,13 +17807,13 @@ snapshots:
dependencies:
- '@types/node': 22.12.0
+ '@types/node': 22.13.4
pg-protocol: 1.7.1
pg-types: 4.0.2
dependencies:
- '@types/node': 22.12.0
+ '@types/node': 22.13.4
pg-protocol: 1.7.1
pg-types: 2.2.0
@@ -17826,7 +17825,7 @@ snapshots:
dependencies:
- '@types/node': 22.12.0
+ '@types/node': 22.13.4
dependencies:
@@ -17918,7 +17917,7 @@ snapshots:
dependencies:
- '@types/node': 22.12.0
+ '@types/node': 22.13.4
dependencies:
@@ -17949,7 +17948,7 @@ snapshots:
dependencies:
- '@types/node': 22.12.0
+ '@types/node': 22.13.4
optional: true
@@ -18040,6 +18039,24 @@ snapshots:
transitivePeerDependencies:
- supports-color
+ dependencies:
+ '@ampproject/remapping': 2.3.0
+ '@bcoe/v8-coverage': 0.2.3
+ debug: 4.4.0([email protected])
+ istanbul-lib-coverage: 3.2.2
+ istanbul-lib-report: 3.0.1
+ istanbul-lib-source-maps: 5.0.6([email protected])
+ istanbul-reports: 3.1.7
+ magic-string: 0.30.17
+ magicast: 0.3.5
+ std-env: 3.8.0
+ test-exclude: 7.0.1
+ tinyrainbow: 1.2.0
+ transitivePeerDependencies:
+ - supports-color
+
'@vitest/[email protected]':
dependencies:
'@vitest/spy': 3.0.4
@@ -21394,8 +21411,7 @@ snapshots:
- optional: true
dependencies:
@@ -21424,7 +21440,6 @@ snapshots:
istanbul-lib-coverage: 3.2.2
make-dir: 4.0.0
supports-color: 7.2.0
- optional: true
dependencies:
@@ -21435,11 +21450,18 @@ snapshots:
- supports-color
optional: true
+ dependencies:
+ '@jridgewell/trace-mapping': 0.3.25
+ debug: 4.4.0([email protected])
+ istanbul-lib-coverage: 3.2.2
+ transitivePeerDependencies:
+ - supports-color
+
dependencies:
html-escaper: 2.0.2
istanbul-lib-report: 3.0.1
- optional: true
dependencies:
@@ -22200,6 +22222,12 @@ snapshots:
dependencies:
'@jridgewell/sourcemap-codec': 1.5.0
+ dependencies:
+ '@babel/parser': 7.26.7
+ '@babel/types': 7.26.7
+ source-map-js: 1.2.1
+
dependencies:
semver: 6.3.1
@@ -22207,7 +22235,6 @@ snapshots:
dependencies:
semver: 7.7.1
- optional: true
optional: true
@@ -24393,7 +24420,7 @@ snapshots:
'@protobufjs/path': 1.1.2
'@protobufjs/pool': 1.1.0
'@protobufjs/utf8': 1.1.0
- '@types/node': 22.12.0
+ '@types/node': 22.13.4
long: 5.2.3
@@ -25389,8 +25416,7 @@ snapshots:
- optional: true
dependencies:
@@ -26092,6 +26118,12 @@ snapshots:
minimatch: 3.1.2
optional: true
+ dependencies:
+ '@istanbuljs/schema': 0.1.3
+ glob: 10.4.5
+ minimatch: 9.0.5
+
@@ -26146,6 +26178,8 @@ snapshots:
+
@@ -27131,10 +27165,7 @@ snapshots:
-
- optional: true
dependencies: