The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
chore(pg-meta): migrate publications (#33732)
Andrew Valleteau791422b2d09a
diff --git a/packages/pg-meta/src/index.ts b/packages/pg-meta/src/index.tsindex 1151984b787..553ae5ee879 100644--- a/packages/pg-meta/src/index.ts+++ b/packages/pg-meta/src/index.ts@@ -4,6 +4,7 @@ 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 publications from './pg-meta-publications'import extensions from './pg-meta-extensions'import config from './pg-meta-config'import materializedViews from './pg-meta-materialized-views'@@ -23,6 +24,7 @@ export default {tables,functions,tablePrivileges,+ publications,extensions,config,materializedViews,diff --git a/packages/pg-meta/src/pg-meta-publications.ts b/packages/pg-meta/src/pg-meta-publications.tsnew file mode 100644index 00000000000..ad11e6e7752--- /dev/null+++ b/packages/pg-meta/src/pg-meta-publications.ts@@ -0,0 +1,243 @@+import { ident, literal } from './pg-format'+import { PUBLICATIONS_SQL } from './sql/publications'+import { z } from 'zod'++const pgPublicationTableZod = z.object({+ id: z.number().optional(),+ name: z.string(),+ schema: z.string(),+})++const pgPublicationZod = z.object({+ id: z.number(),+ name: z.string(),+ owner: z.string(),+ publish_insert: z.boolean(),+ publish_update: z.boolean(),+ publish_delete: z.boolean(),+ publish_truncate: z.boolean(),+ tables: z.array(pgPublicationTableZod).nullable(),+})++const pgPublicationArrayZod = z.array(pgPublicationZod)+const pgPublicationOptionalZod = z.optional(pgPublicationZod)++export type PGPublication = z.infer<typeof pgPublicationZod>++function list({+ limit,+ offset,+}: {+ limit?: number+ offset?: number+} = {}): {+ sql: string+ zod: typeof pgPublicationArrayZod+} {+ let sql = `with publications as (${PUBLICATIONS_SQL}) select * from publications`+ if (limit) {+ sql += ` limit ${limit}`+ }+ if (offset) {+ sql += ` offset ${offset}`+ }+ return {+ sql,+ zod: pgPublicationArrayZod,+ }+}++type PublicationIdentifier = Pick<PGPublication, 'id'> | Pick<PGPublication, 'name'>++function getIdentifierWhereClause(identifier: PublicationIdentifier) {+ if ('id' in identifier && identifier.id) {+ return `${ident('id')} = ${literal(identifier.id)}`+ } else if ('name' in identifier && identifier.name) {+ return `${ident('name')} = ${literal(identifier.name)}`+ }+ throw new Error('Must provide either id or name')+}++function retrieve(identifier: PublicationIdentifier): {+ sql: string+ zod: typeof pgPublicationOptionalZod+} {+ const sql = `with publications as (${PUBLICATIONS_SQL}) select * from publications where ${getIdentifierWhereClause(identifier)};`+ return {+ sql,+ zod: pgPublicationOptionalZod,+ }+}++type PublicationCreateParams = {+ name: string+ publish_insert?: boolean+ publish_update?: boolean+ publish_delete?: boolean+ publish_truncate?: boolean+ tables?: string[] | null+}++function create({+ name,+ publish_insert = false,+ publish_update = false,+ publish_delete = false,+ publish_truncate = false,+ tables = null,+}: PublicationCreateParams): { sql: string } {+ let tableClause: string+ if (tables === undefined || tables === null) {+ tableClause = 'FOR ALL TABLES'+ } else if (tables.length === 0) {+ tableClause = ''+ } else {+ tableClause = `FOR TABLE ${tables+ .map((t) => {+ if (!t.includes('.')) {+ return ident(t)+ }+ const [schema, ...rest] = t.split('.')+ const table = rest.join('.')+ return `${ident(schema)}.${ident(table)}`+ })+ .join(',')}`+ }++ const publishOps = [+ ...(publish_insert ? ['insert'] : []),+ ...(publish_update ? ['update'] : []),+ ...(publish_delete ? ['delete'] : []),+ ...(publish_truncate ? ['truncate'] : []),+ ]++ const sql = `CREATE PUBLICATION ${ident(name)} ${tableClause} WITH (publish = '${publishOps.join(+ ','+ )}');`+ return { sql }+}++type PublicationUpdateParams = {+ name?: string+ owner?: string+ publish_insert?: boolean+ publish_update?: boolean+ publish_delete?: boolean+ publish_truncate?: boolean+ tables?: string[] | null+}++function update(+ identifier: PublicationIdentifier,+ params: PublicationUpdateParams+): { sql: string } {+ const sql = `+do $$+declare+ old record;+ new_name text := ${params.name === undefined ? null : literal(params.name)};+ new_owner text := ${params.owner === undefined ? null : literal(params.owner)};+ new_publish_insert bool := ${params.publish_insert ?? null};+ new_publish_update bool := ${params.publish_update ?? null};+ new_publish_delete bool := ${params.publish_delete ?? null};+ new_publish_truncate bool := ${params.publish_truncate ?? null};+ new_tables text := ${+ params.tables === undefined+ ? null+ : literal(+ params.tables === null+ ? 'all tables'+ : params.tables+ .map((t) => {+ if (!t.includes('.')) {+ return ident(t)+ }+ const [schema, ...rest] = t.split('.')+ const table = rest.join('.')+ return `${ident(schema)}.${ident(table)}`+ })+ .join(', ')+ )+ };+begin+ with publications as (${PUBLICATIONS_SQL})+ select * into old from publications where ${getIdentifierWhereClause(identifier)};+ if old is null then+ raise exception 'Cannot find publication with %', ${literal(getIdentifierWhereClause(identifier))};+ end if;+ if new_tables is null then+ null;+ elsif new_tables = 'all tables' AND old.tables is not null then+ -- Need to recreate because going from list of tables <-> all tables with alter is not possible.+ execute(format('drop publication %1$I; create publication %1$I for all tables;', old.name));+ else+ if old.tables is null then+ -- Need to recreate because going from list of tables <-> all tables with alter is not possible.+ execute(format('drop publication %1$I; create publication %1$I;', old.name));+ elsif exists(select from pg_publication_rel where prpubid = old.id) then+ execute(+ format(+ 'alter publication %I drop table %s',+ old.name,+ (select string_agg(prrelid::regclass::text, ', ') from pg_publication_rel where prpubid = old.id)+ )+ );+ end if;++ -- At this point the publication must have no tables.+ if new_tables != '' then+ execute(format('alter publication %I add table %s', old.name, new_tables));+ end if;+ end if;++ execute(+ format(+ 'alter publication %I set (publish = %L);',+ old.name,+ concat_ws(+ ', ',+ case when coalesce(new_publish_insert, old.publish_insert) then 'insert' end,+ case when coalesce(new_publish_update, old.publish_update) then 'update' end,+ case when coalesce(new_publish_delete, old.publish_delete) then 'delete' end,+ case when coalesce(new_publish_truncate, old.publish_truncate) then 'truncate' end+ )+ )+ );++ if new_owner is not null then+ execute(format('alter publication %I owner to %I;', old.name, new_owner));+ end if;++ -- Using the same name in the rename clause gives an error, so only do it if the new name is different.+ if new_name is not null and new_name != old.name then+ execute(format('alter publication %I rename to %I;', old.name, new_name));+ end if;+end $$;`+ return { sql }+}++function remove(identifier: PublicationIdentifier): { sql: string } {+ const sql = `+ do $$+ declare+ v_name name;+ begin+ with publications as (${PUBLICATIONS_SQL})+ select name into v_name from publications where ${getIdentifierWhereClause(identifier)};+ if v_name is not null then+ execute(format('drop publication if exists %I', v_name));+ end if;+ end+ $$;+ `+ return { sql }+}++export default {+ list,+ retrieve,+ create,+ update,+ remove,+ zod: pgPublicationZod,+}diff --git a/packages/pg-meta/src/sql/publications.ts b/packages/pg-meta/src/sql/publications.tsnew file mode 100644index 00000000000..ea778615d32--- /dev/null+++ b/packages/pg-meta/src/sql/publications.ts@@ -0,0 +1,38 @@+export const PUBLICATIONS_SQL = /* SQL */ `+SELECT+ p.oid :: int8 AS id,+ p.pubname AS name,+ p.pubowner::regrole::text AS owner,+ p.pubinsert AS publish_insert,+ p.pubupdate AS publish_update,+ p.pubdelete AS publish_delete,+ p.pubtruncate AS publish_truncate,+ CASE+ WHEN p.puballtables THEN NULL+ ELSE pr.tables+ END AS tables+FROM+ pg_catalog.pg_publication AS p+ LEFT JOIN LATERAL (+ SELECT+ COALESCE(+ array_agg(+ json_build_object(+ 'id',+ c.oid :: int8,+ 'name',+ c.relname,+ 'schema',+ nc.nspname+ )+ ),+ '{}'+ ) AS tables+ FROM+ pg_catalog.pg_publication_rel AS pr+ JOIN pg_class AS c ON pr.prrelid = c.oid+ join pg_namespace as nc on c.relnamespace = nc.oid+ WHERE+ pr.prpubid = p.oid+ ) AS pr ON 1 = 1+`diff --git a/packages/pg-meta/test/publications.test.ts b/packages/pg-meta/test/publications.test.tsnew file mode 100644index 00000000000..308ffb995a3--- /dev/null+++ b/packages/pg-meta/test/publications.test.ts@@ -0,0 +1,321 @@+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()+ }+ })+}+const cleanNondet = (res: any) => {+ if (!res.data?.tables) return res+ const tables = res.data.tables.map(({ id, ...rest }: any) => rest)+ return { ...res, data: { ...res.data, tables } }+}++withTestDatabase('retrieve, create, update, delete', async ({ executeQuery }) => {+ // Create publication+ const { sql: createSql } = pgMeta.publications.create({+ name: 'a',+ publish_insert: true,+ publish_update: true,+ publish_delete: true,+ publish_truncate: false,+ tables: ['users'],+ })+ await executeQuery(createSql)++ // Retrieve publication+ const { sql: retrieveSql, zod: retrieveZod } = pgMeta.publications.retrieve({ name: 'a' })+ const res = retrieveZod.parse((await executeQuery(retrieveSql))[0])+ expect(cleanNondet({ data: res })).toMatchInlineSnapshot(+ { data: { id: expect.any(Number) } },+ `+ {+ "data": {+ "id": Any<Number>,+ "name": "a",+ "owner": "postgres",+ "publish_delete": true,+ "publish_insert": true,+ "publish_truncate": false,+ "publish_update": true,+ "tables": [+ {+ "name": "users",+ "schema": "public",+ },+ ],+ },+ }+ `+ )++ // Update publication+ const { sql: updateSql } = pgMeta.publications.update(res!, {+ name: 'b',+ publish_insert: false,+ tables: [],+ })+ await executeQuery(updateSql)++ // Verify update+ const { sql: retrieveUpdatedSql, zod: retrieveUpdatedZod } = pgMeta.publications.retrieve({+ name: 'b',+ })+ const updatedRes = retrieveUpdatedZod.parse((await executeQuery(retrieveUpdatedSql))[0])+ expect(cleanNondet({ data: updatedRes })).toMatchInlineSnapshot(+ { data: { id: expect.any(Number) } },+ `+ {+ "data": {+ "id": Any<Number>,+ "name": "b",+ "owner": "postgres",+ "publish_delete": true,+ "publish_insert": false,+ "publish_truncate": false,+ "publish_update": true,+ "tables": [],+ },+ }+ `+ )++ // Remove publication+ const { sql: removeSql } = pgMeta.publications.remove(updatedRes!)+ await executeQuery(removeSql)++ // Verify removal+ const { sql: verifyRemoveSql } = pgMeta.publications.retrieve({ id: updatedRes!.id })+ const finalRes = await executeQuery(verifyRemoveSql)+ expect(finalRes).toHaveLength(0)+})++withTestDatabase('tables with uppercase', async ({ executeQuery }) => {+ // Create table with uppercase name+ await executeQuery(`+ CREATE TABLE public."T" (+ id SERIAL PRIMARY KEY+ );+ `)++ // Create publication+ const { sql: createSql } = pgMeta.publications.create({+ name: 'pub',+ tables: ['T'],+ })+ await executeQuery(createSql)++ // Verify creation+ const { sql: retrieveSql, zod: retrieveZod } = pgMeta.publications.retrieve({ name: 'pub' })+ let res = retrieveZod.parse((await executeQuery(retrieveSql))[0])+ expect(cleanNondet({ data: res })).toMatchInlineSnapshot(+ { data: { id: expect.any(Number) } },+ `+ {+ "data": {+ "id": Any<Number>,+ "name": "pub",+ "owner": "postgres",+ "publish_delete": false,+ "publish_insert": false,+ "publish_truncate": false,+ "publish_update": false,+ "tables": [+ {+ "name": "T",+ "schema": "public",+ },+ ],+ },+ }+ `+ )++ // Update publication+ const { sql: updateSql } = pgMeta.publications.update(+ { id: res!.id },+ {+ tables: ['T'],+ }+ )+ await executeQuery(updateSql)++ // Verify update+ const { sql: retrieveUpdatedSql, zod: retrieveUpdatedZod } = pgMeta.publications.retrieve({+ name: 'pub',+ })+ res = retrieveUpdatedZod.parse((await executeQuery(retrieveUpdatedSql))[0])+ expect(cleanNondet({ data: res })).toMatchInlineSnapshot(+ { data: { id: expect.any(Number) } },+ `+ {+ "data": {+ "id": Any<Number>,+ "name": "pub",+ "owner": "postgres",+ "publish_delete": false,+ "publish_insert": false,+ "publish_truncate": false,+ "publish_update": false,+ "tables": [+ {+ "name": "T",+ "schema": "public",+ },+ ],+ },+ }+ `+ )++ // Remove publication+ const { sql: removeSql } = pgMeta.publications.remove(res!)+ await executeQuery(removeSql)+})++withTestDatabase('FOR ALL TABLES', async ({ executeQuery }) => {+ // Create publication+ const { sql: createSql } = pgMeta.publications.create({+ name: 'for_all',+ publish_insert: true,+ publish_update: true,+ publish_delete: true,+ publish_truncate: false,+ })+ await executeQuery(createSql)++ // Retrieve and verify+ const { sql: retrieveSql, zod: retrieveZod } = pgMeta.publications.retrieve({ name: 'for_all' })+ const res = retrieveZod.parse((await executeQuery(retrieveSql))[0])+ expect(cleanNondet({ data: res })).toMatchInlineSnapshot(+ { data: { id: expect.any(Number) } },+ `+ {+ "data": {+ "id": Any<Number>,+ "name": "for_all",+ "owner": "postgres",+ "publish_delete": true,+ "publish_insert": true,+ "publish_truncate": false,+ "publish_update": true,+ "tables": null,+ },+ }+ `+ )++ // Remove publication+ const { sql: removeSql } = pgMeta.publications.remove(res!)+ await executeQuery(removeSql)+})++withTestDatabase('update no tables -> all tables', async ({ executeQuery }) => {+ // Create publication+ const { sql: createSql } = pgMeta.publications.create({+ name: 'pub',+ tables: [],+ })+ await executeQuery(createSql)++ // Retrieve created publication+ const { sql: retrieveSql, zod: retrieveZod } = pgMeta.publications.retrieve({ name: 'pub' })+ const res = retrieveZod.parse((await executeQuery(retrieveSql))[0])++ // Update publication+ const { sql: updateSql } = pgMeta.publications.update(res!, {+ tables: null,+ })+ await executeQuery(updateSql)++ // Verify update+ const { sql: verifyRetrieveSql, zod: verifyRetrieveZod } = pgMeta.publications.retrieve({+ name: 'pub',+ })+ const updatedRes = verifyRetrieveZod.parse((await executeQuery(verifyRetrieveSql))[0])+ expect(cleanNondet({ data: updatedRes })).toMatchInlineSnapshot(+ { data: { id: expect.any(Number) } },+ `+ {+ "data": {+ "id": Any<Number>,+ "name": "pub",+ "owner": "postgres",+ "publish_delete": false,+ "publish_insert": false,+ "publish_truncate": false,+ "publish_update": false,+ "tables": null,+ },+ }+ `+ )++ // Remove publication+ const { sql: removeSql } = pgMeta.publications.remove(updatedRes!)+ await executeQuery(removeSql)+})++withTestDatabase('update all tables -> no tables', async ({ executeQuery }) => {+ // Create publication+ const { sql: createSql } = pgMeta.publications.create({+ name: 'pub',+ tables: null,+ })+ await executeQuery(createSql)++ // Retrieve created publication+ const { sql: retrieveSql, zod: retrieveZod } = pgMeta.publications.retrieve({ name: 'pub' })+ const res = retrieveZod.parse((await executeQuery(retrieveSql))[0])++ // Update publication+ const { sql: updateSql } = pgMeta.publications.update(res!, {+ tables: [],+ })+ await executeQuery(updateSql)++ // Verify update+ const { sql: verifyRetrieveSql, zod: verifyRetrieveZod } = pgMeta.publications.retrieve({+ name: 'pub',+ })+ const updatedRes = verifyRetrieveZod.parse((await executeQuery(verifyRetrieveSql))[0])+ expect(cleanNondet({ data: updatedRes })).toMatchInlineSnapshot(+ { data: { id: expect.any(Number) } },+ `+ {+ "data": {+ "id": Any<Number>,+ "name": "pub",+ "owner": "postgres",+ "publish_delete": false,+ "publish_insert": false,+ "publish_truncate": false,+ "publish_update": false,+ "tables": [],+ },+ }+ `+ )++ // Remove publication+ const { sql: removeSql } = pgMeta.publications.remove(updatedRes!)+ await executeQuery(removeSql)+})