Skip to content

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

fix(pg-meta): generate privilege, publication, role and schema SQL that servers can statically check (#51457)

Ping-Min Lin700365ffba58
diff --git a/packages/pg-meta/src/pg-meta-column-privileges.ts b/packages/pg-meta/src/pg-meta-column-privileges.ts
index 0e9a2f47322..ca331e3a8b2 100644
--- a/packages/pg-meta/src/pg-meta-column-privileges.ts
+++ b/packages/pg-meta/src/pg-meta-column-privileges.ts
@@ -145,6 +145,21 @@ function list({
}
}
+/**
+ * The `%I.%I` arguments of a `format()` call that name the table of the
+ * `col` record (a `pg_attribute` row): its schema and name.
+ *
+ * `%s` with `col.attrelid::regclass` would build the same statement, but `%s`
+ * substitutes raw text, so a server that statically checks `DO` blocks (such as
+ * Multigres) can't prove the statement fixed and rejects the block. A format
+ * string made only of `%I`/`%L` conversions can be checked.
+ */
+const colRelationIdentArgs = safeSql`(select n.nspname from pg_class c join pg_namespace n on n.oid = c.relnamespace where c.oid = col.attrelid), (select relname from pg_class where oid = col.attrelid)`
+
+function granteeSql(grantee: string): SafeSqlFragment {
+ return grantee.toLowerCase() === 'public' ? safeSql`public` : ident(grantee)
+}
+
type ColumnPrivilegesGrant = z.infer<typeof privilegeGrant>
function grant(grants: ColumnPrivilegesGrant[]): { sql: SafeSqlFragment } {
const sql = safeSql`
@@ -161,13 +176,11 @@ from pg_attribute a
where a.attrelid = ${literal(relationId)}
and a.attnum = ${literal(columnNumber)}
into col;
-execute format(
- 'grant ${keyword(privilegeType)} (%I) on %s to ${
- grantee.toLowerCase() === 'public' ? safeSql`public` : ident(grantee)
- } ${isGrantable ? safeSql`with grant option` : safeSql``}',
- col.attname,
- col.attrelid::regclass
-);`
+execute format(${literal(
+ `grant ${keyword(privilegeType)} (%I) on %I.%I to ${granteeSql(grantee)}${
+ isGrantable ? ' with grant option' : ''
+ }`
+ )}, col.attname, ${colRelationIdentArgs});`
}),
'\n'
)}
@@ -192,13 +205,9 @@ from pg_attribute a
where a.attrelid = ${literal(relationId)}
and a.attnum = ${literal(columnNumber)}
into col;
-execute format(
- 'revoke ${keyword(privilegeType)} (%I) on %s from ${
- grantee.toLowerCase() === 'public' ? safeSql`public` : ident(grantee)
- }',
- col.attname,
- col.attrelid::regclass
-);`
+execute format(${literal(
+ `revoke ${keyword(privilegeType)} (%I) on %I.%I from ${granteeSql(grantee)}`
+ )}, col.attname, ${colRelationIdentArgs});`
}),
'\n'
)}
diff --git a/packages/pg-meta/src/pg-meta-publications.ts b/packages/pg-meta/src/pg-meta-publications.ts
index eecd5d1c41e..129ce89a71b 100644
--- a/packages/pg-meta/src/pg-meta-publications.ts
+++ b/packages/pg-meta/src/pg-meta-publications.ts
@@ -129,6 +129,30 @@ type PublicationUpdateParams = {
tables?: string[] | null
}
+/**
+ * Splits a `schema.table` (or bare `table`) entry of `tables` into its schema
+ * and table name. A bare name has no schema, so it resolves via the search path.
+ * Mirrors how the entries were previously quoted: the first `.` separates the
+ * schema, and any further `.` stay part of the table name.
+ */
+function splitPublicationTable(t: string): { schema: string | null; name: string } {
+ if (!t.includes('.')) return { schema: null, name: t }
+ const [schema, ...rest] = t.split('.')
+ return { schema, name: rest.join('.') }
+}
+
+function textArray(values: Array<string | null>): SafeSqlFragment {
+ return safeSql`array[${joinSqlFragments(
+ values.map((v) => literal(v)),
+ ', '
+ )}]::text[]`
+}
+
+// The `execute` statements in the function body below follow the same rules as
+// the ones in `pg-meta-table-privileges.ts`: no parentheses around the payload,
+// and `format()` strings made only of `%I`/`%L` conversions (never `%s`), so a
+// server that statically checks `DO` blocks (such as Multigres) can prove they
+// build fixed statements.
function update(
id: number,
{
@@ -141,91 +165,86 @@ function update(
tables,
}: PublicationUpdateParams
): { sql: SafeSqlFragment } {
+ // 'keep' leaves the tables alone, 'all' publishes all tables, 'list' replaces
+ // the published tables with the given ones.
+ const tablesMode = tables === undefined ? 'keep' : tables === null ? 'all' : 'list'
+ const tableEntries = (tables ?? []).map(splitPublicationTable)
+
const sql = safeSql`
do $$
declare
id oid := ${literal(id)};
old record;
+ r record;
+ i int;
new_name text := ${name === undefined ? literal(null) : literal(name)};
new_owner text := ${owner === undefined ? literal(null) : literal(owner)};
new_publish_insert bool := ${literal(publish_insert ?? null)};
new_publish_update bool := ${literal(publish_update ?? null)};
new_publish_delete bool := ${literal(publish_delete ?? null)};
new_publish_truncate bool := ${literal(publish_truncate ?? null)};
- new_tables text := ${
- tables === undefined
- ? literal(null)
- : literal(
- tables === null
- ? 'all tables'
- : tables
- .map((t) => {
- if (!t.includes('.')) {
- return ident(t)
- }
-
- const [schema, ...rest] = t.split('.')
- const table = rest.join('.')
- return safeSql`${ident(schema)}.${ident(table)}`
- })
- .join(',')
- )
- };
+ tables_mode text := ${literal(tablesMode)};
+ new_table_schemas text[] := ${textArray(tableEntries.map((t) => t.schema))};
+ new_table_names text[] := ${textArray(tableEntries.map((t) => t.name))};
begin
select * into old from pg_publication where oid = id;
if old is null then
raise exception 'Cannot find publication with id %', id;
end if;
- if new_tables is null then
+ if tables_mode = 'keep' then
null;
- elsif new_tables = 'all tables' then
+ elsif tables_mode = 'all' then
if old.puballtables then
null;
else
-- 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.pubname));
+ execute format('drop publication %1$I; create publication %1$I for all tables;', old.pubname);
end if;
else
if old.puballtables 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.pubname));
- elsif exists(select from pg_publication_rel where prpubid = id) then
- execute(
- format(
- 'alter publication %I drop table %s',
- old.pubname,
- (select string_agg(prrelid::regclass::text, ', ') from pg_publication_rel where prpubid = id)
- )
- );
+ execute format('drop publication %1$I; create publication %1$I;', old.pubname);
+ else
+ for r in
+ select n.nspname as schema_name, c.relname as table_name
+ from pg_publication_rel pr
+ join pg_class c on c.oid = pr.prrelid
+ join pg_namespace n on n.oid = c.relnamespace
+ where pr.prpubid = id
+ loop
+ execute format('alter publication %I drop table %I.%I', old.pubname, r.schema_name, r.table_name);
+ end loop;
end if;
-- At this point the publication must have no tables.
- if new_tables != '' then
- execute(format('alter publication %I add table %s', old.pubname, new_tables));
- end if;
+ for i in 1 .. coalesce(cardinality(new_table_names), 0) loop
+ if new_table_schemas[i] is null then
+ execute format('alter publication %I add table %I', old.pubname, new_table_names[i]);
+ else
+ execute format('alter publication %I add table %I.%I', old.pubname, new_table_schemas[i], new_table_names[i]);
+ end if;
+ end loop;
end if;
- execute(
- format(
- 'alter publication %I set (publish = %L);',
- old.pubname,
- concat_ws(
- ', ',
- case when coalesce(new_publish_insert, old.pubinsert) then 'insert' end,
- case when coalesce(new_publish_update, old.pubupdate) then 'update' end,
- case when coalesce(new_publish_delete, old.pubdelete) then 'delete' end,
- case when coalesce(new_publish_truncate, old.pubtruncate) then 'truncate' end
- )
+ execute format(
+ 'alter publication %I set (publish = %L);',
+ old.pubname,
+ concat_ws(
+ ', ',
+ case when coalesce(new_publish_insert, old.pubinsert) then 'insert' end,
+ case when coalesce(new_publish_update, old.pubupdate) then 'update' end,
+ case when coalesce(new_publish_delete, old.pubdelete) then 'delete' end,
+ case when coalesce(new_publish_truncate, old.pubtruncate) then 'truncate' end
)
);
- execute(format('alter publication %I owner to %I;', old.pubname, coalesce(new_owner, old.pubowner::regrole::name)));
+ execute format('alter publication %I owner to %I;', old.pubname, coalesce(new_owner, old.pubowner::regrole::name));
-- 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.pubname then
- execute(format('alter publication %I rename to %I;', old.pubname, coalesce(new_name, old.pubname)));
+ execute format('alter publication %I rename to %I;', old.pubname, coalesce(new_name, old.pubname));
end if;
-- We need to retrieve the publication later, so we need a way to uniquely identify which publication this is.
diff --git a/packages/pg-meta/src/pg-meta-roles.ts b/packages/pg-meta/src/pg-meta-roles.ts
index ab2bf21ecde..303bc0c3d43 100644
--- a/packages/pg-meta/src/pg-meta-roles.ts
+++ b/packages/pg-meta/src/pg-meta-roles.ts
@@ -188,7 +188,7 @@ begin
raise exception 'Cannot find role with id %', id;
end if;
- execute(format('alter role %I
+ execute format('alter role %I
${isSuperuser === undefined ? safeSql`` : isSuperuser ? safeSql`superuser` : safeSql`nosuperuser`}
${canCreateDb === undefined ? safeSql`` : canCreateDb ? safeSql`createdb` : safeSql`nocreatedb`}
${canCreateRole === undefined ? safeSql`` : canCreateRole ? safeSql`createrole` : safeSql`nocreaterole`}
@@ -199,7 +199,7 @@ begin
${connectionLimit === undefined ? safeSql`` : safeSql`connection limit ${literal(connectionLimit)}`}
${password === undefined ? safeSql`` : safeSql`password ${literal(password)}`}
${validUntil === undefined ? safeSql`` : safeSql`valid until %L`}
- ', old.name${validUntil === undefined ? safeSql`` : safeSql`, ${literal(validUntil)}`}));
+ ', old.name${validUntil === undefined ? safeSql`` : safeSql`, ${literal(validUntil)}`});
${
newName === undefined
@@ -207,7 +207,7 @@ begin
: safeSql`
-- Using the same name in the rename clause gives an error, so only do it if the new name is different.
if ${literal(newName)} != old.name then
- execute(format('alter role %I rename to %I;', old.name, ${literal(newName)}));
+ execute format('alter role %I rename to %I;', old.name, ${literal(newName)});
end if;
`
}
@@ -235,7 +235,7 @@ begin
raise exception 'Cannot find role with id %', id;
end if;
- execute(format('drop role ${ifExists ? safeSql`if exists` : safeSql``} %I;', old.name));
+ execute format('drop role ${ifExists ? safeSql`if exists` : safeSql``} %I;', old.name);
end
$$;
`
diff --git a/packages/pg-meta/src/pg-meta-schemas.ts b/packages/pg-meta/src/pg-meta-schemas.ts
index 0005f8cf706..73ca0fd3f25 100644
--- a/packages/pg-meta/src/pg-meta-schemas.ts
+++ b/packages/pg-meta/src/pg-meta-schemas.ts
@@ -108,12 +108,12 @@ begin
end if;
if new_owner is not null then
- execute(format('alter schema %I owner to %I;', old.nspname, new_owner));
+ execute format('alter schema %I owner to %I;', old.nspname, 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.nspname then
- execute(format('alter schema %I rename to %I;', old.nspname, new_name));
+ execute format('alter schema %I rename to %I;', old.nspname, new_name);
end if;
end
$$;
@@ -148,7 +148,11 @@ begin
raise exception 'Cannot find schema with id %', id;
end if;
- execute(format('drop schema %I %s;', old.nspname, case when cascade then 'cascade' else 'restrict' end));
+ if cascade then
+ execute format('drop schema %I cascade;', old.nspname);
+ else
+ execute format('drop schema %I restrict;', old.nspname);
+ end if;
end
$$;
`
diff --git a/packages/pg-meta/src/pg-meta-table-privileges.ts b/packages/pg-meta/src/pg-meta-table-privileges.ts
index 28a8d0d2cd5..aaea39c3531 100644
--- a/packages/pg-meta/src/pg-meta-table-privileges.ts
+++ b/packages/pg-meta/src/pg-meta-table-privileges.ts
@@ -186,6 +186,25 @@ type TablePrivilegesGrant = {
| 'MAINTAIN'
isGrantable?: boolean
}
+/**
+ * The `%I.%I` arguments of a `format()` call that name a relation: the schema
+ * and name of the relation with the given oid.
+ *
+ * The statements below deliberately avoid `format('… %s …', <oid>::regclass)`:
+ * `%s` substitutes raw text, so a PL/pgSQL body using it can't be proven to
+ * build a fixed statement. Servers that statically check `DO` blocks (such as
+ * Multigres) reject those. A format string made only of `%I`/`%L` conversions
+ * can be checked, and builds the same statement.
+ */
+function relationIdentArgs(relationId: number): SafeSqlFragment {
+ const id = literal(relationId)
+ return safeSql`(select n.nspname from pg_class c join pg_namespace n on n.oid = c.relnamespace where c.oid = ${id}), (select relname from pg_class where oid = ${id})`
+}
+
+function granteeSql(grantee: string): SafeSqlFragment {
+ return grantee.toLowerCase() === 'public' ? safeSql`public` : ident(grantee)
+}
+
function grant(grants: TablePrivilegesGrant[]): { sql: SafeSqlFragment } {
const sql = safeSql`
do $$
@@ -193,9 +212,11 @@ begin
${joinSqlFragments(
grants.map(
({ privilegeType, relationId, grantee, isGrantable }) =>
- safeSql`execute format('grant ${keyword(privilegeType)} on table %s to ${
- grantee.toLowerCase() === 'public' ? safeSql`public` : ident(grantee)
- } ${isGrantable ? safeSql`with grant option` : safeSql``}', ${literal(relationId)}::regclass);`
+ safeSql`execute format(${literal(
+ `grant ${keyword(privilegeType)} on table %I.%I to ${granteeSql(grantee)}${
+ isGrantable ? ' with grant option' : ''
+ }`
+ )}, ${relationIdentArgs(relationId)});`
),
'\n'
)}
@@ -225,9 +246,9 @@ begin
${joinSqlFragments(
revokes.map(
({ privilegeType, relationId, grantee }) =>
- safeSql`execute format('revoke ${keyword(privilegeType)} on table %s from ${
- grantee.toLowerCase() === 'public' ? safeSql`public` : ident(grantee)
- }', ${literal(relationId)}::regclass);`
+ safeSql`execute format(${literal(
+ `revoke ${keyword(privilegeType)} on table %I.%I from ${granteeSql(grantee)}`
+ )}, ${relationIdentArgs(relationId)});`
),
'\n'
)}
diff --git a/packages/pg-meta/test/column-privileges.test.ts b/packages/pg-meta/test/column-privileges.test.ts
index bf8ca0db941..a089a62bad0 100644
--- a/packages/pg-meta/test/column-privileges.test.ts
+++ b/packages/pg-meta/test/column-privileges.test.ts
@@ -432,3 +432,107 @@ withTestDatabase('scoped list matches the legacy path row-for-row', async ({ exe
normalize(legacyByIds.zod.parse(await executeQuery(legacyByIds.sql)))
)
})
+
+const columnGrants = async (
+ executeQuery: <T = any>(query: string) => Promise<T>,
+ schema: string,
+ table: string,
+ grantees: string[]
+) => {
+ const rows = await executeQuery<
+ { grantee: string; column_name: string; privilege_type: string; is_grantable: string }[]
+ >(`
+ select grantee, column_name, privilege_type, is_grantable
+ from information_schema.column_privileges
+ where table_schema = '${schema.replaceAll("'", "''")}'
+ and table_name = '${table.replaceAll("'", "''")}'
+ and grantee in (${grantees.map((g) => `'${g.replaceAll("'", "''")}'`).join(', ')})
+ order by grantee, column_name, privilege_type
+ `)
+ return rows.map((r) => `${r.grantee}:${r.column_name}:${r.privilege_type}:${r.is_grantable}`)
+}
+
+withTestDatabase(
+ 'grant & revoke column privileges in a schema, table and column that need quoting',
+ async ({ executeQuery }) => {
+ const role = `cp_quoted_${Date.now()}`
+ await executeQuery(
+ `create role ${role}; create schema "My Schema"; create table "My Schema"."Weird Table"("Col A" int, b int);`
+ )
+ try {
+ const { sql: listSql, zod: listZod } = await pgMeta.columnPrivileges.list()
+ const rows = listZod.parse(await executeQuery(listSql))
+ const columnIdFor = (columnName: string) =>
+ rows.find(
+ ({ relation_schema, relation_name, column_name }) =>
+ relation_schema === 'My Schema' &&
+ relation_name === 'Weird Table' &&
+ column_name === columnName
+ )!.column_id
+
+ await executeQuery(
+ pgMeta.columnPrivileges.grant([
+ { columnId: columnIdFor('Col A'), grantee: role, privilegeType: 'SELECT' },
+ {
+ columnId: columnIdFor('Col A'),
+ grantee: role,
+ privilegeType: 'UPDATE',
+ isGrantable: true,
+ },
+ { columnId: columnIdFor('b'), grantee: 'PUBLIC', privilegeType: 'INSERT' },
+ ]).sql
+ )
+ expect(
+ await columnGrants(executeQuery, 'My Schema', 'Weird Table', [role, 'PUBLIC'])
+ ).toEqual([`PUBLIC:b:INSERT:NO`, `${role}:Col A:SELECT:NO`, `${role}:Col A:UPDATE:YES`])
+
+ await executeQuery(
+ pgMeta.columnPrivileges.revoke([
+ { columnId: columnIdFor('Col A'), grantee: role, privilegeType: 'UPDATE' },
+ { columnId: columnIdFor('b'), grantee: 'public', privilegeType: 'INSERT' },
+ ]).sql
+ )
+ expect(
+ await columnGrants(executeQuery, 'My Schema', 'Weird Table', [role, 'PUBLIC'])
+ ).toEqual([`${role}:Col A:SELECT:NO`])
+ } finally {
+ await executeQuery(`drop owned by ${role}; drop role ${role};`)
+ }
+ }
+)
+
+withTestDatabase(
+ 'grant & revoke column privileges for a role whose name has quotes',
+ async ({ executeQuery }) => {
+ const role = `it's a "role" ${Date.now()}`
+ const quotedRole = `"${role.replaceAll('"', '""')}"`
+ await executeQuery(`create role ${quotedRole};`)
+ try {
+ const { sql: listSql, zod: listZod } = await pgMeta.columnPrivileges.list()
+ const { column_id } = listZod
+ .parse(await executeQuery(listSql))
+ .find(
+ ({ relation_schema, relation_name, column_name }) =>
+ relation_schema === 'public' && relation_name === 'todos' && column_name === 'id'
+ )!
+
+ await executeQuery(
+ pgMeta.columnPrivileges.grant([
+ { columnId: column_id, grantee: role, privilegeType: 'SELECT', isGrantable: true },
+ ]).sql
+ )
+ expect(await columnGrants(executeQuery, 'public', 'todos', [role])).toEqual([
+ `${role}:id:SELECT:YES`,
+ ])
+
+ await executeQuery(
+ pgMeta.columnPrivileges.revoke([
+ { columnId: column_id, grantee: role, privilegeType: 'SELECT' },
+ ]).sql
+ )
+ expect(await columnGrants(executeQuery, 'public', 'todos', [role])).toEqual([])
+ } finally {
+ await executeQuery(`drop owned by ${quotedRole}; drop role ${quotedRole};`)
+ }
+ }
+)
diff --git a/packages/pg-meta/test/multigres-safe-sql.test.ts b/packages/pg-meta/test/multigres-safe-sql.test.ts
new file mode 100644
index 00000000000..e737bea3b1c
--- /dev/null
+++ b/packages/pg-meta/test/multigres-safe-sql.test.ts
@@ -0,0 +1,89 @@
+import { expect, test } from 'vitest'
+
+import pgMeta from '../src/index'
+
+// Servers that statically check DO blocks (such as Multigres) only accept a
+// dynamic EXECUTE whose statement they can prove is fixed. Without that proof
+// they reject the whole block with "EXECUTE of a runtime-built statement …".
+// Two shapes break the proof, and the generated SQL must avoid both:
+// - parentheses around the payload: `execute(format(…))`
+// - a `%s` conversion in a format string, which substitutes raw text
+// `%I`, `%L` and `%%` are fine.
+const expectAnalyzableExecutes = (sql: string) => {
+ expect(sql).not.toMatch(/\bexecute\s*\(/i)
+
+ const formatStrings = [...sql.matchAll(/\bexecute\s+format\(\s*(E?'(?:[^']|'')*')/gi)].map(
+ (m) => m[1]
+ )
+ for (const formatString of formatStrings) {
+ // Strip the allowed conversions; any `%` left over is a `%s` or another unchecked conversion.
+ expect(formatString.replace(/%(?:\d+\$)?[IL]|%%/g, ''), formatString).not.toContain('%')
+ }
+ return formatStrings.length
+}
+
+test('table privilege grant and revoke SQL has analyzable EXECUTEs', () => {
+ const grant = pgMeta.tablePrivileges.grant([
+ { relationId: 1, grantee: 'anon', privilegeType: 'SELECT' },
+ { relationId: 1, grantee: 'authenticated', privilegeType: 'ALL', isGrantable: true },
+ { relationId: 2, grantee: 'public', privilegeType: 'INSERT' },
+ { relationId: 2, grantee: "it's a role", privilegeType: 'UPDATE' },
+ ]).sql
+ const revoke = pgMeta.tablePrivileges.revoke([
+ { relationId: 1, grantee: 'anon', privilegeType: 'DELETE' },
+ { relationId: 2, grantee: 'public', privilegeType: 'SELECT' },
+ ]).sql
+
+ expect(expectAnalyzableExecutes(grant)).toBe(4)
+ expect(expectAnalyzableExecutes(revoke)).toBe(2)
+ // A quote in the grantee can't break out of the format string.
+ expect(grant).toContain(`"it''s a role"`)
+})
+
+test('publication update SQL has analyzable EXECUTEs', () => {
+ const variants = [
+ {},
+ { tables: null },
+ { tables: [] },
+ { tables: ['public.t', 'bare', 'a.b.c'] },
+ { tables: ['My Schema.Odd Table', `it's."q"`] },
+ { name: 'renamed', owner: 'postgres', publish_insert: true },
+ ]
+ for (const params of variants) {
+ const { sql } = pgMeta.publications.update(1, params)
+ expect(expectAnalyzableExecutes(sql), JSON.stringify(params)).toBeGreaterThan(0)
+ }
+})
+
+test('column privilege grant and revoke SQL has analyzable EXECUTEs', () => {
+ const grant = pgMeta.columnPrivileges.grant([
+ { columnId: '1.1', grantee: 'anon', privilegeType: 'SELECT' },
+ { columnId: '1.2', grantee: 'public', privilegeType: 'UPDATE', isGrantable: true },
+ ]).sql
+ const revoke = pgMeta.columnPrivileges.revoke([
+ { columnId: '1.1', grantee: "it's a role", privilegeType: 'SELECT' },
+ ]).sql
+
+ expect(expectAnalyzableExecutes(grant)).toBe(2)
+ expect(expectAnalyzableExecutes(revoke)).toBe(1)
+ expect(revoke).toContain(`"it''s a role"`)
+})
+
+test('schema update and remove SQL has analyzable EXECUTEs', () => {
+ expect(
+ expectAnalyzableExecutes(pgMeta.schemas.update({ id: 1 }, { name: 'a', owner: 'b' }).sql)
+ ).toBe(2)
+ // Both branches of the cascade choice are present, each with a fixed statement.
+ expect(expectAnalyzableExecutes(pgMeta.schemas.remove({ id: 1 }, { cascade: true }).sql)).toBe(2)
+ expect(expectAnalyzableExecutes(pgMeta.schemas.remove({ name: 's' }).sql)).toBe(2)
+})
+
+test('role update and remove SQL has analyzable EXECUTEs', () => {
+ const update = pgMeta.roles.update(
+ { id: 1 },
+ { name: 'renamed', canLogin: true, connectionLimit: 5, validUntil: '2030-01-01' }
+ ).sql
+ expect(expectAnalyzableExecutes(update)).toBe(2)
+ expect(expectAnalyzableExecutes(pgMeta.roles.update({ id: 1 }, { canLogin: false }).sql)).toBe(1)
+ expect(expectAnalyzableExecutes(pgMeta.roles.remove({ id: 1 }, { ifExists: true }).sql)).toBe(1)
+})
diff --git a/packages/pg-meta/test/publications.test.ts b/packages/pg-meta/test/publications.test.ts
index 38a827f7dd1..2b87b81d1ff 100644
--- a/packages/pg-meta/test/publications.test.ts
+++ b/packages/pg-meta/test/publications.test.ts
@@ -317,3 +317,163 @@ withTestDatabase('update all tables -> no tables', async ({ executeQuery }) => {
const { sql: removeSql } = pgMeta.publications.remove(updatedRes!)
await executeQuery(removeSql)
})
+
+const publicationTableNames = async (
+ executeQuery: <T = any>(query: string) => Promise<T>,
+ name: string
+) => {
+ const { sql, zod } = pgMeta.publications.retrieve({ name })
+ const res = zod.parse((await executeQuery(sql))[0])!
+ return (res.tables ?? []).map((t) => `${t.schema}.${t.name}`).sort()
+}
+
+withTestDatabase('update replaces the published tables', async ({ executeQuery }) => {
+ await executeQuery(pgMeta.publications.create({ name: 'pub', tables: ['users', 'todos'] }).sql)
+ const { sql: retrieveSql, zod: retrieveZod } = pgMeta.publications.retrieve({ name: 'pub' })
+ const { id } = retrieveZod.parse((await executeQuery(retrieveSql))[0])!
+ expect(await publicationTableNames(executeQuery, 'pub')).toEqual(['public.todos', 'public.users'])
+
+ // A different list: removes users, keeps todos, adds memes.
+ await executeQuery(
+ pgMeta.publications.update(id, { tables: ['public.todos', 'public.memes'] }).sql
+ )
+ expect(await publicationTableNames(executeQuery, 'pub')).toEqual(['public.memes', 'public.todos'])
+
+ // Bare table names resolve through the search path.
+ await executeQuery(pgMeta.publications.update(id, { tables: ['users'] }).sql)
+ expect(await publicationTableNames(executeQuery, 'pub')).toEqual(['public.users'])
+
+ // An empty list clears the publication.
+ await executeQuery(pgMeta.publications.update(id, { tables: [] }).sql)
+ expect(await publicationTableNames(executeQuery, 'pub')).toEqual([])
+})
+
+withTestDatabase(
+ 'update without tables leaves the published tables alone',
+ async ({ executeQuery }) => {
+ await executeQuery(pgMeta.publications.create({ name: 'pub', tables: ['users', 'todos'] }).sql)
+ const { sql: retrieveSql, zod: retrieveZod } = pgMeta.publications.retrieve({ name: 'pub' })
+ const { id } = retrieveZod.parse((await executeQuery(retrieveSql))[0])!
+
+ await executeQuery(
+ pgMeta.publications.update(id, { name: 'pub_renamed', publish_insert: true }).sql
+ )
+ expect(await publicationTableNames(executeQuery, 'pub_renamed')).toEqual([
+ 'public.todos',
+ 'public.users',
+ ])
+ }
+)
+
+withTestDatabase('update from a table list to all tables and back', async ({ executeQuery }) => {
+ await executeQuery(pgMeta.publications.create({ name: 'pub', tables: ['users'] }).sql)
+ const { sql: retrieveSql, zod: retrieveZod } = pgMeta.publications.retrieve({ name: 'pub' })
+ const { id } = retrieveZod.parse((await executeQuery(retrieveSql))[0])!
+
+ await executeQuery(pgMeta.publications.update(id, { tables: null }).sql)
+ const allTables = retrieveZod.parse((await executeQuery(retrieveSql))[0])!
+ expect(allTables.tables).toBeNull()
+
+ // The publication was recreated, so its id changed.
+ await executeQuery(pgMeta.publications.update(allTables.id, { tables: ['todos'] }).sql)
+ expect(await publicationTableNames(executeQuery, 'pub')).toEqual(['public.todos'])
+})
+
+const createPublication = async (
+ executeQuery: <T = any>(query: string) => Promise<T>,
+ params: Parameters<typeof pgMeta.publications.create>[0]
+) => {
+ await executeQuery(pgMeta.publications.create(params).sql)
+ const { sql, zod } = pgMeta.publications.retrieve({ name: params.name })
+ return zod.parse((await executeQuery(sql))[0])!
+}
+
+withTestDatabase(
+ 'update with tables in other schemas, with names that need quoting',
+ async ({ executeQuery }) => {
+ await executeQuery(`
+ create schema "My Schema";
+ create table "My Schema"."Odd Table"();
+ create schema a;
+ create table a."b.c"();
+ `)
+ const { id } = await createPublication(executeQuery, { name: 'pub', tables: ['users'] })
+
+ // `a.b.c` splits on the first dot only: schema `a`, table `b.c`.
+ await executeQuery(
+ pgMeta.publications.update(id, { tables: ['My Schema.Odd Table', 'a.b.c', 'public.users'] })
+ .sql
+ )
+ expect(await publicationTableNames(executeQuery, 'pub')).toEqual([
+ 'My Schema.Odd Table',
+ 'a.b.c',
+ 'public.users',
+ ])
+
+ // Replacing the list drops the tables in the other schemas again.
+ await executeQuery(pgMeta.publications.update(id, { tables: ['public.todos'] }).sql)
+ expect(await publicationTableNames(executeQuery, 'pub')).toEqual(['public.todos'])
+ }
+)
+
+withTestDatabase(
+ 'update the published tables together with the name and events',
+ async ({ executeQuery }) => {
+ const { id } = await createPublication(executeQuery, {
+ name: 'pub',
+ publish_insert: true,
+ publish_update: true,
+ tables: ['users'],
+ })
+
+ await executeQuery(
+ pgMeta.publications.update(id, {
+ name: 'pub_renamed',
+ owner: 'postgres',
+ publish_insert: false,
+ publish_update: false,
+ tables: ['public.todos', 'public.memes'],
+ }).sql
+ )
+
+ const { sql, zod } = pgMeta.publications.retrieve({ name: 'pub_renamed' })
+ const res = zod.parse((await executeQuery(sql))[0])!
+ expect(res.publish_insert).toBe(false)
+ expect(res.publish_update).toBe(false)
+ expect(res.tables?.map((t) => `${t.schema}.${t.name}`).sort()).toEqual([
+ 'public.memes',
+ 'public.todos',
+ ])
+ }
+)
+
+withTestDatabase('update from all tables to an empty list', async ({ executeQuery }) => {
+ const { id } = await createPublication(executeQuery, { name: 'pub', tables: null })
+
+ // Going from `all tables` recreates the publication, then the add loop runs zero times.
+ await executeQuery(pgMeta.publications.update(id, { tables: [] }).sql)
+
+ const { sql, zod } = pgMeta.publications.retrieve({ name: 'pub' })
+ const res = zod.parse((await executeQuery(sql))[0])!
+ expect(res.tables).toEqual([])
+})
+
+withTestDatabase(
+ 'update with a table that does not exist fails and leaves the publication untouched',
+ async ({ executeQuery }) => {
+ const { id } = await createPublication(executeQuery, {
+ name: 'pub',
+ tables: ['users', 'todos'],
+ })
+
+ await expect(
+ executeQuery(pgMeta.publications.update(id, { tables: ['public.todos', 'nope'] }).sql)
+ ).rejects.toThrow(/relation "nope" does not exist/)
+
+ // The whole `do` block rolls back, including the earlier drop of `users`.
+ expect(await publicationTableNames(executeQuery, 'pub')).toEqual([
+ 'public.todos',
+ 'public.users',
+ ])
+ }
+)
diff --git a/packages/pg-meta/test/roles.test.ts b/packages/pg-meta/test/roles.test.ts
index e47d00819d9..f279d99a177 100644
--- a/packages/pg-meta/test/roles.test.ts
+++ b/packages/pg-meta/test/roles.test.ts
@@ -237,3 +237,30 @@ withTestDatabase('retrieve, create, update, delete roles', async ({ executeQuery
const finalRoles = finalListZod.parse(await executeQuery(finalListSql))
expect(finalRoles.find((role) => role.name === 'config_role')).toBeUndefined()
})
+
+withTestDatabase('update and remove a role whose name needs quoting', async ({ executeQuery }) => {
+ const { sql: createSql } = pgMeta.roles.create({ name: 'quoting_r1' })
+ await executeQuery(createSql)
+ const { sql: listSql, zod: listZod } = pgMeta.roles.list()
+ const findRole = async (name: string) =>
+ listZod.parse(await executeQuery(listSql)).find((role) => role.name === name)
+ const { id } = (await findRole('quoting_r1'))!
+
+ // The rename and `valid until %L` are separate statements in one `do` block.
+ await executeQuery(
+ pgMeta.roles.update(
+ { id },
+ { name: `it's a "role"`, canLogin: true, validUntil: '2030-01-01T00:00:00.000Z' }
+ ).sql
+ )
+
+ const renamed = (await findRole(`it's a "role"`))!
+ expect(await findRole('quoting_r1')).toBeUndefined()
+ expect(renamed.id).toBe(id)
+ expect(renamed.canLogin).toBe(true)
+ // The server's time zone decides how the value is printed, so compare instants.
+ expect(new Date(renamed.validUntil!).toISOString()).toBe('2030-01-01T00:00:00.000Z')
+
+ await executeQuery(pgMeta.roles.remove({ id }).sql)
+ expect(await findRole(`it's a "role"`)).toBeUndefined()
+})
diff --git a/packages/pg-meta/test/schemas.test.ts b/packages/pg-meta/test/schemas.test.ts
index 9311f85e2a1..57c88701277 100644
--- a/packages/pg-meta/test/schemas.test.ts
+++ b/packages/pg-meta/test/schemas.test.ts
@@ -135,3 +135,58 @@ withTestDatabase('retrieve, create, update, delete', async ({ executeQuery }) =>
const finalRes = await executeQuery(finalRetrieveSql)
expect(finalRes).toMatchInlineSnapshot(`[]`)
})
+
+withTestDatabase(
+ 'remove with cascade drops the schema and its contents',
+ async ({ executeQuery }) => {
+ await executeQuery(`create schema s; create table s.t(); create view s.v as select 1;`)
+ const { sql: retrieveSql, zod } = pgMeta.schemas.retrieve({ name: 's' })
+ const { id } = zod.parse((await executeQuery(retrieveSql))[0])!
+
+ await executeQuery(pgMeta.schemas.remove({ id }, { cascade: true }).sql)
+
+ expect(await executeQuery(retrieveSql)).toEqual([])
+ expect(
+ await executeQuery(
+ `select 1 from pg_class c join pg_namespace n on n.oid = c.relnamespace where n.nspname = 's'`
+ )
+ ).toEqual([])
+ }
+)
+
+withTestDatabase('remove without cascade only drops an empty schema', async ({ executeQuery }) => {
+ await executeQuery(`create schema full_s; create table full_s.t(); create schema empty_s;`)
+ const retrieve = (name: string) => pgMeta.schemas.retrieve({ name })
+ const fullSchema = retrieve('full_s')
+ const emptySchema = retrieve('empty_s')
+ const { id: fullId } = fullSchema.zod.parse((await executeQuery(fullSchema.sql))[0])!
+ const { id: emptyId } = emptySchema.zod.parse((await executeQuery(emptySchema.sql))[0])!
+
+ // Both the default and an explicit `cascade: false` restrict.
+ await expect(executeQuery(pgMeta.schemas.remove({ id: fullId }).sql)).rejects.toThrow(
+ /cannot drop schema full_s because other objects depend on it/
+ )
+ await expect(
+ executeQuery(pgMeta.schemas.remove({ id: fullId }, { cascade: false }).sql)
+ ).rejects.toThrow(/cannot drop schema full_s/)
+ expect(await executeQuery(fullSchema.sql)).toHaveLength(1)
+
+ await executeQuery(pgMeta.schemas.remove({ id: emptyId }).sql)
+ expect(await executeQuery(emptySchema.sql)).toEqual([])
+})
+
+withTestDatabase(
+ 'update and remove a schema whose name needs quoting',
+ async ({ executeQuery }) => {
+ await executeQuery(`create schema "My Schema";`)
+ const { sql: retrieveSql, zod } = pgMeta.schemas.retrieve({ name: 'My Schema' })
+ const { id } = zod.parse((await executeQuery(retrieveSql))[0])!
+
+ await executeQuery(pgMeta.schemas.update({ id }, { name: `it's "renamed"` }).sql)
+ const renamed = pgMeta.schemas.retrieve({ id })
+ expect(renamed.zod.parse((await executeQuery(renamed.sql))[0])!.name).toBe(`it's "renamed"`)
+
+ await executeQuery(pgMeta.schemas.remove({ id }).sql)
+ expect(await executeQuery(renamed.sql)).toEqual([])
+ }
+)
diff --git a/packages/pg-meta/test/table-privileges.test.ts b/packages/pg-meta/test/table-privileges.test.ts
index 246448dad52..884dfe7ea13 100644
--- a/packages/pg-meta/test/table-privileges.test.ts
+++ b/packages/pg-meta/test/table-privileges.test.ts
@@ -453,3 +453,111 @@ withTestDatabase(
)
}
)
+
+// Reads grants through `information_schema` instead of snapshotting the whole privilege list, so
+// the assertions don't depend on which privileges a Postgres version adds (e.g. `MAINTAIN`).
+const tableGrants = async (
+ executeQuery: <T = any>(query: string) => Promise<T>,
+ schema: string,
+ table: string,
+ grantees: string[]
+) => {
+ const rows = await executeQuery<
+ { grantee: string; privilege_type: string; is_grantable: string }[]
+ >(`
+ select grantee, privilege_type, is_grantable
+ from information_schema.table_privileges
+ where table_schema = '${schema.replaceAll("'", "''")}'
+ and table_name = '${table.replaceAll("'", "''")}'
+ and grantee in (${grantees.map((g) => `'${g.replaceAll("'", "''")}'`).join(', ')})
+ order by grantee, privilege_type
+ `)
+ return rows.map((r) => `${r.grantee}:${r.privilege_type}:${r.is_grantable}`)
+}
+
+withTestDatabase(
+ 'grant & revoke table privileges in a schema and table that need quoting',
+ async ({ executeQuery }) => {
+ const role = `tp_quoted_${Date.now()}`
+ await executeQuery(
+ `create role ${role}; create schema "My Schema"; create table "My Schema"."Weird Table"();`
+ )
+ try {
+ const { sql: listSql, zod: listZod } = await pgMeta.tablePrivileges.list()
+ const { relation_id } = listZod
+ .parse(await executeQuery(listSql))
+ .find(({ schema, name }) => schema === 'My Schema' && name === 'Weird Table')!
+
+ // `isGrantable`, a role grantee and the `public` pseudo-role (any casing) in one call.
+ await executeQuery(
+ pgMeta.tablePrivileges.grant([
+ { relationId: relation_id, grantee: role, privilegeType: 'SELECT' },
+ { relationId: relation_id, grantee: role, privilegeType: 'INSERT', isGrantable: true },
+ { relationId: relation_id, grantee: 'PUBLIC', privilegeType: 'UPDATE' },
+ ]).sql
+ )
+ expect(await tableGrants(executeQuery, 'My Schema', 'Weird Table', [role, 'PUBLIC'])).toEqual(
+ [`PUBLIC:UPDATE:NO`, `${role}:INSERT:YES`, `${role}:SELECT:NO`]
+ )
+
+ await executeQuery(
+ pgMeta.tablePrivileges.revoke([
+ { relationId: relation_id, grantee: role, privilegeType: 'INSERT' },
+ { relationId: relation_id, grantee: 'public', privilegeType: 'UPDATE' },
+ ]).sql
+ )
+ expect(await tableGrants(executeQuery, 'My Schema', 'Weird Table', [role, 'PUBLIC'])).toEqual(
+ [`${role}:SELECT:NO`]
+ )
+ } finally {
+ await executeQuery(`drop owned by ${role}; drop role ${role};`)
+ }
+ }
+)
+
+withTestDatabase(
+ 'grant & revoke table privileges for a role whose name has quotes',
+ async ({ executeQuery }) => {
+ const role = `it's a "role" ${Date.now()}`
+ const quotedRole = `"${role.replaceAll('"', '""')}"`
+ await executeQuery(`create role ${quotedRole};`)
+ try {
+ const { sql: listSql, zod: listZod } = await pgMeta.tablePrivileges.list()
+ const { relation_id } = listZod
+ .parse(await executeQuery(listSql))
+ .find(({ schema, name }) => schema === 'public' && name === 'todos')!
+
+ await executeQuery(
+ pgMeta.tablePrivileges.grant([
+ { relationId: relation_id, grantee: role, privilegeType: 'SELECT', isGrantable: true },
+ ]).sql
+ )
+ expect(await tableGrants(executeQuery, 'public', 'todos', [role])).toEqual([
+ `${role}:SELECT:YES`,
+ ])
+
+ await executeQuery(
+ pgMeta.tablePrivileges.revoke([
+ { relationId: relation_id, grantee: role, privilegeType: 'SELECT' },
+ ]).sql
+ )
+ expect(await tableGrants(executeQuery, 'public', 'todos', [role])).toEqual([])
+ } finally {
+ await executeQuery(`drop owned by ${quotedRole}; drop role ${quotedRole};`)
+ }
+ }
+)
+
+withTestDatabase(
+ 'grant table privileges for a table that does not exist',
+ async ({ executeQuery }) => {
+ // A dropped table leaves the subselects with no row, which `%I` rejects.
+ await expect(
+ executeQuery(
+ pgMeta.tablePrivileges.grant([
+ { relationId: 2147483000, grantee: 'postgres', privilegeType: 'SELECT' },
+ ]).sql
+ )
+ ).rejects.toThrow()
+ }
+)