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 types sql (#33649)

Andrew Valleteauffddcab9b846
diff --git a/packages/pg-meta/src/index.ts b/packages/pg-meta/src/index.ts
index c772acc69f8..7f2062c26c8 100644
--- a/packages/pg-meta/src/index.ts
+++ b/packages/pg-meta/src/index.ts
@@ -2,6 +2,7 @@ import roles from './pg-meta-roles'
import schemas from './pg-meta-schemas'
import * as functions from './pg-meta-functions'
import tablePrivileges from './pg-meta-table-privileges'
+import types from './pg-meta-types'
import version from './pg-meta-version'
import indexes from './pg-meta-indexes'
import columnPrivileges from './pg-meta-column-privileges'
@@ -11,6 +12,7 @@ export default {
schemas,
functions,
tablePrivileges,
+ types,
version,
indexes,
columnPrivileges,
diff --git a/packages/pg-meta/src/pg-meta-types.ts b/packages/pg-meta/src/pg-meta-types.ts
new file mode 100644
index 00000000000..2a3316f902f
--- /dev/null
+++ b/packages/pg-meta/src/pg-meta-types.ts
@@ -0,0 +1,72 @@
+import { z } from 'zod'
+import { DEFAULT_SYSTEM_SCHEMAS } from './constants'
+import { filterByList } from './helpers'
+import { TYPES_SQL } from './sql/types'
+
+const pgTypeZod = z.object({
+ id: z.number(),
+ name: z.string(),
+ schema: z.string(),
+ format: z.string(),
+ enums: z.array(z.string()),
+ attributes: z.array(
+ z.object({
+ name: z.string(),
+ type_id: z.number(),
+ })
+ ),
+ comment: z.string().nullable(),
+})
+
+const pgTypeArrayZod = z.array(pgTypeZod)
+
+function list({
+ includeArrayTypes = false,
+ includeSystemSchemas = false,
+ includedSchemas,
+ excludedSchemas,
+ limit,
+ offset,
+}: {
+ includeArrayTypes?: boolean
+ includeSystemSchemas?: boolean
+ includedSchemas?: string[]
+ excludedSchemas?: string[]
+ limit?: number
+ offset?: number
+} = {}): {
+ sql: string
+ zod: typeof pgTypeArrayZod
+} {
+ let sql = TYPES_SQL
+ if (!includeArrayTypes) {
+ sql += ` and not exists (
+ select from pg_type el
+ where el.oid = t.typelem
+ and el.typarray = t.oid
+ )`
+ }
+ const filter = filterByList(
+ includedSchemas,
+ excludedSchemas,
+ !includeSystemSchemas ? DEFAULT_SYSTEM_SCHEMAS : undefined
+ )
+ if (filter) {
+ sql += ` and n.nspname ${filter}`
+ }
+ if (limit) {
+ sql += ` limit ${limit}`
+ }
+ if (offset) {
+ sql += ` offset ${offset}`
+ }
+ return {
+ sql,
+ zod: pgTypeArrayZod,
+ }
+}
+
+export default {
+ list,
+ zod: pgTypeZod,
+}
diff --git a/packages/pg-meta/src/sql/types.ts b/packages/pg-meta/src/sql/types.ts
new file mode 100644
index 00000000000..cc73a14c33c
--- /dev/null
+++ b/packages/pg-meta/src/sql/types.ts
@@ -0,0 +1,49 @@
+export const TYPES_SQL = /* SQL */ `
+select
+ t.oid::int8 as id,
+ t.typname as name,
+ n.nspname as schema,
+ format_type (t.oid, null) as format,
+ coalesce(t_enums.enums, '[]') as enums,
+ coalesce(t_attributes.attributes, '[]') as attributes,
+ obj_description (t.oid, 'pg_type') as comment
+from
+ pg_type t
+ left join pg_namespace n on n.oid = t.typnamespace
+ left join (
+ select
+ enumtypid,
+ jsonb_agg(enumlabel order by enumsortorder) as enums
+ from
+ pg_enum
+ group by
+ enumtypid
+ ) as t_enums on t_enums.enumtypid = t.oid
+ left join (
+ select
+ oid,
+ jsonb_agg(
+ jsonb_build_object('name', a.attname, 'type_id', a.atttypid::int8)
+ order by a.attnum asc
+ ) as attributes
+ from
+ pg_class c
+ join pg_attribute a on a.attrelid = c.oid
+ where
+ c.relkind = 'c' and not a.attisdropped
+ group by
+ c.oid
+ ) as t_attributes on t_attributes.oid = t.typrelid
+where
+ (
+ t.typrelid = 0
+ or (
+ select
+ c.relkind = 'c'
+ from
+ pg_class c
+ where
+ c.oid = t.typrelid
+ )
+ )
+`
diff --git a/packages/pg-meta/test/types.test.ts b/packages/pg-meta/test/types.test.ts
new file mode 100644
index 00000000000..0a3480e4c42
--- /dev/null
+++ b/packages/pg-meta/test/types.test.ts
@@ -0,0 +1,118 @@
+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 types', async ({ executeQuery }) => {
+ const { sql, zod } = await pgMeta.types.list()
+ const res = zod.parse(await executeQuery(sql))
+
+ expect(res.find(({ name }) => name === 'user_status')).toMatchInlineSnapshot(
+ { id: expect.any(Number) },
+ `
+ {
+ "attributes": [],
+ "comment": null,
+ "enums": [
+ "ACTIVE",
+ "INACTIVE",
+ ],
+ "format": "user_status",
+ "id": Any<Number>,
+ "name": "user_status",
+ "schema": "public",
+ }
+ `
+ )
+})
+
+withTestDatabase('list types with included schemas', async ({ executeQuery }) => {
+ const { sql, zod } = await pgMeta.types.list({
+ includedSchemas: ['public'],
+ })
+ const res = zod.parse(await executeQuery(sql))
+
+ expect(res.length).toBeGreaterThan(0)
+ res.forEach((type) => {
+ expect(type.schema).toBe('public')
+ })
+})
+
+withTestDatabase('list types with excluded schemas', async ({ executeQuery }) => {
+ const { sql, zod } = await pgMeta.types.list({
+ excludedSchemas: ['public'],
+ })
+ const res = zod.parse(await executeQuery(sql))
+
+ res.forEach((type) => {
+ expect(type.schema).not.toBe('public')
+ })
+})
+
+withTestDatabase(
+ 'list types with excluded schemas and include System Schemas',
+ async ({ executeQuery }) => {
+ const { sql, zod } = await pgMeta.types.list({
+ excludedSchemas: ['public'],
+ includeSystemSchemas: true,
+ })
+ const res = zod.parse(await executeQuery(sql))
+
+ expect(res.length).toBeGreaterThan(0)
+ res.forEach((type) => {
+ expect(type.schema).not.toBe('public')
+ })
+ }
+)
+
+withTestDatabase('composite type attributes', async ({ executeQuery }) => {
+ await executeQuery(`create type test_composite as (id int8, data text);`)
+
+ const { sql, zod } = await pgMeta.types.list()
+ const res = zod.parse(await executeQuery(sql))
+
+ expect(res.find(({ name }) => name === 'test_composite')).toMatchInlineSnapshot(
+ { id: expect.any(Number) },
+ `
+ {
+ "attributes": [
+ {
+ "name": "id",
+ "type_id": 20,
+ },
+ {
+ "name": "data",
+ "type_id": 25,
+ },
+ ],
+ "comment": null,
+ "enums": [],
+ "format": "test_composite",
+ "id": Any<Number>,
+ "name": "test_composite",
+ "schema": "public",
+ }
+ `
+ )
+})