Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -892,14 +892,26 @@ private String catalogName() {

// -- Catalog result sets (C23.16). --

/**
* The {@code pg_description} text of an object, as obj_description/col_description return it.
* Those are SQL-language functions before PostgreSQL 14, parsed with the caller's search_path,
* and their bodies compare oid = int4 and oid = regclass, so a search_path schema could supply
* either operator. This reads the catalog directly with pg_catalog's operators.
*/
private static String description(String objectOid, String catalog, String subId) {
return "(SELECT d.description FROM pg_catalog.pg_description d WHERE d.objoid OPERATOR(pg_catalog.=) "
+ objectOid + " AND d.classoid OPERATOR(pg_catalog.=) 'pg_catalog." + catalog
+ "'::pg_catalog.regclass AND d.objsubid OPERATOR(pg_catalog.=) " + subId + ")";
}

@Override
public ResultSet getTables(String catalog, String schemaPattern, String tableNamePattern, String[] types)
throws SQLException {
// Operators with no exact pg_catalog match for their argument types (name LIKE varchar,
// oid = int4, ...) are written OPERATOR(pg_catalog.op): otherwise an exact match from any
// search_path schema would win.
String sql = "SELECT n.nspname AS schem, c.relname AS name, c.relkind AS kind, "
+ "pg_catalog.obj_description(c.oid, 'pg_class') AS remarks "
+ description("c.oid", "pg_class", "0") + " AS remarks "
+ "FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace "
+ "WHERE c.relkind IN ('r','p','v','m','f','i','I','S','c') AND n.nspname OPERATOR(pg_catalog.~~) ? AND c.relname OPERATOR(pg_catalog.~~) ? "
+ "ORDER BY c.relkind, n.nspname, c.relname";
Expand Down Expand Up @@ -981,7 +993,7 @@ public ResultSet getColumns(String catalog, String schemaPattern, String tableNa
+ "t.typnotnull AS domnotnull, "
+ "t.typname AS typname, "
+ "pg_catalog.pg_get_expr(ad.adbin, ad.adrelid) AS def, "
+ "pg_catalog.col_description(c.oid, a.attnum) AS remarks, "
+ description("c.oid", "pg_class", "a.attnum") + " AS remarks, "
+ identityExpr + " AS identity, " + generatedExpr + " AS generated "
+ "FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace "
+ "JOIN pg_catalog.pg_attribute a ON a.attrelid = c.oid "
Expand Down Expand Up @@ -1370,7 +1382,7 @@ public ResultSet getIndexInfo(String catalog, String schema, String table, boole
+ "ELSE a.attname END AS col, "
+ "CASE WHEN (ix.indoption[(" + INDKEY_ORD + " - 1)::int]::int & 1) = 1 THEN 'D' ELSE 'A' END AS dir, "
+ "pg_catalog.pg_get_expr(ix.indpred, ix.indrelid) AS filter, "
+ "pg_catalog.obj_description(ci.oid, 'pg_class') AS remarks "
+ description("ci.oid", "pg_class", "0") + " AS remarks "
+ "FROM " + EXPANDED_INDKEY
+ "JOIN pg_catalog.pg_class ct ON ct.oid = ix.indrelid "
+ "JOIN pg_catalog.pg_class ci ON ci.oid = ix.indexrelid "
Expand Down Expand Up @@ -1476,10 +1488,13 @@ public ResultSet getTypeInfo() throws SQLException {
@Override
public ResultSet getProcedures(String catalog, String schemaPattern, String procedureNamePattern)
throws SQLException {
// pg_proc.prokind is PG 11+, as are procedures: before it there is nothing to list.
String isProcedure = getDatabaseMajorVersion() >= 11 ? "p.prokind = 'p'" : "false";
String sql = "SELECT n.nspname AS schem, p.proname AS name, p.oid AS oid, "
+ "pg_catalog.obj_description(p.oid, 'pg_proc') AS remarks "
+ description("p.oid", "pg_proc", "0") + " AS remarks "
+ "FROM pg_catalog.pg_proc p JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace "
+ "WHERE p.prokind = 'p' AND n.nspname OPERATOR(pg_catalog.~~) ? AND p.proname OPERATOR(pg_catalog.~~) ? "
+ "WHERE " + isProcedure
+ " AND n.nspname OPERATOR(pg_catalog.~~) ? AND p.proname OPERATOR(pg_catalog.~~) ? "
// SPECIFIC_NAME is proname_oid; JDBC orders by it as text, so sort the same way.
+ "ORDER BY n.nspname, p.proname, p.proname OPERATOR(pg_catalog.||) '_' OPERATOR(pg_catalog.||) p.oid";
List<Object[]> rows = !catalogSelects(catalog)
Expand Down Expand Up @@ -1723,10 +1738,13 @@ private static String[] parseTextArrayLiteral(String text) {
@Override
public ResultSet getFunctions(String catalog, String schemaPattern, String functionNamePattern)
throws SQLException {
// Before PG 11 (no prokind) every pg_proc row is a function, aggregate or window function.
String isFunction = getDatabaseMajorVersion() >= 11 ? "p.prokind IN ('f','a','w')" : "true";
String sql = "SELECT n.nspname AS schem, p.proname AS name, p.oid AS oid, p.proretset AS retset, "
+ "pg_catalog.obj_description(p.oid, 'pg_proc') AS remarks "
+ description("p.oid", "pg_proc", "0") + " AS remarks "
+ "FROM pg_catalog.pg_proc p JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace "
+ "WHERE p.prokind IN ('f','a','w') AND n.nspname OPERATOR(pg_catalog.~~) ? AND p.proname OPERATOR(pg_catalog.~~) ? "
+ "WHERE " + isFunction
+ " AND n.nspname OPERATOR(pg_catalog.~~) ? AND p.proname OPERATOR(pg_catalog.~~) ? "
// SPECIFIC_NAME is proname_oid; JDBC orders by it as text, so sort the same way.
+ "ORDER BY n.nspname, p.proname, p.proname OPERATOR(pg_catalog.||) '_' OPERATOR(pg_catalog.||) p.oid";
List<Object[]> rows = !catalogSelects(catalog)
Expand Down Expand Up @@ -1866,24 +1884,45 @@ private Object[] functionColumnRow(
};
}

/**
* The JDBC privilege columns of the {@code aclexplode} row {@code x.g}. The privilege queries call
* aclexplode in a subquery's select list rather than through CROSS JOIN LATERAL, which PostgreSQL
* 9.1 and 9.2 lack.
*/
private static final String EXPLODED_ACL_COLUMNS = "pg_catalog.pg_get_userbyid((x.g).grantor) AS grantor, "
+ "CASE WHEN (x.g).grantee OPERATOR(pg_catalog.=) 0 THEN 'PUBLIC' "
+ "ELSE pg_catalog.pg_get_userbyid((x.g).grantee) END AS grantee, "
+ "(x.g).privilege_type AS priv, "
+ "CASE WHEN (x.g).is_grantable THEN 'YES' ELSE 'NO' END AS grantable ";

/**
* The ACL a relation with no relacl has: every table privilege for its owner. acldefault is 9.2+;
* on 9.1 the same owner entry is built as text.
*/
private String ownerDefaultAcl() throws SQLException {
int major = getDatabaseMajorVersion();
if (major > 9 || (major == 9 && getDatabaseMinorVersion() >= 2)) {
return "pg_catalog.acldefault('r'::\"char\", c.relowner)";
}
String owner = "pg_catalog.quote_ident(pg_catalog.pg_get_userbyid(c.relowner))";
return "ARRAY[(" + owner + " OPERATOR(pg_catalog.||) '=arwdDxt/' OPERATOR(pg_catalog.||) " + owner
+ ")::pg_catalog.aclitem]";
}

@Override
public ResultSet getColumnPrivileges(String catalog, String schema, String table, String columnNamePattern)
throws SQLException {
// A column's privileges are the column-grantable subset (SELECT/INSERT/UPDATE/REFERENCES) of its
// effective ACL: the column's own attacl when set, else the table's relacl, else the owner's default
// grants (acldefault). One row per (column, grantee, privilege); grantee 0 is PUBLIC.
String sql = "SELECT n.nspname AS schem, c.relname AS tbl, a.attname AS col, "
+ "pg_catalog.pg_get_userbyid(g.grantor) AS grantor, "
+ "CASE WHEN g.grantee OPERATOR(pg_catalog.=) 0 THEN 'PUBLIC' ELSE pg_catalog.pg_get_userbyid(g.grantee) END AS grantee, "
+ "g.privilege_type AS priv, "
+ "CASE WHEN g.is_grantable THEN 'YES' ELSE 'NO' END AS grantable "
String sql = "SELECT x.schem, x.tbl, x.col, " + EXPLODED_ACL_COLUMNS
+ "FROM (SELECT n.nspname AS schem, c.relname AS tbl, a.attname AS col, "
+ "pg_catalog.aclexplode(COALESCE(a.attacl, c.relacl, " + ownerDefaultAcl() + ")) AS g "
+ "FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace "
+ "JOIN pg_catalog.pg_attribute a ON a.attrelid = c.oid AND a.attnum > 0 AND NOT a.attisdropped "
+ "CROSS JOIN LATERAL "
+ "pg_catalog.aclexplode(COALESCE(a.attacl, c.relacl, pg_catalog.acldefault('r'::\"char\", c.relowner))) g "
+ "WHERE n.nspname OPERATOR(pg_catalog.~~) ? AND c.relname OPERATOR(pg_catalog.=) ? AND a.attname OPERATOR(pg_catalog.~~) ? "
+ "AND g.privilege_type IN ('SELECT','INSERT','UPDATE','REFERENCES') "
+ "ORDER BY a.attname, g.privilege_type";
+ "WHERE n.nspname OPERATOR(pg_catalog.~~) ? AND c.relname OPERATOR(pg_catalog.=) ? AND a.attname OPERATOR(pg_catalog.~~) ?) x "
+ "WHERE (x.g).privilege_type IN ('SELECT','INSERT','UPDATE','REFERENCES') "
+ "ORDER BY x.col, (x.g).privilege_type";
List<Object[]> rows = !catalogSelects(catalog)
? List.of()
: query(
Expand Down Expand Up @@ -1918,16 +1957,12 @@ public ResultSet getTablePrivileges(String catalog, String schemaPattern, String
// relacl still grants the owner every privilege: acldefault(...) synthesizes that default ACL, so
// the owner's grants are reported (matching pgjdbc). aclexplode's privilege_type is already the JDBC
// privilege name; grantee 0 is PUBLIC.
String sql = "SELECT n.nspname AS schem, c.relname AS tbl, "
+ "pg_catalog.pg_get_userbyid(g.grantor) AS grantor, "
+ "CASE WHEN g.grantee OPERATOR(pg_catalog.=) 0 THEN 'PUBLIC' ELSE pg_catalog.pg_get_userbyid(g.grantee) END AS grantee, "
+ "g.privilege_type AS priv, "
+ "CASE WHEN g.is_grantable THEN 'YES' ELSE 'NO' END AS grantable "
String sql = "SELECT x.schem, x.tbl, " + EXPLODED_ACL_COLUMNS
+ "FROM (SELECT n.nspname AS schem, c.relname AS tbl, "
+ "pg_catalog.aclexplode(COALESCE(c.relacl, " + ownerDefaultAcl() + ")) AS g "
+ "FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace "
+ "CROSS JOIN LATERAL "
+ "pg_catalog.aclexplode(COALESCE(c.relacl, pg_catalog.acldefault('r'::\"char\", c.relowner))) g "
+ "WHERE c.relkind IN ('r','p','v','m','f') AND n.nspname OPERATOR(pg_catalog.~~) ? AND c.relname OPERATOR(pg_catalog.~~) ? "
+ "ORDER BY n.nspname, c.relname, g.privilege_type";
+ "WHERE c.relkind IN ('r','p','v','m','f') AND n.nspname OPERATOR(pg_catalog.~~) ? AND c.relname OPERATOR(pg_catalog.~~) ?) x "
+ "ORDER BY x.schem, x.tbl, (x.g).privilege_type";
List<Object[]> rows =
query(sql, List.of(pattern(schemaPattern), pattern(tableNamePattern)), rs -> new Object[] {
catalogName(),
Expand Down Expand Up @@ -2033,7 +2068,7 @@ public ResultSet getUDTs(String catalog, String schemaPattern, String typeNamePa
}
}
String sql = "SELECT n.nspname AS schem, t.typname AS name, t.typtype AS kind, t.typbasetype AS basetype, "
+ "pg_catalog.obj_description(t.oid, 'pg_type') AS remarks "
+ description("t.oid", "pg_type", "0") + " AS remarks "
+ "FROM pg_catalog.pg_type t JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace "
+ "WHERE t.typtype IN ('c','d','e') AND n.nspname OPERATOR(pg_catalog.~~) ? AND t.typname OPERATOR(pg_catalog.~~) ? "
+ "ORDER BY n.nspname, t.typname";
Expand Down Expand Up @@ -2106,7 +2141,7 @@ public ResultSet getAttributes(
+ "a.atttypid AS typid, a.atttypmod AS typmod, a.attnotnull AS notnull, "
+ "pg_catalog.row_number() OVER (PARTITION BY c.oid ORDER BY a.attnum) AS ord, "
+ "pg_catalog.pg_get_expr(ad.adbin, ad.adrelid) AS def, "
+ "pg_catalog.col_description(c.oid, a.attnum) AS remarks "
+ description("c.oid", "pg_class", "a.attnum") + " AS remarks "
+ "FROM pg_catalog.pg_type t "
+ "JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace "
+ "JOIN pg_catalog.pg_class c ON c.oid = t.typrelid "
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
package org.postgresql.client.jdbc.it;

import static org.junit.jupiter.api.Assertions.assertTrue;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashSet;
import java.util.Set;
import org.junit.jupiter.api.Test;

/**
* getTablePrivileges and getColumnPrivileges on every supported server: the owner's default grants
* for a table with no ACL (acldefault, or its 9.1 stand-in), and an explicit grant to PUBLIC.
*/
class PrivilegesMetaDataIT extends AbstractJdbcPostgresIT {

private static void exec(Connection con, String sql) throws SQLException {
try (Statement st = con.createStatement()) {
st.execute(sql);
}
}

private static String currentUser(Connection con) throws SQLException {
try (Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT current_user")) {
assertTrue(rs.next());
return rs.getString(1);
}
}

/** "grantee privilege" pairs of a privileges result set. */
private static Set<String> grants(ResultSet rs) throws SQLException {
try (rs) {
Set<String> grants = new HashSet<>();
while (rs.next()) {
grants.add(rs.getString("GRANTEE") + " " + rs.getString("PRIVILEGE"));
}
return grants;
}
}

@Test
void ownerDefaultGrantsAreReported() throws SQLException {
try (Connection con = connect()) {
exec(con, "DROP TABLE IF EXISTS priv_default");
exec(con, "CREATE TABLE priv_default (a int)");
String owner = currentUser(con);

Set<String> table = grants(con.getMetaData().getTablePrivileges(null, "public", "priv_default"));
assertTrue(table.contains(owner + " SELECT"), table.toString());
assertTrue(table.contains(owner + " TRUNCATE"), table.toString());

Set<String> column = grants(con.getMetaData().getColumnPrivileges(null, "public", "priv_default", "a"));
assertTrue(column.contains(owner + " SELECT"), column.toString());
assertTrue(column.contains(owner + " UPDATE"), column.toString());
exec(con, "DROP TABLE priv_default");
}
}

@Test
void anExplicitGrantToPublicIsReported() throws SQLException {
try (Connection con = connect()) {
exec(con, "DROP TABLE IF EXISTS priv_public");
exec(con, "CREATE TABLE priv_public (a int)");
exec(con, "GRANT SELECT ON priv_public TO PUBLIC");

Set<String> table = grants(con.getMetaData().getTablePrivileges(null, "public", "priv_public"));
assertTrue(table.contains("PUBLIC SELECT"), table.toString());

Set<String> column = grants(con.getMetaData().getColumnPrivileges(null, "public", "priv_public", "a"));
assertTrue(column.contains("PUBLIC SELECT"), column.toString());
exec(con, "DROP TABLE priv_public");
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ private static Connection shadowedConnection() throws SQLException {
exec(con, "CREATE TABLE sh_child (id serial PRIMARY KEY, parent int4 REFERENCES sh_parent)");
exec(con, "CREATE INDEX sh_child_parent ON sh_child (parent)");
exec(con, "CREATE TYPE sh_pair AS (a int4, b text)");
exec(con, "CREATE FUNCTION sh_fn(x int4) RETURNS sh_pair LANGUAGE sql AS $$SELECT x, 'v'::text$$");
exec(con, "CREATE FUNCTION sh_fn(x int4) RETURNS sh_pair LANGUAGE sql AS $$SELECT $1, 'v'::text$$");
exec(con, "INSERT INTO sh_parent VALUES (1, 'one')");
for (int i = 0; i < SHADOWED.length; i++) {
String[] s = SHADOWED[i];
Expand All @@ -70,7 +70,7 @@ private static Connection shadowedConnection() throws SQLException {
exec(
con,
"CREATE OPERATOR " + SCHEMA + "." + s[2] + " (LEFTARG = " + s[0] + ", RIGHTARG = " + s[1]
+ ", FUNCTION = " + fn + ")");
+ ", PROCEDURE = " + fn + ")");
}
return con;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ void catalogLookupsUsePgCatalogOperators() throws SQLException {
+ " AS $$BEGIN RAISE EXCEPTION 'shadowing operator ran'; END$$");
exec(
con,
"CREATE OPERATOR " + SCHEMA + ".= (LEFTARG = oid, RIGHTARG = int4, FUNCTION = " + SCHEMA
"CREATE OPERATOR " + SCHEMA + ".= (LEFTARG = oid, RIGHTARG = int4, PROCEDURE = " + SCHEMA
+ ".shadow_eq)");

assertEquals(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ private static PgConnection shadowedConnection(String schema) {
c.execute("CREATE FUNCTION " + schema + ".shadow_eq(oid, int4) RETURNS bool LANGUAGE plpgsql"
+ " AS $$BEGIN RAISE EXCEPTION 'shadowing operator ran'; END$$")
.close();
c.execute("CREATE OPERATOR " + schema + ".= (LEFTARG = oid, RIGHTARG = int4, FUNCTION = " + schema
c.execute("CREATE OPERATOR " + schema + ".= (LEFTARG = oid, RIGHTARG = int4, PROCEDURE = " + schema
+ ".shadow_eq)")
.close();
c.execute("CREATE FUNCTION " + schema + ".set_config(text, varchar, bool) RETURNS text"
Expand All @@ -52,7 +52,7 @@ void typeLookupsUsePgCatalogOperators() {
c.resolveType(typeOid(c, "shadow_mood"));
c.resolveType(typeOid(c, "shadow_pt"));
List<PgComposite> points = List.of(new PgComposite("shadow_pt", List.of(1, 2)));
try (PgResultStream rs = c.execute("SELECT cardinality($1::shadow_pt[])", List.<Object>of(points))) {
try (PgResultStream rs = c.execute("SELECT array_length($1::shadow_pt[], 1)", List.<Object>of(points))) {
assertTrue(rs.next(), "expected one row");
assertEquals(1, rs.currentRow().getInt(1));
}
Expand Down
Loading