pg.ddx.io pgsql-hackers@postgresql.org mailing list archive
help / color / mirror / Atom feedOddity in handling of cached plans for FDW queries
19+ messages / 4 participants
[nested] [flat]
* Oddity in handling of cached plans for FDW queries
@ 2016-07-12 12:40 Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>
2016-07-13 09:00 ` Re: Oddity in handling of cached plans for FDW queries Ashutosh Bapat <ashutosh.bapat@enterprisedb.com>
0 siblings, 1 reply; 19+ messages in thread
From: Etsuro Fujita @ 2016-07-12 12:40 UTC (permalink / raw)
To: pgsql-hackers
Hi,
I noticed odd behavior in invalidating a cached plan with a foreign join
due to user mapping changes. Consider:
postgres=# create extension postgres_fdw;
postgres=# create server loopback foreign data wrapper postgres_fdw
options (dbname 'postgres');
postgres=# create user mapping for public server loopback;
postgres=# create table t1 (a int, b int);
postgres=# insert into t1 values (1, 1);
postgres=# create foreign table ft1 (a int, b int) server loopback
options (table_name 't1');
postgres=# analyze ft1;
postgres=# create view v1 as select * from ft1;
postgres=# create user v1_owner;
postgres=# alter view v1 owner to v1_owner;
postgres=# grant select on ft1 to v1_owner;
postgres=# prepare join_stmt as select * from ft1, v1 where ft1.a = v1.a;
postgres=# explain verbose execute join_stmt;
QUERY PLAN
--------------------------------------------------------------------------------------------------------------
Foreign Scan (cost=100.00..102.04 rows=1 width=16)
Output: ft1.a, ft1.b, ft1_1.a, ft1_1.b
Relations: (public.ft1) INNER JOIN (public.ft1)
Remote SQL: SELECT r1.a, r1.b, r5.a, r5.b FROM (public.t1 r1 INNER
JOIN public.t1 r5 ON (((r1.a = r5.a))))
(4 rows)
That's great.
postgres=# create user mapping for v1_owner server loopback;
postgres=# explain verbose execute join_stmt;
QUERY PLAN
------------------------------------------------------------------------------
Nested Loop (cost=200.00..202.07 rows=1 width=16)
Output: ft1.a, ft1.b, ft1_1.a, ft1_1.b
Join Filter: (ft1.a = ft1_1.a)
-> Foreign Scan on public.ft1 (cost=100.00..101.03 rows=1 width=8)
Output: ft1.a, ft1.b
Remote SQL: SELECT a, b FROM public.t1
-> Foreign Scan on public.ft1 ft1_1 (cost=100.00..101.03 rows=1
width=8)
Output: ft1_1.a, ft1_1.b
Remote SQL: SELECT a, b FROM public.t1
(9 rows)
That's also great. Since ft1 and v1 use different user mappings, the
join should not be pushed down.
postgres=# drop user mapping for v1_owner server loopback;
postgres=# explain verbose execute join_stmt;
QUERY PLAN
------------------------------------------------------------------------------
Nested Loop (cost=200.00..202.07 rows=1 width=16)
Output: ft1.a, ft1.b, ft1_1.a, ft1_1.b
Join Filter: (ft1.a = ft1_1.a)
-> Foreign Scan on public.ft1 (cost=100.00..101.03 rows=1 width=8)
Output: ft1.a, ft1.b
Remote SQL: SELECT a, b FROM public.t1
-> Foreign Scan on public.ft1 ft1_1 (cost=100.00..101.03 rows=1
width=8)
Output: ft1_1.a, ft1_1.b
Remote SQL: SELECT a, b FROM public.t1
(9 rows)
Seems odd to me. Both relations use the same user mapping as before, so
the join should be pushed down.
Another thing I noticed is that the code in plancache.c would invalidate
a cached plan with a foreign join due to user mapping changes even in
the case where user mappings are meaningless to the FDW.
To fix the first, I'd like to propose (1) replacing the existing
has_foreign_join flag in the CachedPlan data structure with a new flag,
say uses_user_mapping, that indicates whether a cached plan uses any
user mapping regardless of whether the cached plan has foreign joins or
not (likewise, replace the hasForeignJoin flag in PlannedStmt), and (2)
invalidating the cached plan if the uses_user_mapping flag is true. I
thought that we invalidate the cached plan if the flag is true and there
is a possibility of performing foreign joins, but it seems to me that
updates on the corresponding catalog are infrequent enough that such a
detailed tracking is not worth the effort. One benefit of using the
proposed approach is that we could make the FDW's handling of user
mappings in BeginForeignScan more efficient; currently, there is
additional overhead caused by catalog re-lookups to obtain the user
mapping information for the simple-foreign-table-scan case where user
mappings mean something to the FDW as in postgres_fdw (probably, updates
on the catalogs are infrequent, though), but we could improve the
efficiency by using the validated user mapping information created at
planning time for that case as well as for the foreign-join case. For
that, I'd like to propose storing the validated user mapping information
into ForeignScan, not fdw_private. There is a discussion about using an
ExtensibleNode [1] for that, but the proposed approach would make the
FDW's job much simpler.
I don't think the above change is sufficient to fix the second. The
root reason for that is that since currently, we allow the user mapping
OID (rel->umid) to be InvalidOid in two cases: (1) user mappings mean
something to the FDW but it can't get any user mapping at planning time
and (2) user mappings are meaningless to the FDW, we cannot distinguish
these two cases. So, I'd like to introduce a new callback routine to
specify that user mappings mean something to the FDW as proposed by Tom
[2], and use that to reject the former case, which allows us to set the
above uses_user_mapping flag appropriately, ie, set the flag to true
only if user mapping changes require forcing a replan. This would
change the postgres_fdw's behavior that it allows to prepare statements
involving foreign tables without any user mappings as long as those
aren't required at planning time, but I'm not sure that it's a good idea
to keep that behavior because ISTM that such a behavior would make
people sloppy about creating user mappings, which could lead to latent
security problems [2].
Attached is a proposed patch for that.
Best regards,
Etsuro Fujita
[1]
https://www.postgresql.org/message-id/CA%2BTgmoZK6BB4RTb5paz45Vme%3Dq6Z3D7FF2-VKdVyQCS1ps-cGw%40mail...
[2] https://www.postgresql.org/message-id/18299.1457923919%40sss.pgh.pa.us
--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers
Attachments:
user-mapping-handling.patch (text/x-diff, 35.4K) download
*** a/contrib/file_fdw/file_fdw.c
--- b/contrib/file_fdw/file_fdw.c
***************
*** 128,133 **** static void fileBeginForeignScan(ForeignScanState *node, int eflags);
--- 128,134 ----
static TupleTableSlot *fileIterateForeignScan(ForeignScanState *node);
static void fileReScanForeignScan(ForeignScanState *node);
static void fileEndForeignScan(ForeignScanState *node);
+ static bool fileNeedUserMapping(void);
static bool fileAnalyzeForeignTable(Relation relation,
AcquireSampleRowsFunc *func,
BlockNumber *totalpages);
***************
*** 171,176 **** file_fdw_handler(PG_FUNCTION_ARGS)
--- 172,178 ----
fdwroutine->IterateForeignScan = fileIterateForeignScan;
fdwroutine->ReScanForeignScan = fileReScanForeignScan;
fdwroutine->EndForeignScan = fileEndForeignScan;
+ fdwroutine->NeedUserMapping = fileNeedUserMapping;
fdwroutine->AnalyzeForeignTable = fileAnalyzeForeignTable;
fdwroutine->IsForeignScanParallelSafe = fileIsForeignScanParallelSafe;
***************
*** 727,732 **** fileEndForeignScan(ForeignScanState *node)
--- 729,744 ----
}
/*
+ * fileNeedUserMapping
+ * Test whether any user mapping is needed for scanning a foreign table
+ */
+ static bool
+ fileNeedUserMapping(void)
+ {
+ return false;
+ }
+
+ /*
* fileAnalyzeForeignTable
* Test whether analyzing this foreign table is supported
*/
*** a/contrib/postgres_fdw/expected/postgres_fdw.out
--- b/contrib/postgres_fdw/expected/postgres_fdw.out
***************
*** 2086,2117 **** EXECUTE join_stmt;
40 |
(10 rows)
! -- change the session user to view_owner and execute the statement. Because of
! -- change in session user, the plan should get invalidated and created again.
! -- The join will not be pushed down since the joining relations do not have a
! -- valid user mapping.
SET SESSION ROLE view_owner;
EXPLAIN (COSTS OFF, VERBOSE) EXECUTE join_stmt;
! QUERY PLAN
! ------------------------------------------------------------------
! Limit
! Output: t1.c1, t2.c1
! -> Sort
! Output: t1.c1, t2.c1
! Sort Key: t1.c1, t2.c1
! -> Hash Left Join
! Output: t1.c1, t2.c1
! Hash Cond: (t1.c1 = t2.c1)
! -> Foreign Scan on public.ft4 t1
! Output: t1.c1, t1.c2, t1.c3
! Remote SQL: SELECT c1 FROM "S 1"."T 3"
! -> Hash
! Output: t2.c1
! -> Foreign Scan on public.ft5 t2
! Output: t2.c1
! Remote SQL: SELECT c1 FROM "S 1"."T 4"
! (16 rows)
!
RESET ROLE;
DEALLOCATE join_stmt;
CREATE VIEW v_ft5 AS SELECT * FROM ft5;
--- 2086,2098 ----
40 |
(10 rows)
! -- change the session user to view_owner and execute the statement
! -- error thrown due to no user mapping
SET SESSION ROLE view_owner;
EXPLAIN (COSTS OFF, VERBOSE) EXECUTE join_stmt;
! ERROR: user mapping not found for "view_owner"
! EXECUTE join_stmt;
! ERROR: user mapping not found for "view_owner"
RESET ROLE;
DEALLOCATE join_stmt;
CREATE VIEW v_ft5 AS SELECT * FROM ft5;
***************
*** 2168,2173 **** EXECUTE join_stmt;
--- 2149,2176 ----
----+----
(0 rows)
+ -- drop user mapping for view_owner and execute the prepared statement
+ -- both relations use the same user mapping as before, so the join should
+ -- be pushed down
+ DROP USER MAPPING FOR view_owner SERVER loopback;
+ EXPLAIN (COSTS false, VERBOSE) EXECUTE join_stmt;
+ QUERY PLAN
+ ----------------------------------------------------------------------------------------------------------------------------------------------
+ Limit
+ Output: t1.c1, ft5.c1
+ -> Foreign Scan
+ Output: t1.c1, ft5.c1
+ Relations: (public.ft5 t1) INNER JOIN (public.ft5)
+ Remote SQL: SELECT r1.c1, r6.c1 FROM ("S 1"."T 4" r1 INNER JOIN "S 1"."T 4" r6 ON (((r1.c1 = r6.c1)))) ORDER BY r1.c1 ASC NULLS LAST
+ (6 rows)
+
+ EXECUTE join_stmt;
+ c1 | c1
+ ----+----
+ (0 rows)
+
+ -- recreate the dropped user mapping for further tests
+ CREATE USER MAPPING FOR view_owner SERVER loopback;
-- If a sub-join can't be pushed down, upper level join shouldn't be either.
EXPLAIN (COSTS false, VERBOSE)
SELECT t1.c1, t2.c1 FROM (ft5 t1 JOIN v_ft5 t2 ON (t1.c1 = t2.c1)) left join (ft5 t3 JOIN v_ft5 t4 ON (t3.c1 = t4.c1)) ON (t1.c1 = t3.c1);
*** a/contrib/postgres_fdw/postgres_fdw.c
--- b/contrib/postgres_fdw/postgres_fdw.c
***************
*** 67,74 **** enum FdwScanPrivateIndex
FdwScanPrivateRetrievedAttrs,
/* Integer representing the desired fetch_size */
FdwScanPrivateFetchSize,
- /* Oid of user mapping to be used while connecting to the foreign server */
- FdwScanPrivateUserMappingOid,
/*
* String describing join i.e. names of relations being joined and types
--- 67,72 ----
***************
*** 289,294 **** static void postgresBeginForeignScan(ForeignScanState *node, int eflags);
--- 287,293 ----
static TupleTableSlot *postgresIterateForeignScan(ForeignScanState *node);
static void postgresReScanForeignScan(ForeignScanState *node);
static void postgresEndForeignScan(ForeignScanState *node);
+ static bool postgresNeedUserMapping(void);
static void postgresAddForeignUpdateTargets(Query *parsetree,
RangeTblEntry *target_rte,
Relation target_relation);
***************
*** 426,431 **** postgres_fdw_handler(PG_FUNCTION_ARGS)
--- 425,431 ----
routine->IterateForeignScan = postgresIterateForeignScan;
routine->ReScanForeignScan = postgresReScanForeignScan;
routine->EndForeignScan = postgresEndForeignScan;
+ routine->NeedUserMapping = postgresNeedUserMapping;
/* Functions for updating foreign tables */
routine->AddForeignUpdateTargets = postgresAddForeignUpdateTargets;
***************
*** 1226,1236 **** postgresGetForeignPlan(PlannerInfo *root,
* Build the fdw_private list that will be available to the executor.
* Items in the list must match order in enum FdwScanPrivateIndex.
*/
! fdw_private = list_make5(makeString(sql.data),
remote_conds,
retrieved_attrs,
! makeInteger(fpinfo->fetch_size),
! makeInteger(foreignrel->umid));
if (foreignrel->reloptkind == RELOPT_JOINREL)
fdw_private = lappend(fdw_private,
makeString(fpinfo->relation_name->data));
--- 1226,1235 ----
* Build the fdw_private list that will be available to the executor.
* Items in the list must match order in enum FdwScanPrivateIndex.
*/
! fdw_private = list_make4(makeString(sql.data),
remote_conds,
retrieved_attrs,
! makeInteger(fpinfo->fetch_size));
if (foreignrel->reloptkind == RELOPT_JOINREL)
fdw_private = lappend(fdw_private,
makeString(fpinfo->relation_name->data));
***************
*** 1278,1318 **** postgresBeginForeignScan(ForeignScanState *node, int eflags)
node->fdw_state = (void *) fsstate;
/*
- * Obtain the foreign server where to connect and user mapping to use for
- * connection. For base relations we obtain this information from
- * catalogs. For join relations, this information is frozen at the time of
- * planning to ensure that the join is safe to pushdown. In case the
- * information goes stale between planning and execution, plan will be
- * invalidated and replanned.
- */
- if (fsplan->scan.scanrelid > 0)
- {
- ForeignTable *table;
-
- /*
- * Identify which user to do the remote access as. This should match
- * what ExecCheckRTEPerms() does.
- */
- RangeTblEntry *rte = rt_fetch(fsplan->scan.scanrelid, estate->es_range_table);
- Oid userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
-
- fsstate->rel = node->ss.ss_currentRelation;
- table = GetForeignTable(RelationGetRelid(fsstate->rel));
-
- user = GetUserMapping(userid, table->serverid);
- }
- else
- {
- Oid umid = intVal(list_nth(fsplan->fdw_private, FdwScanPrivateUserMappingOid));
-
- user = GetUserMappingById(umid);
- Assert(fsplan->fs_server == user->serverid);
- }
-
- /*
* Get connection to the foreign server. Connection manager will
* establish new connection if necessary.
*/
fsstate->conn = GetConnection(user, false);
/* Assign a unique ID for my cursor */
--- 1277,1286 ----
node->fdw_state = (void *) fsstate;
/*
* Get connection to the foreign server. Connection manager will
* establish new connection if necessary.
*/
+ user = GetUserMappingById(fsplan->fs_usermapping);
fsstate->conn = GetConnection(user, false);
/* Assign a unique ID for my cursor */
***************
*** 1344,1352 **** postgresBeginForeignScan(ForeignScanState *node, int eflags)
--- 1312,1326 ----
* into local representation and error reporting during that process.
*/
if (fsplan->scan.scanrelid > 0)
+ {
+ fsstate->rel = node->ss.ss_currentRelation;
fsstate->tupdesc = RelationGetDescr(fsstate->rel);
+ }
else
+ {
+ fsstate->rel = NULL;
fsstate->tupdesc = node->ss.ss_ScanTupleSlot->tts_tupleDescriptor;
+ }
fsstate->attinmeta = TupleDescGetAttInMetadata(fsstate->tupdesc);
***************
*** 1487,1492 **** postgresEndForeignScan(ForeignScanState *node)
--- 1461,1476 ----
}
/*
+ * postgresNeedUserMapping
+ * Test whether any user mapping is needed for scanning a foreign table
+ */
+ static bool
+ postgresNeedUserMapping(void)
+ {
+ return true;
+ }
+
+ /*
* postgresAddForeignUpdateTargets
* Add resjunk column(s) needed for update/delete on a foreign table
*/
***************
*** 2251,2259 **** postgresBeginDirectModify(ForeignScanState *node, int eflags)
ForeignScan *fsplan = (ForeignScan *) node->ss.ps.plan;
EState *estate = node->ss.ps.state;
PgFdwDirectModifyState *dmstate;
- RangeTblEntry *rte;
- Oid userid;
- ForeignTable *table;
UserMapping *user;
int numParams;
--- 2235,2240 ----
***************
*** 2269,2290 **** postgresBeginDirectModify(ForeignScanState *node, int eflags)
dmstate = (PgFdwDirectModifyState *) palloc0(sizeof(PgFdwDirectModifyState));
node->fdw_state = (void *) dmstate;
- /*
- * Identify which user to do the remote access as. This should match what
- * ExecCheckRTEPerms() does.
- */
- rte = rt_fetch(fsplan->scan.scanrelid, estate->es_range_table);
- userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
-
/* Get info about foreign table. */
dmstate->rel = node->ss.ss_currentRelation;
- table = GetForeignTable(RelationGetRelid(dmstate->rel));
- user = GetUserMapping(userid, table->serverid);
/*
* Get connection to the foreign server. Connection manager will
* establish new connection if necessary.
*/
dmstate->conn = GetConnection(user, false);
/* Initialize state variable */
--- 2250,2263 ----
dmstate = (PgFdwDirectModifyState *) palloc0(sizeof(PgFdwDirectModifyState));
node->fdw_state = (void *) dmstate;
/* Get info about foreign table. */
dmstate->rel = node->ss.ss_currentRelation;
/*
* Get connection to the foreign server. Connection manager will
* establish new connection if necessary.
*/
+ user = GetUserMappingById(fsplan->fs_usermapping);
dmstate->conn = GetConnection(user, false);
/* Initialize state variable */
***************
*** 3966,3981 **** foreign_join_ok(PlannerInfo *root, RelOptInfo *joinrel, JoinType jointype,
List *otherclauses;
/*
- * Core code may call GetForeignJoinPaths hook even when the join relation
- * doesn't have a valid user mapping associated with it. See
- * build_join_rel() for details. We can't push down such join, since there
- * doesn't exist a user mapping which can be used to connect to the
- * foreign server.
- */
- if (!OidIsValid(joinrel->umid))
- return false;
-
- /*
* We support pushing down INNER, LEFT, RIGHT and FULL OUTER joins.
* Constructing queries representing SEMI and ANTI joins is hard, hence
* not considered right now.
--- 3939,3944 ----
*** a/contrib/postgres_fdw/sql/postgres_fdw.sql
--- b/contrib/postgres_fdw/sql/postgres_fdw.sql
***************
*** 494,505 **** GRANT ALL ON ft5 TO view_owner;
PREPARE join_stmt AS SELECT t1.c1, t2.c1 FROM ft4 t1 LEFT JOIN ft5 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c1, t2.c1 OFFSET 10 LIMIT 10;
EXPLAIN (COSTS OFF, VERBOSE) EXECUTE join_stmt;
EXECUTE join_stmt;
! -- change the session user to view_owner and execute the statement. Because of
! -- change in session user, the plan should get invalidated and created again.
! -- The join will not be pushed down since the joining relations do not have a
! -- valid user mapping.
SET SESSION ROLE view_owner;
EXPLAIN (COSTS OFF, VERBOSE) EXECUTE join_stmt;
RESET ROLE;
DEALLOCATE join_stmt;
--- 494,504 ----
PREPARE join_stmt AS SELECT t1.c1, t2.c1 FROM ft4 t1 LEFT JOIN ft5 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c1, t2.c1 OFFSET 10 LIMIT 10;
EXPLAIN (COSTS OFF, VERBOSE) EXECUTE join_stmt;
EXECUTE join_stmt;
! -- change the session user to view_owner and execute the statement
! -- error thrown due to no user mapping
SET SESSION ROLE view_owner;
EXPLAIN (COSTS OFF, VERBOSE) EXECUTE join_stmt;
+ EXECUTE join_stmt;
RESET ROLE;
DEALLOCATE join_stmt;
***************
*** 522,527 **** EXECUTE join_stmt;
--- 521,534 ----
CREATE USER MAPPING FOR view_owner SERVER loopback;
EXPLAIN (COSTS false, VERBOSE) EXECUTE join_stmt;
EXECUTE join_stmt;
+ -- drop user mapping for view_owner and execute the prepared statement
+ -- both relations use the same user mapping as before, so the join should
+ -- be pushed down
+ DROP USER MAPPING FOR view_owner SERVER loopback;
+ EXPLAIN (COSTS false, VERBOSE) EXECUTE join_stmt;
+ EXECUTE join_stmt;
+ -- recreate the dropped user mapping for further tests
+ CREATE USER MAPPING FOR view_owner SERVER loopback;
-- If a sub-join can't be pushed down, upper level join shouldn't be either.
EXPLAIN (COSTS false, VERBOSE)
*** a/doc/src/sgml/fdwhandler.sgml
--- b/doc/src/sgml/fdwhandler.sgml
***************
*** 283,288 **** EndForeignScan (ForeignScanState *node);
--- 283,300 ----
to remote servers should be cleaned up.
</para>
+ <para>
+ <programlisting>
+ bool
+ NeedUserMapping (void);
+ </programlisting>
+
+ Test whether any user mapping is needed for scanning a foreign table.
+ This is called at the beginning of query planning. This function takes
+ no arguments, and return <literal>true</> if the FDW needs user mappings
+ and <literal>false</> otherwise.
+ </para>
+
</sect2>
<sect2 id="fdw-callbacks-join-scan">
*** a/src/backend/executor/execParallel.c
--- b/src/backend/executor/execParallel.c
***************
*** 160,166 **** ExecSerializePlan(Plan *plan, EState *estate)
pstmt->relationOids = NIL;
pstmt->invalItems = NIL; /* workers can't replan anyway... */
pstmt->hasRowSecurity = false;
! pstmt->hasForeignJoin = false;
/* Return serialized copy of our dummy PlannedStmt. */
return nodeToString(pstmt);
--- 160,166 ----
pstmt->relationOids = NIL;
pstmt->invalItems = NIL; /* workers can't replan anyway... */
pstmt->hasRowSecurity = false;
! pstmt->usesUserMapping = false;
/* Return serialized copy of our dummy PlannedStmt. */
return nodeToString(pstmt);
*** a/src/backend/foreign/foreign.c
--- b/src/backend/foreign/foreign.c
***************
*** 31,37 ****
extern Datum pg_options_to_table(PG_FUNCTION_ARGS);
extern Datum postgresql_fdw_validator(PG_FUNCTION_ARGS);
! static HeapTuple find_user_mapping(Oid userid, Oid serverid, bool missing_ok);
/*
* GetForeignDataWrapper - look up the foreign-data wrapper by OID.
--- 31,37 ----
extern Datum pg_options_to_table(PG_FUNCTION_ARGS);
extern Datum postgresql_fdw_validator(PG_FUNCTION_ARGS);
! static HeapTuple find_user_mapping(Oid userid, Oid serverid);
/*
* GetForeignDataWrapper - look up the foreign-data wrapper by OID.
***************
*** 223,229 **** GetUserMapping(Oid userid, Oid serverid)
bool isnull;
UserMapping *um;
! tp = find_user_mapping(userid, serverid, false);
um = (UserMapping *) palloc(sizeof(UserMapping));
um->umid = HeapTupleGetOid(tp);
--- 223,229 ----
bool isnull;
UserMapping *um;
! tp = find_user_mapping(userid, serverid);
um = (UserMapping *) palloc(sizeof(UserMapping));
um->umid = HeapTupleGetOid(tp);
***************
*** 250,272 **** GetUserMapping(Oid userid, Oid serverid)
*
* If no mapping is found for the supplied user, we also look for
* PUBLIC mappings (userid == InvalidOid).
- *
- * If missing_ok is true, the function returns InvalidOid when it does not find
- * required user mapping. Otherwise, find_user_mapping() throws error if it
- * does not find required user mapping.
*/
Oid
! GetUserMappingId(Oid userid, Oid serverid, bool missing_ok)
{
HeapTuple tp;
Oid umid;
! tp = find_user_mapping(userid, serverid, missing_ok);
!
! Assert(missing_ok || tp);
!
! if (!tp && missing_ok)
! return InvalidOid;
/* Extract the Oid */
umid = HeapTupleGetOid(tp);
--- 250,263 ----
*
* If no mapping is found for the supplied user, we also look for
* PUBLIC mappings (userid == InvalidOid).
*/
Oid
! GetUserMappingId(Oid userid, Oid serverid)
{
HeapTuple tp;
Oid umid;
! tp = find_user_mapping(userid, serverid);
/* Extract the Oid */
umid = HeapTupleGetOid(tp);
***************
*** 282,294 **** GetUserMappingId(Oid userid, Oid serverid, bool missing_ok)
*
* If no mapping is found for the supplied user, we also look for
* PUBLIC mappings (userid == InvalidOid).
- *
- * If missing_ok is true, the function returns NULL, if it does not find
- * the required user mapping. Otherwise, it throws error if it does not
- * find the required user mapping.
*/
static HeapTuple
! find_user_mapping(Oid userid, Oid serverid, bool missing_ok)
{
HeapTuple tp;
--- 273,281 ----
*
* If no mapping is found for the supplied user, we also look for
* PUBLIC mappings (userid == InvalidOid).
*/
static HeapTuple
! find_user_mapping(Oid userid, Oid serverid)
{
HeapTuple tp;
***************
*** 305,319 **** find_user_mapping(Oid userid, Oid serverid, bool missing_ok)
ObjectIdGetDatum(serverid));
if (!HeapTupleIsValid(tp))
! {
! if (missing_ok)
! return NULL;
! else
! ereport(ERROR,
! (errcode(ERRCODE_UNDEFINED_OBJECT),
! errmsg("user mapping not found for \"%s\"",
! MappingUserName(userid))));
! }
return tp;
}
--- 292,301 ----
ObjectIdGetDatum(serverid));
if (!HeapTupleIsValid(tp))
! ereport(ERROR,
! (errcode(ERRCODE_UNDEFINED_OBJECT),
! errmsg("user mapping not found for \"%s\"",
! MappingUserName(userid))));
return tp;
}
*** a/src/backend/nodes/copyfuncs.c
--- b/src/backend/nodes/copyfuncs.c
***************
*** 97,103 **** _copyPlannedStmt(const PlannedStmt *from)
COPY_SCALAR_FIELD(nParamExec);
COPY_SCALAR_FIELD(hasRowSecurity);
COPY_SCALAR_FIELD(parallelModeNeeded);
! COPY_SCALAR_FIELD(hasForeignJoin);
return newnode;
}
--- 97,103 ----
COPY_SCALAR_FIELD(nParamExec);
COPY_SCALAR_FIELD(hasRowSecurity);
COPY_SCALAR_FIELD(parallelModeNeeded);
! COPY_SCALAR_FIELD(usesUserMapping);
return newnode;
}
***************
*** 652,657 **** _copyForeignScan(const ForeignScan *from)
--- 652,658 ----
*/
COPY_SCALAR_FIELD(operation);
COPY_SCALAR_FIELD(fs_server);
+ COPY_SCALAR_FIELD(fs_usermapping);
COPY_NODE_FIELD(fdw_exprs);
COPY_NODE_FIELD(fdw_private);
COPY_NODE_FIELD(fdw_scan_tlist);
*** a/src/backend/nodes/outfuncs.c
--- b/src/backend/nodes/outfuncs.c
***************
*** 273,279 **** _outPlannedStmt(StringInfo str, const PlannedStmt *node)
WRITE_INT_FIELD(nParamExec);
WRITE_BOOL_FIELD(hasRowSecurity);
WRITE_BOOL_FIELD(parallelModeNeeded);
! WRITE_BOOL_FIELD(hasForeignJoin);
}
/*
--- 273,279 ----
WRITE_INT_FIELD(nParamExec);
WRITE_BOOL_FIELD(hasRowSecurity);
WRITE_BOOL_FIELD(parallelModeNeeded);
! WRITE_BOOL_FIELD(usesUserMapping);
}
/*
***************
*** 610,615 **** _outForeignScan(StringInfo str, const ForeignScan *node)
--- 610,616 ----
WRITE_ENUM_FIELD(operation, CmdType);
WRITE_OID_FIELD(fs_server);
+ WRITE_OID_FIELD(fs_usermapping);
WRITE_NODE_FIELD(fdw_exprs);
WRITE_NODE_FIELD(fdw_private);
WRITE_NODE_FIELD(fdw_scan_tlist);
***************
*** 2018,2024 **** _outPlannerGlobal(StringInfo str, const PlannerGlobal *node)
WRITE_BOOL_FIELD(hasRowSecurity);
WRITE_BOOL_FIELD(parallelModeOK);
WRITE_BOOL_FIELD(parallelModeNeeded);
! WRITE_BOOL_FIELD(hasForeignJoin);
}
static void
--- 2019,2025 ----
WRITE_BOOL_FIELD(hasRowSecurity);
WRITE_BOOL_FIELD(parallelModeOK);
WRITE_BOOL_FIELD(parallelModeNeeded);
! WRITE_BOOL_FIELD(usesUserMapping);
}
static void
*** a/src/backend/nodes/readfuncs.c
--- b/src/backend/nodes/readfuncs.c
***************
*** 1402,1408 **** _readPlannedStmt(void)
READ_INT_FIELD(nParamExec);
READ_BOOL_FIELD(hasRowSecurity);
READ_BOOL_FIELD(parallelModeNeeded);
! READ_BOOL_FIELD(hasForeignJoin);
READ_DONE();
}
--- 1402,1408 ----
READ_INT_FIELD(nParamExec);
READ_BOOL_FIELD(hasRowSecurity);
READ_BOOL_FIELD(parallelModeNeeded);
! READ_BOOL_FIELD(usesUserMapping);
READ_DONE();
}
***************
*** 1806,1811 **** _readForeignScan(void)
--- 1806,1812 ----
READ_ENUM_FIELD(operation, CmdType);
READ_OID_FIELD(fs_server);
+ READ_OID_FIELD(fs_usermapping);
READ_NODE_FIELD(fdw_exprs);
READ_NODE_FIELD(fdw_private);
READ_NODE_FIELD(fdw_scan_tlist);
*** a/src/backend/optimizer/plan/createplan.c
--- b/src/backend/optimizer/plan/createplan.c
***************
*** 3246,3259 **** create_foreignscan_plan(PlannerInfo *root, ForeignPath *best_path,
/* Likewise, copy the relids that are represented by this foreign scan */
scan_plan->fs_relids = best_path->path.parent->relids;
! /*
! * If a join between foreign relations was pushed down, remember it. The
! * push-down safety of the join depends upon the server and user mapping
! * being same. That can change between planning and execution time, in
! * which case the plan should be invalidated.
! */
! if (scan_relid == 0)
! root->glob->hasForeignJoin = true;
/*
* Replace any outer-relation variables with nestloop params in the qual,
--- 3246,3256 ----
/* Likewise, copy the relids that are represented by this foreign scan */
scan_plan->fs_relids = best_path->path.parent->relids;
! /* Likewise, copy user mapping OID */
! scan_plan->fs_usermapping = rel->umid;
!
! /* Detect whether the FDW uses any user mapping */
! root->glob->usesUserMapping = OidIsValid(rel->umid);
/*
* Replace any outer-relation variables with nestloop params in the qual,
*** a/src/backend/optimizer/plan/planner.c
--- b/src/backend/optimizer/plan/planner.c
***************
*** 220,226 **** standard_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
glob->lastPlanNodeId = 0;
glob->transientPlan = false;
glob->hasRowSecurity = false;
! glob->hasForeignJoin = false;
/*
* Assess whether it's feasible to use parallel mode for this query. We
--- 220,226 ----
glob->lastPlanNodeId = 0;
glob->transientPlan = false;
glob->hasRowSecurity = false;
! glob->usesUserMapping = false;
/*
* Assess whether it's feasible to use parallel mode for this query. We
***************
*** 417,423 **** standard_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
result->nParamExec = glob->nParamExec;
result->hasRowSecurity = glob->hasRowSecurity;
result->parallelModeNeeded = glob->parallelModeNeeded;
! result->hasForeignJoin = glob->hasForeignJoin;
return result;
}
--- 417,423 ----
result->nParamExec = glob->nParamExec;
result->hasRowSecurity = glob->hasRowSecurity;
result->parallelModeNeeded = glob->parallelModeNeeded;
! result->usesUserMapping = glob->usesUserMapping;
return result;
}
*** a/src/backend/optimizer/util/relnode.c
--- b/src/backend/optimizer/util/relnode.c
***************
*** 16,21 ****
--- 16,22 ----
#include "miscadmin.h"
#include "catalog/pg_class.h"
+ #include "foreign/fdwapi.h"
#include "foreign/foreign.h"
#include "optimizer/clauses.h"
#include "optimizer/cost.h"
***************
*** 179,195 **** build_simple_rel(PlannerInfo *root, int relid, RelOptKind reloptkind)
* Note that if the plan ends up depending on the user OID in any way
* - e.g. if it depends on the computed user mapping OID - we must
* ensure that it gets invalidated in the case of a user OID change.
! * See RevalidateCachedQuery and more generally the hasForeignJoin
* flags in PlannerGlobal and PlannedStmt.
*
* It's possible, and not necessarily an error, for rel->umid to be
* InvalidOid even though rel->serverid is set. That just means there
* is a server with no user mapping.
*/
! Oid userid;
! userid = OidIsValid(rte->checkAsUser) ? rte->checkAsUser : GetUserId();
! rel->umid = GetUserMappingId(userid, rel->serverid, true);
}
else
rel->umid = InvalidOid;
--- 180,200 ----
* Note that if the plan ends up depending on the user OID in any way
* - e.g. if it depends on the computed user mapping OID - we must
* ensure that it gets invalidated in the case of a user OID change.
! * See RevalidateCachedQuery and more generally the usesUserMapping
* flags in PlannerGlobal and PlannedStmt.
*
* It's possible, and not necessarily an error, for rel->umid to be
* InvalidOid even though rel->serverid is set. That just means there
* is a server with no user mapping.
*/
! if (rel->fdwroutine->NeedUserMapping())
! {
! Oid userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
! rel->umid = GetUserMappingId(userid, rel->serverid);
! }
! else
! rel->umid = InvalidOid;
}
else
rel->umid = InvalidOid;
***************
*** 441,450 **** build_join_rel(PlannerInfo *root,
* Otherwise those fields are left invalid, so FDW API will not be called
* for the join relation.
*
! * For FDWs like file_fdw, which ignore user mapping, the user mapping id
! * associated with the joining relation may be invalid. A valid serverid
! * distinguishes between a pushed down join with no user mapping and a
! * join which can not be pushed down because of user mapping mismatch.
*/
if (OidIsValid(outer_rel->serverid) &&
inner_rel->serverid == outer_rel->serverid &&
--- 446,454 ----
* Otherwise those fields are left invalid, so FDW API will not be called
* for the join relation.
*
! * Note: if the FDW doesn't need user mappings, the user mapping OID is
! * InvalidOid. So, to give the FDW a chance to push down joins in that
! * case as well, allow combining when both sides have InvalidOid.
*/
if (OidIsValid(outer_rel->serverid) &&
inner_rel->serverid == outer_rel->serverid &&
*** a/src/backend/utils/cache/plancache.c
--- b/src/backend/utils/cache/plancache.c
***************
*** 122,128 **** InitPlanCache(void)
CacheRegisterSyscacheCallback(NAMESPACEOID, PlanCacheSysCallback, (Datum) 0);
CacheRegisterSyscacheCallback(OPEROID, PlanCacheSysCallback, (Datum) 0);
CacheRegisterSyscacheCallback(AMOPOPID, PlanCacheSysCallback, (Datum) 0);
! /* User mapping change may invalidate plans with pushed down foreign join */
CacheRegisterSyscacheCallback(USERMAPPINGOID, PlanCacheUserMappingCallback, (Datum) 0);
}
--- 122,128 ----
CacheRegisterSyscacheCallback(NAMESPACEOID, PlanCacheSysCallback, (Datum) 0);
CacheRegisterSyscacheCallback(OPEROID, PlanCacheSysCallback, (Datum) 0);
CacheRegisterSyscacheCallback(AMOPOPID, PlanCacheSysCallback, (Datum) 0);
! /* User mapping change may invalidate plans with user mappings */
CacheRegisterSyscacheCallback(USERMAPPINGOID, PlanCacheUserMappingCallback, (Datum) 0);
}
***************
*** 610,624 **** RevalidateCachedQuery(CachedPlanSource *plansource)
plansource->is_valid = false;
/*
! * If we have a join pushed down to the foreign server and the current
! * user is different from the one for which the plan was created,
! * invalidate the generic plan since user mapping for the new user might
! * make the join unsafe to push down, or change which user mapping is
! * used.
*/
if (plansource->is_valid &&
plansource->gplan &&
! plansource->gplan->has_foreign_join &&
plansource->planUserId != GetUserId())
plansource->gplan->is_valid = false;
--- 610,622 ----
plansource->is_valid = false;
/*
! * If the plan uses user mappings and the current user is different from
! * the one for which the plan was created, force a replan since the user
! * mapping for the new user might change.
*/
if (plansource->is_valid &&
plansource->gplan &&
! plansource->gplan->uses_user_mapping &&
plansource->planUserId != GetUserId())
plansource->gplan->is_valid = false;
***************
*** 1011,1027 **** BuildCachedPlan(CachedPlanSource *plansource, List *qlist,
plan->is_valid = true;
/*
! * Walk through the plist and set hasForeignJoin if any of the plans have
! * it set.
*/
! plan->has_foreign_join = false;
foreach(lc, plist)
{
PlannedStmt *plan_stmt = (PlannedStmt *) lfirst(lc);
if (IsA(plan_stmt, PlannedStmt))
! plan->has_foreign_join =
! plan->has_foreign_join || plan_stmt->hasForeignJoin;
}
/* assign generation number to new plan */
--- 1009,1025 ----
plan->is_valid = true;
/*
! * Walk through the plist and set uses_user_mapping if any of the plans
! * have it set.
*/
! plan->uses_user_mapping = false;
foreach(lc, plist)
{
PlannedStmt *plan_stmt = (PlannedStmt *) lfirst(lc);
if (IsA(plan_stmt, PlannedStmt))
! plan->uses_user_mapping =
! plan->uses_user_mapping || plan_stmt->usesUserMapping;
}
/* assign generation number to new plan */
***************
*** 1891,1897 **** PlanCacheSysCallback(Datum arg, int cacheid, uint32 hashvalue)
* PlanCacheUserMappingCallback
* Syscache inval callback function for user mapping cache invalidation.
*
! * Invalidates plans which have pushed down foreign joins.
*/
static void
PlanCacheUserMappingCallback(Datum arg, int cacheid, uint32 hashvalue)
--- 1889,1895 ----
* PlanCacheUserMappingCallback
* Syscache inval callback function for user mapping cache invalidation.
*
! * Invalidates plans which use user mappings.
*/
static void
PlanCacheUserMappingCallback(Datum arg, int cacheid, uint32 hashvalue)
***************
*** 1911,1922 **** PlanCacheUserMappingCallback(Datum arg, int cacheid, uint32 hashvalue)
continue;
/*
! * If the plan has pushed down foreign joins, those join may become
! * unsafe to push down because of user mapping changes. Invalidate
! * only the generic plan, since changes to user mapping do not
! * invalidate the parse tree.
*/
! if (plansource->gplan && plansource->gplan->has_foreign_join)
plansource->gplan->is_valid = false;
}
}
--- 1909,1918 ----
continue;
/*
! * Invalidate only the generic plan, since changes to user mapping do
! * not invalidate the parse tree.
*/
! if (plansource->gplan && plansource->gplan->uses_user_mapping)
plansource->gplan->is_valid = false;
}
}
*** a/src/include/foreign/fdwapi.h
--- b/src/include/foreign/fdwapi.h
***************
*** 52,57 **** typedef void (*ReScanForeignScan_function) (ForeignScanState *node);
--- 52,59 ----
typedef void (*EndForeignScan_function) (ForeignScanState *node);
+ typedef bool (*NeedUserMapping_function) (void);
+
typedef void (*GetForeignJoinPaths_function) (PlannerInfo *root,
RelOptInfo *joinrel,
RelOptInfo *outerrel,
***************
*** 177,182 **** typedef struct FdwRoutine
--- 179,185 ----
IterateForeignScan_function IterateForeignScan;
ReScanForeignScan_function ReScanForeignScan;
EndForeignScan_function EndForeignScan;
+ NeedUserMapping_function NeedUserMapping;
/*
* Remaining functions are optional. Set the pointer to NULL for any that
*** a/src/include/foreign/foreign.h
--- b/src/include/foreign/foreign.h
***************
*** 72,78 **** typedef struct ForeignTable
extern ForeignServer *GetForeignServer(Oid serverid);
extern ForeignServer *GetForeignServerByName(const char *name, bool missing_ok);
extern UserMapping *GetUserMapping(Oid userid, Oid serverid);
! extern Oid GetUserMappingId(Oid userid, Oid serverid, bool missing_ok);
extern UserMapping *GetUserMappingById(Oid umid);
extern ForeignDataWrapper *GetForeignDataWrapper(Oid fdwid);
extern ForeignDataWrapper *GetForeignDataWrapperByName(const char *name,
--- 72,78 ----
extern ForeignServer *GetForeignServer(Oid serverid);
extern ForeignServer *GetForeignServerByName(const char *name, bool missing_ok);
extern UserMapping *GetUserMapping(Oid userid, Oid serverid);
! extern Oid GetUserMappingId(Oid userid, Oid serverid);
extern UserMapping *GetUserMappingById(Oid umid);
extern ForeignDataWrapper *GetForeignDataWrapper(Oid fdwid);
extern ForeignDataWrapper *GetForeignDataWrapperByName(const char *name,
*** a/src/include/nodes/plannodes.h
--- b/src/include/nodes/plannodes.h
***************
*** 73,79 **** typedef struct PlannedStmt
bool hasRowSecurity; /* row security applied? */
bool parallelModeNeeded; /* parallel mode required to execute? */
! bool hasForeignJoin; /* Plan has a pushed down foreign join */
} PlannedStmt;
/* macro for fetching the Plan associated with a SubPlan node */
--- 73,80 ----
bool hasRowSecurity; /* row security applied? */
bool parallelModeNeeded; /* parallel mode required to execute? */
!
! bool usesUserMapping; /* does use any user mapping */
} PlannedStmt;
/* macro for fetching the Plan associated with a SubPlan node */
***************
*** 534,539 **** typedef struct ForeignScan
--- 535,541 ----
Scan scan;
CmdType operation; /* SELECT/INSERT/UPDATE/DELETE */
Oid fs_server; /* OID of foreign server */
+ Oid fs_usermapping; /* OID of user mapping */
List *fdw_exprs; /* expressions that FDW may evaluate */
List *fdw_private; /* private data for FDW */
List *fdw_scan_tlist; /* optional tlist describing scan tuple */
*** a/src/include/nodes/relation.h
--- b/src/include/nodes/relation.h
***************
*** 127,133 **** typedef struct PlannerGlobal
bool parallelModeNeeded; /* parallel mode actually required? */
! bool hasForeignJoin; /* does have a pushed down foreign join */
} PlannerGlobal;
/* macro for fetching the Plan associated with a SubPlan node */
--- 127,133 ----
bool parallelModeNeeded; /* parallel mode actually required? */
! bool usesUserMapping; /* does use any user mapping */
} PlannerGlobal;
/* macro for fetching the Plan associated with a SubPlan node */
*** a/src/include/utils/plancache.h
--- b/src/include/utils/plancache.h
***************
*** 135,141 **** typedef struct CachedPlan
* changes from this value */
int generation; /* parent's generation number for this plan */
int refcount; /* count of live references to this struct */
! bool has_foreign_join; /* plan has pushed down a foreign join */
MemoryContext context; /* context containing this CachedPlan */
} CachedPlan;
--- 135,141 ----
* changes from this value */
int generation; /* parent's generation number for this plan */
int refcount; /* count of live references to this struct */
! bool uses_user_mapping; /* does CachedPlan use any user mapping */
MemoryContext context; /* context containing this CachedPlan */
} CachedPlan;
^ permalink raw reply [nested|flat] 19+ messages in thread
* Re: Oddity in handling of cached plans for FDW queries
2016-07-12 12:40 Oddity in handling of cached plans for FDW queries Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>
@ 2016-07-13 09:00 ` Ashutosh Bapat <ashutosh.bapat@enterprisedb.com>
2016-07-14 11:40 ` Re: Oddity in handling of cached plans for FDW queries Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>
0 siblings, 1 reply; 19+ messages in thread
From: Ashutosh Bapat @ 2016-07-13 09:00 UTC (permalink / raw)
To: Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>; +Cc: pgsql-hackers
> Seems odd to me. Both relations use the same user mapping as before, so
> the join should be pushed down.
>
> Another thing I noticed is that the code in plancache.c would invalidate a
> cached plan with a foreign join due to user mapping changes even in the
> case where user mappings are meaningless to the FDW.
>
> To fix the first, I'd like to propose (1) replacing the existing
> has_foreign_join flag in the CachedPlan data structure with a new flag, say
> uses_user_mapping, that indicates whether a cached plan uses any user
> mapping regardless of whether the cached plan has foreign joins or not
> (likewise, replace the hasForeignJoin flag in PlannedStmt), and (2)
> invalidating the cached plan if the uses_user_mapping flag is true. I
> thought that we invalidate the cached plan if the flag is true and there is
> a possibility of performing foreign joins, but it seems to me that updates
> on the corresponding catalog are infrequent enough that such a detailed
> tracking is not worth the effort.
That way we will have plan cache invalidations even when simple foreign
tables scans (not join) are involved, which means all the plans involving
any reference to a foreign table with valid user mapping associated with
it. That can be a huge cost as compared to the current solution where
sub-optimal plan will be used only when a user mapping is changed while a
statement has been prepared. That's a rare scenario and somebody can work
around that by preparing the statement again. IIRC, we had discussed this
situation when implementing the cache invalidation logic. But there's no
workaround for your solution.
> One benefit of using the proposed approach is that we could make the FDW's
> handling of user mappings in BeginForeignScan more efficient; currently,
> there is additional overhead caused by catalog re-lookups to obtain the
> user mapping information for the simple-foreign-table-scan case where user
> mappings mean something to the FDW as in postgres_fdw (probably, updates on
> the catalogs are infrequent, though), but we could improve the efficiency
> by using the validated user mapping information created at planning time
> for that case as well as for the foreign-join case. For that, I'd like to
> propose storing the validated user mapping information into ForeignScan,
> not fdw_private.
postgres_fdw to fetches user mapping in some cases but never remembers it.
If what you are describing is a better way, it should have been implemented
before join pushdown was implemented. Refetching a user mapping is not that
expensive given that there is a high chance that it will be found in the
syscache, because it was accessed at the time of planning. Effect of plan
cache invalidation is probably worse than fetching the value from a sys
cache again.
> There is a discussion about using an ExtensibleNode [1] for that, but the
> proposed approach would make the FDW's job much simpler.
>
> I don't think the above change is sufficient to fix the second. The root
> reason for that is that since currently, we allow the user mapping OID
> (rel->umid) to be InvalidOid in two cases: (1) user mappings mean something
> to the FDW but it can't get any user mapping at planning time and (2) user
> mappings are meaningless to the FDW, we cannot distinguish these two cases.
The way to differentiate between these two is to look at the serverid. If
server id is invalid it's the case 1, otherwise 2. For a simple table,
there will always be a serverid associated with it. A user mapping will
always be associated with a simple table if there is one i.e. FDW requires
it. Albeit, there will be a case when FDW requires a user mapping but it's
not created, in which case the table will be useless for fetching remote
data anyway. I don't think we should be programming for that case.
> So, I'd like to introduce a new callback routine to specify that user
> mappings mean something to the FDW as proposed by Tom [2], and use that to
> reject the former case, which allows us to set the above uses_user_mapping
> flag appropriately, ie, set the flag to true only if user mapping changes
> require forcing a replan. This would change the postgres_fdw's behavior
> that it allows to prepare statements involving foreign tables without any
> user mappings as long as those aren't required at planning time, but I'm
> not sure that it's a good idea to keep that behavior because ISTM that such
> a behavior would make people sloppy about creating user mappings, which
> could lead to latent security problems [2].
>
> Attached is a proposed patch for that.
>
>
This routine is meaningless unless the core (or FDW) does not allow a user
mapping to be created for such FDWs. Without that, core code would get
confused as to what it should do when it sees a user mapping for an FDW
which says user mappings are meaningless. If we do that, we might not set
hasForeignJoin flag in create_foreignscan_plan() when the user mapping for
pushed down join is invalid. That will keep FDWs which do not use user
mappings out of plan cache invalidation.
--
Best Wishes,
Ashutosh Bapat
EnterpriseDB Corporation
The Postgres Database Company
^ permalink raw reply [nested|flat] 19+ messages in thread
* Re: Oddity in handling of cached plans for FDW queries
2016-07-12 12:40 Oddity in handling of cached plans for FDW queries Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>
2016-07-13 09:00 ` Re: Oddity in handling of cached plans for FDW queries Ashutosh Bapat <ashutosh.bapat@enterprisedb.com>
@ 2016-07-14 11:40 ` Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>
2016-07-14 12:26 ` Re: Oddity in handling of cached plans for FDW queries Ashutosh Bapat <ashutosh.bapat@enterprisedb.com>
0 siblings, 1 reply; 19+ messages in thread
From: Etsuro Fujita @ 2016-07-14 11:40 UTC (permalink / raw)
To: Ashutosh Bapat <ashutosh.bapat@enterprisedb.com>; +Cc: pgsql-hackers
On 2016/07/13 18:00, Ashutosh Bapat wrote:
> To fix the first, I'd like to propose (1) replacing the existing
> has_foreign_join flag in the CachedPlan data structure with a new
> flag, say uses_user_mapping, that indicates whether a cached plan
> uses any user mapping regardless of whether the cached plan has
> foreign joins or not (likewise, replace the hasForeignJoin flag in
> PlannedStmt), and (2) invalidating the cached plan if the
> uses_user_mapping flag is true.
> That way we will have plan cache invalidations even when simple foreign
> tables scans (not join) are involved, which means all the plans
> involving any reference to a foreign table with valid user mapping
> associated with it. That can be a huge cost as compared to the current
> solution where sub-optimal plan will be used only when a user mapping is
> changed while a statement has been prepared. That's a rare scenario and
> somebody can work around that by preparing the statement again.
I'm not sure that's a good workaround. ISTM that people often don't pay
much attention to plan changes, so they would execute the inefficient
plan without realizing the plan change, it would take long, they would
start thinking what's happening there, and finally, they would find that
the reason for that is due to the plan change. I think we should
prevent such a trouble.
> IIRC, we
> had discussed this situation when implementing the cache invalidation
> logic.
I didn't know that. Sorry for speaking up late.
> But there's no workaround for your solution.
As you said, this is a rare scenario; in many cases, people define user
mappings properly beforehand. So, just invalidating all relevant plans
on the syscache invalidation events would be fine. (I thought one
possible improvement might be to track exactly the dependencies of plans
on user mappings and invalidate just those plans that depend on the user
mapping being modified the same way for user-defined functions, but I'm
not sure it's worth complicating the code.)
> One benefit of using the proposed approach is that we could make the
> FDW's handling of user mappings in BeginForeignScan more efficient;
> currently, there is additional overhead caused by catalog re-lookups
> to obtain the user mapping information for the
> simple-foreign-table-scan case where user mappings mean something to
> the FDW as in postgres_fdw (probably, updates on the catalogs are
> infrequent, though), but we could improve the efficiency by using
> the validated user mapping information created at planning time for
> that case as well as for the foreign-join case.
> postgres_fdw to fetches user mapping in some cases but never remembers
> it. If what you are describing is a better way, it should have been
> implemented before join pushdown was implemented. Refetching a user
> mapping is not that expensive given that there is a high chance that it
> will be found in the syscache, because it was accessed at the time of
> planning.
That assumption is reasonably valid if execution is done immediately
after planning, but that doesn't necessarily follow.
> Effect of plan cache invalidation is probably worse than
> fetching the value from a sys cache again.
As I said above, we could expect updates on pg_user_mapping to be
infrequent, so the effect of the plan cache invalidation would be more
limited than that of re-fetching user mappings during BeginForeignScan.
> I don't think the above change is sufficient to fix the second. The
> root reason for that is that since currently, we allow the user
> mapping OID (rel->umid) to be InvalidOid in two cases: (1) user
> mappings mean something to the FDW but it can't get any user mapping
> at planning time and (2) user mappings are meaningless to the FDW,
> we cannot distinguish these two cases.
> The way to differentiate between these two is to look at the serverid.
> If server id is invalid it's the case 1,
Really? Maybe my explanation was not good, but consider a foreign join
plan created through GetForeignJoinPaths, by an FDW to which user
mappings are meaningless, like file_fdw. In that plan, the
corresponding server id would be valid, not invalid. No?
> So, I'd like to introduce a new callback routine to specify that
> user mappings mean something to the FDW as proposed by Tom [2], and
> use that to reject the former case, which allows us to set the above
> uses_user_mapping flag appropriately, ie, set the flag to true only
> if user mapping changes require forcing a replan.
> This routine is meaningless unless the core (or FDW) does not allow a
> user mapping to be created for such FDWs. Without that, core code would
> get confused as to what it should do when it sees a user mapping for an
> FDW which says user mappings are meaningless.
The core wouldn't care about such a user mapping for the FDW; the core
would just ignore the user mapping. No?
Best regards,
Etsuro Fujita
--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers
^ permalink raw reply [nested|flat] 19+ messages in thread
* Re: Oddity in handling of cached plans for FDW queries
2016-07-12 12:40 Oddity in handling of cached plans for FDW queries Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>
2016-07-13 09:00 ` Re: Oddity in handling of cached plans for FDW queries Ashutosh Bapat <ashutosh.bapat@enterprisedb.com>
2016-07-14 11:40 ` Re: Oddity in handling of cached plans for FDW queries Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>
@ 2016-07-14 12:26 ` Ashutosh Bapat <ashutosh.bapat@enterprisedb.com>
2016-07-14 16:32 ` Re: Oddity in handling of cached plans for FDW queries Tom Lane <tgl@sss.pgh.pa.us>
0 siblings, 1 reply; 19+ messages in thread
From: Ashutosh Bapat @ 2016-07-14 12:26 UTC (permalink / raw)
To: Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>; +Cc: pgsql-hackers
On Thu, Jul 14, 2016 at 5:10 PM, Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>
wrote:
> On 2016/07/13 18:00, Ashutosh Bapat wrote:
>
>> To fix the first, I'd like to propose (1) replacing the existing
>> has_foreign_join flag in the CachedPlan data structure with a new
>> flag, say uses_user_mapping, that indicates whether a cached plan
>> uses any user mapping regardless of whether the cached plan has
>> foreign joins or not (likewise, replace the hasForeignJoin flag in
>> PlannedStmt), and (2) invalidating the cached plan if the
>> uses_user_mapping flag is true.
>>
>
> That way we will have plan cache invalidations even when simple foreign
>> tables scans (not join) are involved, which means all the plans
>> involving any reference to a foreign table with valid user mapping
>> associated with it. That can be a huge cost as compared to the current
>> solution where sub-optimal plan will be used only when a user mapping is
>> changed while a statement has been prepared. That's a rare scenario and
>> somebody can work around that by preparing the statement again.
>>
>
> I'm not sure that's a good workaround. ISTM that people often don't pay
> much attention to plan changes, so they would execute the inefficient plan
> without realizing the plan change, it would take long, they would start
> thinking what's happening there, and finally, they would find that the
> reason for that is due to the plan change. I think we should prevent such
> a trouble.
>
The case you described is other way round. When the statement was prepared
the join was not pushed down. A change in user mapping afterwards may allow
the join to be pushed down. But right now it won't be, so a user wouldn't
see any difference, right?
>
> IIRC, we
>> had discussed this situation when implementing the cache invalidation
>> logic.
>>
>
> I didn't know that. Sorry for speaking up late.
>
> But there's no workaround for your solution.
>>
>
> As you said, this is a rare scenario; in many cases, people define user
> mappings properly beforehand. So, just invalidating all relevant plans on
> the syscache invalidation events would be fine. (I thought one possible
> improvement might be to track exactly the dependencies of plans on user
> mappings and invalidate just those plans that depend on the user mapping
> being modified the same way for user-defined functions, but I'm not sure
> it's worth complicating the code.)
>
Exactly, for a rare scenario, should we be penalizing large number of plans
or just continue to use a previously prepared plan when an optimal plan has
become available because of changed condition. I would choose second over
the first as it doesn't make things worse than they are.
> I don't think the above change is sufficient to fix the second. The
>> root reason for that is that since currently, we allow the user
>> mapping OID (rel->umid) to be InvalidOid in two cases: (1) user
>> mappings mean something to the FDW but it can't get any user mapping
>> at planning time and (2) user mappings are meaningless to the FDW,
>> we cannot distinguish these two cases.
>>
>
> The way to differentiate between these two is to look at the serverid.
>> If server id is invalid it's the case 1,
>>
>
> Really? Maybe my explanation was not good, but consider a foreign join
> plan created through GetForeignJoinPaths, by an FDW to which user mappings
> are meaningless, like file_fdw. In that plan, the corresponding server id
> would be valid, not invalid. No?
>
While planning join, we invalidate user mapping id if the user mappings do
not match (see build_join_rel()). In such case, the joinrel will have
invalid user mapping (and invalid server id) even though user mapping is
associated with the joining tables. The way to differentiate between this
case and the case when an FDW doesn't need user mappings and the join is
shippable is through valid serverid (see build_join_rel()).
Non-availability of a user mapping for a table whose FDW requires user
mappings should end up in an error (in FDW code), so we shouldn't add
complexity for that case.
>
> So, I'd like to introduce a new callback routine to specify that
>> user mappings mean something to the FDW as proposed by Tom [2], and
>> use that to reject the former case, which allows us to set the above
>> uses_user_mapping flag appropriately, ie, set the flag to true only
>> if user mapping changes require forcing a replan.
>>
>
> This routine is meaningless unless the core (or FDW) does not allow a
>> user mapping to be created for such FDWs. Without that, core code would
>> get confused as to what it should do when it sees a user mapping for an
>> FDW which says user mappings are meaningless.
>>
>
> The core wouldn't care about such a user mapping for the FDW; the core
> would just ignore the user mapping. No?
>
See build_join_rel(). I would like to see, how do you change the conditions
below in that function with your proposal.
468 /*
469 * Set up foreign-join fields if outer and inner relation are
foreign
470 * tables (or joins) belonging to the same server and using the
same user
471 * mapping.
472 *
473 * Otherwise those fields are left invalid, so FDW API will not be
called
474 * for the join relation.
475 *
476 * For FDWs like file_fdw, which ignore user mapping, the user
mapping id
477 * associated with the joining relation may be invalid. A valid
serverid
478 * distinguishes between a pushed down join with no user mapping
and a
479 * join which can not be pushed down because of user mapping
mismatch.
480 */
481 if (OidIsValid(outer_rel->serverid) &&
482 inner_rel->serverid == outer_rel->serverid &&
483 inner_rel->umid == outer_rel->umid)
484 {
485 joinrel->serverid = outer_rel->serverid;
486 joinrel->umid = outer_rel->umid;
487 joinrel->fdwroutine = outer_rel->fdwroutine;
488 }
--
Best Wishes,
Ashutosh Bapat
EnterpriseDB Corporation
The Postgres Database Company
^ permalink raw reply [nested|flat] 19+ messages in thread
* Re: Oddity in handling of cached plans for FDW queries
2016-07-12 12:40 Oddity in handling of cached plans for FDW queries Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>
2016-07-13 09:00 ` Re: Oddity in handling of cached plans for FDW queries Ashutosh Bapat <ashutosh.bapat@enterprisedb.com>
2016-07-14 11:40 ` Re: Oddity in handling of cached plans for FDW queries Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>
2016-07-14 12:26 ` Re: Oddity in handling of cached plans for FDW queries Ashutosh Bapat <ashutosh.bapat@enterprisedb.com>
@ 2016-07-14 16:32 ` Tom Lane <tgl@sss.pgh.pa.us>
2016-07-14 18:49 ` Re: Oddity in handling of cached plans for FDW queries Tom Lane <tgl@sss.pgh.pa.us>
2016-07-15 05:13 ` Re: Oddity in handling of cached plans for FDW queries Ashutosh Bapat <ashutosh.bapat@enterprisedb.com>
0 siblings, 2 replies; 19+ messages in thread
From: Tom Lane @ 2016-07-14 16:32 UTC (permalink / raw)
To: Ashutosh Bapat <ashutosh.bapat@enterprisedb.com>; +Cc: Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>; pgsql-hackers
Ashutosh Bapat <ashutosh.bapat@enterprisedb.com> writes:
> Exactly, for a rare scenario, should we be penalizing large number of plans
> or just continue to use a previously prepared plan when an optimal plan has
> become available because of changed condition. I would choose second over
> the first as it doesn't make things worse than they are.
You seem to be arguing from a premise that the worst consequence is use of
an inefficient plan. This is false; the worst consequence is use of a
*wrong* plan, specifically one where a join has been pushed down but doing
so is no longer legal because of a user mapping change. That is, it was
previously correct to access the two remote tables under the same remote
userID but now they should be accessed under different userIDs. The
result will be that one or the other remote table is accessed under a
userID that is not what the current user mappings say should be used.
That could lead to either unexpected permissions failures (if the
actually-used userID lacks needed permissions) or security breakdowns
(if the actually-used userID has permissions to do something but the
query should not have been allowed to do it).
I do not think fixing this is optional.
I concur with Etsuro-san's dislike for hasForeignJoin; that flag is
underspecified and doesn't convey nearly enough information. I do not
think a uses_user_mapping flag is much better. ISTM what should happen is
that any time we decide to push down a foreign join, we should record the
identity of the common user mapping that made that pushdown possible in
the plan's invalItems list. That would make it possible to invalidate
only the relevant plans when a user mapping is changed.
I believe what Ashutosh is focusing on is whether, when some user mapping
changes, we should invalidate all plans that could potentially now use a
pushed-down join but did not before. I tend to agree that that's probably
not something we want to do, as it would be very hard to identify just the
plans likely to benefit. So we would cause replanning of a lot of queries
that won't actually benefit, and in this direction it is indeed only an
optimization not a correctness matter.
Another way we could attack it would be to record the foreign server OID
as an invalItem for any query that has more than one foreign table
belonging to the same foreign server. Then, invalidate whenever any user
mapping for that server changes. This would take care of both the case
where a join pushdown becomes possible and where it stops becoming
possible. But I'm not sure that the extra invalidations would be
worthwhile.
I'm not excited about Etsuro-san's proposal to record user mapping info
in the plan and skip execution-time mapping lookups altogether. I think
(1) that's solving a problem that hasn't been proven to be a problem,
(2) it doesn't help unless the FDW code is changed to take advantage of
it, which is unlikely to happen for third-party FDWs, and (3) it opens
the door to a class of new bugs, as any failure to invalidate after a
mapping change would become a security fail even for non-join situations.
regards, tom lane
--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers
^ permalink raw reply [nested|flat] 19+ messages in thread
* Re: Oddity in handling of cached plans for FDW queries
2016-07-12 12:40 Oddity in handling of cached plans for FDW queries Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>
2016-07-13 09:00 ` Re: Oddity in handling of cached plans for FDW queries Ashutosh Bapat <ashutosh.bapat@enterprisedb.com>
2016-07-14 11:40 ` Re: Oddity in handling of cached plans for FDW queries Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>
2016-07-14 12:26 ` Re: Oddity in handling of cached plans for FDW queries Ashutosh Bapat <ashutosh.bapat@enterprisedb.com>
2016-07-14 16:32 ` Re: Oddity in handling of cached plans for FDW queries Tom Lane <tgl@sss.pgh.pa.us>
@ 2016-07-14 18:49 ` Tom Lane <tgl@sss.pgh.pa.us>
2016-07-15 02:37 ` Re: Oddity in handling of cached plans for FDW queries Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>
2016-07-15 05:27 ` Re: Oddity in handling of cached plans for FDW queries Ashutosh Bapat <ashutosh.bapat@enterprisedb.com>
1 sibling, 2 replies; 19+ messages in thread
From: Tom Lane @ 2016-07-14 18:49 UTC (permalink / raw)
To: Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>; +Cc: Ashutosh Bapat <ashutosh.bapat@enterprisedb.com>; pgsql-hackers
I wrote:
> I concur with Etsuro-san's dislike for hasForeignJoin; that flag is
> underspecified and doesn't convey nearly enough information. I do not
> think a uses_user_mapping flag is much better. ISTM what should happen is
> that any time we decide to push down a foreign join, we should record the
> identity of the common user mapping that made that pushdown possible in
> the plan's invalItems list. That would make it possible to invalidate
> only the relevant plans when a user mapping is changed.
I thought a bit more about this and realized that the above doesn't work
too well. Initially, a join might have been pushed down on the strength
of both userids mapping to a PUBLIC user mapping for the server. If now
someone does CREATE USER MAPPING to install a new mapping for one of
those userids, we should invalidate the plan --- but there is certainly
not going to be anything in the plan matching the new user mapping.
> Another way we could attack it would be to record the foreign server OID
> as an invalItem for any query that has more than one foreign table
> belonging to the same foreign server. Then, invalidate whenever any user
> mapping for that server changes.
And that doesn't work so well either, because the most that the plan inval
code is going to have its hands on is (a hash of) the OID of the user
mapping that changed. We can't tell which server that's for.
On reflection, it seems to me that we've gone wrong by tying planning to
equality of user mappings at all, and the best way to get out of this is
to not do that. Instead, let's insist that a join can be pushed down only
if the checkAsUser fields of the relevant RTEs are equal. If they are,
then the same user mapping must apply to both at runtime, whatever it is
--- and we don't need to predetermine that. With this approach, the need
for plan invalidation due to user mapping changes goes away entirely.
This doesn't cost us anything at all in simple cases such as direct
execution of a query, because all the checkAsUser fields will be equal
(i.e., zero). And it also doesn't hurt if the potential foreign join is
encapsulated in a view, where all the checkAsUser fields would contain
the OID of the view owner.
The situation where we potentially lose something is a case like
Etsuro-san's original example, where the query contains one foreign table
reference coming from a view and one coming from the outer query, or maybe
from a different view. In the two-views case we would have to not push
down the join if the views have different owners, even though perhaps both
owners will use the PUBLIC mapping at runtime. I think that's a narrow
enough case that we can just live with not optimizing it. In the
view-and-outer-query case, the simplest answer is that we can't push down
because zero is not equal to the view owner's OID. We could make that a
little better if we know that the query will be executed as the view
owner, so that the relevant user IDs will be the same at runtime. There
is already some mechanism in the plan cache to track whether a plan
depends on the identity of the user running it (for RLS), so we could use
that to enforce that a plan containing such a pushed-down join is only run
by the same user that owns the view.
Comments?
regards, tom lane
--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers
^ permalink raw reply [nested|flat] 19+ messages in thread
* Re: Oddity in handling of cached plans for FDW queries
2016-07-12 12:40 Oddity in handling of cached plans for FDW queries Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>
2016-07-13 09:00 ` Re: Oddity in handling of cached plans for FDW queries Ashutosh Bapat <ashutosh.bapat@enterprisedb.com>
2016-07-14 11:40 ` Re: Oddity in handling of cached plans for FDW queries Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>
2016-07-14 12:26 ` Re: Oddity in handling of cached plans for FDW queries Ashutosh Bapat <ashutosh.bapat@enterprisedb.com>
2016-07-14 16:32 ` Re: Oddity in handling of cached plans for FDW queries Tom Lane <tgl@sss.pgh.pa.us>
2016-07-14 18:49 ` Re: Oddity in handling of cached plans for FDW queries Tom Lane <tgl@sss.pgh.pa.us>
@ 2016-07-15 02:37 ` Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>
2016-07-15 02:48 ` Re: Oddity in handling of cached plans for FDW queries Tom Lane <tgl@sss.pgh.pa.us>
1 sibling, 1 reply; 19+ messages in thread
From: Etsuro Fujita @ 2016-07-15 02:37 UTC (permalink / raw)
To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Ashutosh Bapat <ashutosh.bapat@enterprisedb.com>; pgsql-hackers
On 2016/07/15 3:49, Tom Lane wrote:
> On reflection, it seems to me that we've gone wrong by tying planning to
> equality of user mappings at all, and the best way to get out of this is
> to not do that. Instead, let's insist that a join can be pushed down only
> if the checkAsUser fields of the relevant RTEs are equal. If they are,
> then the same user mapping must apply to both at runtime, whatever it is
> --- and we don't need to predetermine that. With this approach, the need
> for plan invalidation due to user mapping changes goes away entirely.
+1
> The situation where we potentially lose something is a case like
> Etsuro-san's original example, where the query contains one foreign table
> reference coming from a view and one coming from the outer query, or maybe
> from a different view. In the two-views case we would have to not push
> down the join if the views have different owners, even though perhaps both
> owners will use the PUBLIC mapping at runtime. I think that's a narrow
> enough case that we can just live with not optimizing it. In the
> view-and-outer-query case, the simplest answer is that we can't push down
> because zero is not equal to the view owner's OID. We could make that a
> little better if we know that the query will be executed as the view
> owner, so that the relevant user IDs will be the same at runtime. There
> is already some mechanism in the plan cache to track whether a plan
> depends on the identity of the user running it (for RLS), so we could use
> that to enforce that a plan containing such a pushed-down join is only run
> by the same user that owns the view.
Seems reasonable to me.
One thing I'm not sure about is: should we insist that a join can be
pushed down only if the checkAsUser fields of the relevant RTEs are
equal in the case where user mappings are meaningless to the FDW, like
file_fdw?
Best regards,
Etsuro Fujita
--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers
^ permalink raw reply [nested|flat] 19+ messages in thread
* Re: Oddity in handling of cached plans for FDW queries
2016-07-12 12:40 Oddity in handling of cached plans for FDW queries Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>
2016-07-13 09:00 ` Re: Oddity in handling of cached plans for FDW queries Ashutosh Bapat <ashutosh.bapat@enterprisedb.com>
2016-07-14 11:40 ` Re: Oddity in handling of cached plans for FDW queries Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>
2016-07-14 12:26 ` Re: Oddity in handling of cached plans for FDW queries Ashutosh Bapat <ashutosh.bapat@enterprisedb.com>
2016-07-14 16:32 ` Re: Oddity in handling of cached plans for FDW queries Tom Lane <tgl@sss.pgh.pa.us>
2016-07-14 18:49 ` Re: Oddity in handling of cached plans for FDW queries Tom Lane <tgl@sss.pgh.pa.us>
2016-07-15 02:37 ` Re: Oddity in handling of cached plans for FDW queries Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>
@ 2016-07-15 02:48 ` Tom Lane <tgl@sss.pgh.pa.us>
2016-07-15 12:55 ` Re: Oddity in handling of cached plans for FDW queries Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>
0 siblings, 1 reply; 19+ messages in thread
From: Tom Lane @ 2016-07-15 02:48 UTC (permalink / raw)
To: Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>; +Cc: Ashutosh Bapat <ashutosh.bapat@enterprisedb.com>; pgsql-hackers
Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp> writes:
> One thing I'm not sure about is: should we insist that a join can be
> pushed down only if the checkAsUser fields of the relevant RTEs are
> equal in the case where user mappings are meaningless to the FDW, like
> file_fdw?
If we add a mechanism to let us know that the FDW doesn't care, we could
relax the requirement for such cases. I don't have a strong opinion on
whether that's worthwhile. It'd depend in part on how many FDWs there
are that don't care, versus those that do; and I have no idea about that.
regards, tom lane
--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers
^ permalink raw reply [nested|flat] 19+ messages in thread
* Re: Oddity in handling of cached plans for FDW queries
2016-07-12 12:40 Oddity in handling of cached plans for FDW queries Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>
2016-07-13 09:00 ` Re: Oddity in handling of cached plans for FDW queries Ashutosh Bapat <ashutosh.bapat@enterprisedb.com>
2016-07-14 11:40 ` Re: Oddity in handling of cached plans for FDW queries Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>
2016-07-14 12:26 ` Re: Oddity in handling of cached plans for FDW queries Ashutosh Bapat <ashutosh.bapat@enterprisedb.com>
2016-07-14 16:32 ` Re: Oddity in handling of cached plans for FDW queries Tom Lane <tgl@sss.pgh.pa.us>
2016-07-14 18:49 ` Re: Oddity in handling of cached plans for FDW queries Tom Lane <tgl@sss.pgh.pa.us>
2016-07-15 02:37 ` Re: Oddity in handling of cached plans for FDW queries Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>
2016-07-15 02:48 ` Re: Oddity in handling of cached plans for FDW queries Tom Lane <tgl@sss.pgh.pa.us>
@ 2016-07-15 12:55 ` Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>
2016-07-15 13:35 ` Re: Oddity in handling of cached plans for FDW queries Tom Lane <tgl@sss.pgh.pa.us>
0 siblings, 1 reply; 19+ messages in thread
From: Etsuro Fujita @ 2016-07-15 12:55 UTC (permalink / raw)
To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Ashutosh Bapat <ashutosh.bapat@enterprisedb.com>; pgsql-hackers
On 2016/07/15 11:48, Tom Lane wrote:
> Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp> writes:
>> One thing I'm not sure about is: should we insist that a join can be
>> pushed down only if the checkAsUser fields of the relevant RTEs are
>> equal in the case where user mappings are meaningless to the FDW, like
>> file_fdw?
> If we add a mechanism to let us know that the FDW doesn't care, we could
> relax the requirement for such cases. I don't have a strong opinion on
> whether that's worthwhile. It'd depend in part on how many FDWs there
> are that don't care, versus those that do; and I have no idea about that.
So, I'd vote for leaving that for future work if necessary.
Here is a patch for that redesign proposed by you; reverts commits
fbe5a3fb73102c2cfec11aaaa4a67943f4474383 and
5d4171d1c70edfe3e9be1de9e66603af28e3afe1, adds changes for that redesign
to the core, and adjusts the postgres_fdw code to that changes. Also, I
rearranged the postgres_fdw regression tests to match that changes.
Best regards,
Etsuro Fujita
--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers
Attachments:
fdw-join-pushdown-checkAsUser.patch (text/x-diff, 51.8K) download
*** a/contrib/postgres_fdw/expected/postgres_fdw.out
--- b/contrib/postgres_fdw/expected/postgres_fdw.out
***************
*** 2053,2207 **** SELECT t1."C 1" FROM "S 1"."T 1" t1, LATERAL (SELECT DISTINCT t2.c1, t3.c1 FROM
1
(10 rows)
- -- create another user for permission, user mapping, effective user tests
- CREATE USER view_owner;
- -- grant privileges on ft4 and ft5 to view_owner
- GRANT ALL ON ft4 TO view_owner;
- GRANT ALL ON ft5 TO view_owner;
- -- prepare statement with current session user
- PREPARE join_stmt AS SELECT t1.c1, t2.c1 FROM ft4 t1 LEFT JOIN ft5 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c1, t2.c1 OFFSET 10 LIMIT 10;
- EXPLAIN (COSTS OFF, VERBOSE) EXECUTE join_stmt;
- QUERY PLAN
- -------------------------------------------------------------------------------------------------------------------------------------------------------------------
- Limit
- Output: t1.c1, t2.c1
- -> Foreign Scan
- Output: t1.c1, t2.c1
- Relations: (public.ft4 t1) LEFT JOIN (public.ft5 t2)
- Remote SQL: SELECT r1.c1, r2.c1 FROM ("S 1"."T 3" r1 LEFT JOIN "S 1"."T 4" r2 ON (((r1.c1 = r2.c1)))) ORDER BY r1.c1 ASC NULLS LAST, r2.c1 ASC NULLS LAST
- (6 rows)
-
- EXECUTE join_stmt;
- c1 | c1
- ----+----
- 22 |
- 24 | 24
- 26 |
- 28 |
- 30 | 30
- 32 |
- 34 |
- 36 | 36
- 38 |
- 40 |
- (10 rows)
-
- -- change the session user to view_owner and execute the statement. Because of
- -- change in session user, the plan should get invalidated and created again.
- -- The join will not be pushed down since the joining relations do not have a
- -- valid user mapping.
- SET SESSION ROLE view_owner;
- EXPLAIN (COSTS OFF, VERBOSE) EXECUTE join_stmt;
- QUERY PLAN
- ------------------------------------------------------------------
- Limit
- Output: t1.c1, t2.c1
- -> Sort
- Output: t1.c1, t2.c1
- Sort Key: t1.c1, t2.c1
- -> Hash Left Join
- Output: t1.c1, t2.c1
- Hash Cond: (t1.c1 = t2.c1)
- -> Foreign Scan on public.ft4 t1
- Output: t1.c1, t1.c2, t1.c3
- Remote SQL: SELECT c1 FROM "S 1"."T 3"
- -> Hash
- Output: t2.c1
- -> Foreign Scan on public.ft5 t2
- Output: t2.c1
- Remote SQL: SELECT c1 FROM "S 1"."T 4"
- (16 rows)
-
- RESET ROLE;
- DEALLOCATE join_stmt;
- CREATE VIEW v_ft5 AS SELECT * FROM ft5;
- -- change owner of v_ft5 to view_owner so that the effective user for scan on
- -- ft5 is view_owner and not the current user.
- ALTER VIEW v_ft5 OWNER TO view_owner;
- -- create a public user mapping for loopback server
- -- drop user mapping for current_user.
- DROP USER MAPPING FOR CURRENT_USER SERVER loopback;
- CREATE USER MAPPING FOR PUBLIC SERVER loopback;
- -- different effective user for permission check, but same user mapping for the
- -- joining sides, join pushed down, no result expected.
- PREPARE join_stmt AS SELECT t1.c1, t2.c1 FROM ft5 t1 JOIN v_ft5 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c1, t2.c1 OFFSET 100 LIMIT 10;
- EXPLAIN (COSTS false, VERBOSE) EXECUTE join_stmt;
- QUERY PLAN
- ----------------------------------------------------------------------------------------------------------------------------------------------
- Limit
- Output: t1.c1, ft5.c1
- -> Foreign Scan
- Output: t1.c1, ft5.c1
- Relations: (public.ft5 t1) INNER JOIN (public.ft5)
- Remote SQL: SELECT r1.c1, r6.c1 FROM ("S 1"."T 4" r1 INNER JOIN "S 1"."T 4" r6 ON (((r1.c1 = r6.c1)))) ORDER BY r1.c1 ASC NULLS LAST
- (6 rows)
-
- EXECUTE join_stmt;
- c1 | c1
- ----+----
- (0 rows)
-
- -- create user mapping for view_owner and execute the prepared statement
- -- the join should not be pushed down since joining relations now use two
- -- different user mappings
- CREATE USER MAPPING FOR view_owner SERVER loopback;
- EXPLAIN (COSTS false, VERBOSE) EXECUTE join_stmt;
- QUERY PLAN
- ---------------------------------------------------------------------------------------
- Limit
- Output: t1.c1, ft5.c1
- -> Merge Join
- Output: t1.c1, ft5.c1
- Merge Cond: (t1.c1 = ft5.c1)
- -> Foreign Scan on public.ft5 t1
- Output: t1.c1, t1.c2, t1.c3
- Remote SQL: SELECT c1 FROM "S 1"."T 4" ORDER BY c1 ASC NULLS LAST
- -> Materialize
- Output: ft5.c1, ft5.c2, ft5.c3
- -> Foreign Scan on public.ft5
- Output: ft5.c1, ft5.c2, ft5.c3
- Remote SQL: SELECT c1 FROM "S 1"."T 4" ORDER BY c1 ASC NULLS LAST
- (13 rows)
-
- EXECUTE join_stmt;
- c1 | c1
- ----+----
- (0 rows)
-
- -- If a sub-join can't be pushed down, upper level join shouldn't be either.
- EXPLAIN (COSTS false, VERBOSE)
- SELECT t1.c1, t2.c1 FROM (ft5 t1 JOIN v_ft5 t2 ON (t1.c1 = t2.c1)) left join (ft5 t3 JOIN v_ft5 t4 ON (t3.c1 = t4.c1)) ON (t1.c1 = t3.c1);
- QUERY PLAN
- ------------------------------------------------------------------
- Hash Join
- Output: t1.c1, ft5.c1
- Hash Cond: (t1.c1 = ft5.c1)
- -> Hash Right Join
- Output: t1.c1
- Hash Cond: (t3.c1 = t1.c1)
- -> Hash Join
- Output: t3.c1
- Hash Cond: (t3.c1 = ft5_1.c1)
- -> Foreign Scan on public.ft5 t3
- Output: t3.c1, t3.c2, t3.c3
- Remote SQL: SELECT c1 FROM "S 1"."T 4"
- -> Hash
- Output: ft5_1.c1
- -> Foreign Scan on public.ft5 ft5_1
- Output: ft5_1.c1
- Remote SQL: SELECT c1 FROM "S 1"."T 4"
- -> Hash
- Output: t1.c1
- -> Foreign Scan on public.ft5 t1
- Output: t1.c1
- Remote SQL: SELECT c1 FROM "S 1"."T 4"
- -> Hash
- Output: ft5.c1
- -> Foreign Scan on public.ft5
- Output: ft5.c1
- Remote SQL: SELECT c1 FROM "S 1"."T 4"
- (27 rows)
-
-- non-Var items in targelist of the nullable rel of a join preventing
-- push-down in some cases
-- unable to push {ft1, ft2}
--- 2053,2058 ----
***************
*** 2260,2268 **** SELECT ft4.c1, q.* FROM ft4 LEFT JOIN (SELECT 13, ft1.c1, ft2.c1 FROM ft1 RIGHT
14 | | |
(3 rows)
- -- recreate the dropped user mapping for further tests
- CREATE USER MAPPING FOR CURRENT_USER SERVER loopback;
- DROP USER MAPPING FOR PUBLIC SERVER loopback;
-- join with nullable side with some columns with null values
UPDATE ft5 SET c3 = null where c1 % 9 = 0;
EXPLAIN VERBOSE SELECT ft5, ft5.c1, ft5.c2, ft5.c3, ft4.c1, ft4.c2 FROM ft5 left join ft4 on ft5.c1 = ft4.c1 WHERE ft4.c1 BETWEEN 10 and 30 ORDER BY ft5.c1, ft4.c1;
--- 2111,2116 ----
***************
*** 2283,2288 **** SELECT ft5, ft5.c1, ft5.c2, ft5.c3, ft4.c1, ft4.c2 FROM ft5 left join ft4 on ft5
--- 2131,2324 ----
(30,31,AAA030) | 30 | 31 | AAA030 | 30 | 31
(4 rows)
+ -- join encapsulated in a view
+ DROP USER MAPPING FOR CURRENT_USER SERVER loopback;
+ CREATE USER MAPPING FOR PUBLIC SERVER loopback;
+ CREATE USER view_owner;
+ GRANT SELECT ON ft4 TO view_owner;
+ GRANT SELECT ON ft5 TO view_owner;
+ CREATE VIEW join_view AS SELECT t1.c1, t2.c2 FROM ft4 t1 LEFT JOIN ft5 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c1, t2.c1 OFFSET 10 LIMIT 10;
+ ALTER VIEW join_view OWNER TO view_owner;
+ EXPLAIN (COSTS false, VERBOSE)
+ SELECT * FROM join_view; -- can be pushed down
+ QUERY PLAN
+ --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
+ Subquery Scan on join_view
+ Output: join_view.c1, join_view.c2
+ -> Limit
+ Output: t1.c1, t2.c2, t2.c1
+ -> Foreign Scan
+ Output: t1.c1, t2.c2, t2.c1
+ Relations: (public.ft4 t1) LEFT JOIN (public.ft5 t2)
+ Remote SQL: SELECT r3.c1, r4.c2, r4.c1 FROM ("S 1"."T 3" r3 LEFT JOIN "S 1"."T 4" r4 ON (((r3.c1 = r4.c1)))) ORDER BY r3.c1 ASC NULLS LAST, r4.c1 ASC NULLS LAST
+ (8 rows)
+
+ SELECT * FROM join_view;
+ c1 | c2
+ ----+----
+ 22 |
+ 24 | 25
+ 26 |
+ 28 |
+ 30 | 31
+ 32 |
+ 34 |
+ 36 | 37
+ 38 |
+ 40 |
+ (10 rows)
+
+ -- join between two views
+ CREATE VIEW v4 AS SELECT * FROM ft4;
+ CREATE VIEW v5 AS SELECT * FROM ft5;
+ ALTER VIEW v5 OWNER TO view_owner;
+ EXPLAIN (COSTS false, VERBOSE)
+ SELECT t1.c1, t2.c2 FROM v4 t1 LEFT JOIN v5 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c1, t2.c1 OFFSET 10 LIMIT 10; -- can't be pushed down
+ QUERY PLAN
+ ----------------------------------------------------------------------
+ Limit
+ Output: ft4.c1, ft5.c2, ft5.c1
+ -> Sort
+ Output: ft4.c1, ft5.c2, ft5.c1
+ Sort Key: ft4.c1, ft5.c1
+ -> Hash Left Join
+ Output: ft4.c1, ft5.c2, ft5.c1
+ Hash Cond: (ft4.c1 = ft5.c1)
+ -> Foreign Scan on public.ft4
+ Output: ft4.c1, ft4.c2, ft4.c3
+ Remote SQL: SELECT c1 FROM "S 1"."T 3"
+ -> Hash
+ Output: ft5.c2, ft5.c1
+ -> Foreign Scan on public.ft5
+ Output: ft5.c2, ft5.c1
+ Remote SQL: SELECT c1, c2 FROM "S 1"."T 4"
+ (16 rows)
+
+ SELECT t1.c1, t2.c2 FROM v4 t1 LEFT JOIN v5 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c1, t2.c1 OFFSET 10 LIMIT 10;
+ c1 | c2
+ ----+----
+ 22 |
+ 24 | 25
+ 26 |
+ 28 |
+ 30 | 31
+ 32 |
+ 34 |
+ 36 | 37
+ 38 |
+ 40 |
+ (10 rows)
+
+ ALTER VIEW v4 OWNER TO view_owner;
+ EXPLAIN (COSTS false, VERBOSE)
+ SELECT t1.c1, t2.c2 FROM v4 t1 LEFT JOIN v5 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c1, t2.c1 OFFSET 10 LIMIT 10; -- can be pushed down
+ QUERY PLAN
+ --------------------------------------------------------------------------------------------------------------------------------------------------------------------------
+ Limit
+ Output: ft4.c1, ft5.c2, ft5.c1
+ -> Foreign Scan
+ Output: ft4.c1, ft5.c2, ft5.c1
+ Relations: (public.ft4) LEFT JOIN (public.ft5)
+ Remote SQL: SELECT r6.c1, r9.c2, r9.c1 FROM ("S 1"."T 3" r6 LEFT JOIN "S 1"."T 4" r9 ON (((r6.c1 = r9.c1)))) ORDER BY r6.c1 ASC NULLS LAST, r9.c1 ASC NULLS LAST
+ (6 rows)
+
+ SELECT t1.c1, t2.c2 FROM v4 t1 LEFT JOIN v5 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c1, t2.c1 OFFSET 10 LIMIT 10;
+ c1 | c2
+ ----+----
+ 22 |
+ 24 | 25
+ 26 |
+ 28 |
+ 30 | 31
+ 32 |
+ 34 |
+ 36 | 37
+ 38 |
+ 40 |
+ (10 rows)
+
+ -- join between a view and a foreign table
+ EXPLAIN (COSTS false, VERBOSE)
+ SELECT t1.c1, t2.c2 FROM v4 t1 LEFT JOIN ft5 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c1, t2.c1 OFFSET 10 LIMIT 10; -- can't be pushed down
+ QUERY PLAN
+ ----------------------------------------------------------------------
+ Limit
+ Output: ft4.c1, t2.c2, t2.c1
+ -> Sort
+ Output: ft4.c1, t2.c2, t2.c1
+ Sort Key: ft4.c1, t2.c1
+ -> Hash Left Join
+ Output: ft4.c1, t2.c2, t2.c1
+ Hash Cond: (ft4.c1 = t2.c1)
+ -> Foreign Scan on public.ft4
+ Output: ft4.c1, ft4.c2, ft4.c3
+ Remote SQL: SELECT c1 FROM "S 1"."T 3"
+ -> Hash
+ Output: t2.c2, t2.c1
+ -> Foreign Scan on public.ft5 t2
+ Output: t2.c2, t2.c1
+ Remote SQL: SELECT c1, c2 FROM "S 1"."T 4"
+ (16 rows)
+
+ SELECT t1.c1, t2.c2 FROM v4 t1 LEFT JOIN ft5 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c1, t2.c1 OFFSET 10 LIMIT 10;
+ c1 | c2
+ ----+----
+ 22 |
+ 24 | 25
+ 26 |
+ 28 |
+ 30 | 31
+ 32 |
+ 34 |
+ 36 | 37
+ 38 |
+ 40 |
+ (10 rows)
+
+ ALTER VIEW v4 OWNER TO CURRENT_USER;
+ EXPLAIN (COSTS false, VERBOSE)
+ SELECT t1.c1, t2.c2 FROM v4 t1 LEFT JOIN ft5 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c1, t2.c1 OFFSET 10 LIMIT 10; -- can be pushed down
+ QUERY PLAN
+ ----------------------------------------------------------------------
+ Limit
+ Output: ft4.c1, t2.c2, t2.c1
+ -> Sort
+ Output: ft4.c1, t2.c2, t2.c1
+ Sort Key: ft4.c1, t2.c1
+ -> Hash Left Join
+ Output: ft4.c1, t2.c2, t2.c1
+ Hash Cond: (ft4.c1 = t2.c1)
+ -> Foreign Scan on public.ft4
+ Output: ft4.c1, ft4.c2, ft4.c3
+ Remote SQL: SELECT c1 FROM "S 1"."T 3"
+ -> Hash
+ Output: t2.c2, t2.c1
+ -> Foreign Scan on public.ft5 t2
+ Output: t2.c2, t2.c1
+ Remote SQL: SELECT c1, c2 FROM "S 1"."T 4"
+ (16 rows)
+
+ SELECT t1.c1, t2.c2 FROM v4 t1 LEFT JOIN ft5 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c1, t2.c1 OFFSET 10 LIMIT 10;
+ c1 | c2
+ ----+----
+ 22 |
+ 24 | 25
+ 26 |
+ 28 |
+ 30 | 31
+ 32 |
+ 34 |
+ 36 | 37
+ 38 |
+ 40 |
+ (10 rows)
+
+ ALTER VIEW v4 OWNER TO view_owner;
+ -- cleanup
+ DROP OWNED BY view_owner;
+ DROP USER view_owner;
+ DROP USER MAPPING FOR PUBLIC SERVER loopback;
+ CREATE USER MAPPING FOR CURRENT_USER SERVER loopback;
-- ===================================================================
-- parameterized queries
-- ===================================================================
***************
*** 5867,5872 **** AND ftoptions @> array['fetch_size=60000'];
(1 row)
ROLLBACK;
- -- Cleanup
- DROP OWNED BY view_owner;
- DROP USER view_owner;
--- 5903,5905 ----
*** a/contrib/postgres_fdw/postgres_fdw.c
--- b/contrib/postgres_fdw/postgres_fdw.c
***************
*** 67,74 **** enum FdwScanPrivateIndex
FdwScanPrivateRetrievedAttrs,
/* Integer representing the desired fetch_size */
FdwScanPrivateFetchSize,
- /* Oid of user mapping to be used while connecting to the foreign server */
- FdwScanPrivateUserMappingOid,
/*
* String describing join i.e. names of relations being joined and types
--- 67,72 ----
***************
*** 1226,1236 **** postgresGetForeignPlan(PlannerInfo *root,
* Build the fdw_private list that will be available to the executor.
* Items in the list must match order in enum FdwScanPrivateIndex.
*/
! fdw_private = list_make5(makeString(sql.data),
remote_conds,
retrieved_attrs,
! makeInteger(fpinfo->fetch_size),
! makeInteger(foreignrel->umid));
if (foreignrel->reloptkind == RELOPT_JOINREL)
fdw_private = lappend(fdw_private,
makeString(fpinfo->relation_name->data));
--- 1224,1233 ----
* Build the fdw_private list that will be available to the executor.
* Items in the list must match order in enum FdwScanPrivateIndex.
*/
! fdw_private = list_make4(makeString(sql.data),
remote_conds,
retrieved_attrs,
! makeInteger(fpinfo->fetch_size));
if (foreignrel->reloptkind == RELOPT_JOINREL)
fdw_private = lappend(fdw_private,
makeString(fpinfo->relation_name->data));
***************
*** 1262,1268 **** postgresBeginForeignScan(ForeignScanState *node, int eflags)
--- 1259,1269 ----
ForeignScan *fsplan = (ForeignScan *) node->ss.ps.plan;
EState *estate = node->ss.ps.state;
PgFdwScanState *fsstate;
+ RangeTblEntry *rte;
+ Oid userid;
+ ForeignTable *table;
UserMapping *user;
+ int rtindex;
int numParams;
/*
***************
*** 1278,1313 **** postgresBeginForeignScan(ForeignScanState *node, int eflags)
node->fdw_state = (void *) fsstate;
/*
! * Obtain the foreign server where to connect and user mapping to use for
! * connection. For base relations we obtain this information from
! * catalogs. For join relations, this information is frozen at the time of
! * planning to ensure that the join is safe to pushdown. In case the
! * information goes stale between planning and execution, plan will be
! * invalidated and replanned.
*/
if (fsplan->scan.scanrelid > 0)
! {
! ForeignTable *table;
!
! /*
! * Identify which user to do the remote access as. This should match
! * what ExecCheckRTEPerms() does.
! */
! RangeTblEntry *rte = rt_fetch(fsplan->scan.scanrelid, estate->es_range_table);
! Oid userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
!
! fsstate->rel = node->ss.ss_currentRelation;
! table = GetForeignTable(RelationGetRelid(fsstate->rel));
!
! user = GetUserMapping(userid, table->serverid);
! }
else
{
! Oid umid = intVal(list_nth(fsplan->fdw_private, FdwScanPrivateUserMappingOid));
!
! user = GetUserMappingById(umid);
! Assert(fsplan->fs_server == user->serverid);
}
/*
* Get connection to the foreign server. Connection manager will
--- 1279,1301 ----
node->fdw_state = (void *) fsstate;
/*
! * Identify which user to do the remote access as. This should match what
! * ExecCheckRTEPerms() does.
*/
if (fsplan->scan.scanrelid > 0)
! rtindex = fsplan->scan.scanrelid;
else
{
! /* Pick the lowest-numbered one as a representative. */
! rtindex = -1;
! rtindex = bms_next_member(fsplan->fs_relids, rtindex);
}
+ rte = rt_fetch(rtindex, estate->es_range_table);
+ userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
+
+ /* Get info about foreign table. */
+ table = GetForeignTable(rte->relid);
+ user = GetUserMapping(userid, table->serverid);
/*
* Get connection to the foreign server. Connection manager will
***************
*** 1344,1352 **** postgresBeginForeignScan(ForeignScanState *node, int eflags)
--- 1332,1346 ----
* into local representation and error reporting during that process.
*/
if (fsplan->scan.scanrelid > 0)
+ {
+ fsstate->rel = node->ss.ss_currentRelation;
fsstate->tupdesc = RelationGetDescr(fsstate->rel);
+ }
else
+ {
+ fsstate->rel = NULL;
fsstate->tupdesc = node->ss.ss_ScanTupleSlot->tts_tupleDescriptor;
+ }
fsstate->attinmeta = TupleDescGetAttInMetadata(fsstate->tupdesc);
***************
*** 3966,3981 **** foreign_join_ok(PlannerInfo *root, RelOptInfo *joinrel, JoinType jointype,
List *otherclauses;
/*
- * Core code may call GetForeignJoinPaths hook even when the join relation
- * doesn't have a valid user mapping associated with it. See
- * build_join_rel() for details. We can't push down such join, since there
- * doesn't exist a user mapping which can be used to connect to the
- * foreign server.
- */
- if (!OidIsValid(joinrel->umid))
- return false;
-
- /*
* We support pushing down INNER, LEFT, RIGHT and FULL OUTER joins.
* Constructing queries representing SEMI and ANTI joins is hard, hence
* not considered right now.
--- 3960,3965 ----
***************
*** 4151,4156 **** foreign_join_ok(PlannerInfo *root, RelOptInfo *joinrel, JoinType jointype,
--- 4135,4154 ----
fpinfo->use_remote_estimate = fpinfo_o->use_remote_estimate ||
fpinfo_i->use_remote_estimate;
+ /* Get user mapping */
+ if (fpinfo->use_remote_estimate)
+ {
+ if (fpinfo_o->use_remote_estimate)
+ fpinfo->user = fpinfo_o->user;
+ else
+ fpinfo->user = fpinfo_i->user;
+ }
+ else
+ fpinfo->user = NULL;
+
+ /* Get foreign server */
+ fpinfo->server = fpinfo_o->server;
+
/*
* Since both the joining relations come from the same server, the server
* level options should have same value for both the relations. Pick from
***************
*** 4312,4337 **** postgresGetForeignJoinPaths(PlannerInfo *root,
cost_qual_eval(&fpinfo->local_conds_cost, fpinfo->local_conds, root);
/*
! * If we are going to estimate the costs using EXPLAIN, we will need
! * connection information. Fill it here.
*/
! if (fpinfo->use_remote_estimate)
! fpinfo->user = GetUserMappingById(joinrel->umid);
! else
! {
! fpinfo->user = NULL;
!
! /*
! * If we are going to estimate costs locally, estimate the join clause
! * selectivity here while we have special join info.
! */
fpinfo->joinclause_sel = clauselist_selectivity(root, fpinfo->joinclauses,
0, fpinfo->jointype,
extra->sjinfo);
- }
- fpinfo->server = GetForeignServer(joinrel->serverid);
-
/* Estimate costs for bare join relation */
estimate_path_cost_size(root, joinrel, NIL, NIL, &rows,
&width, &startup_cost, &total_cost);
--- 4310,4323 ----
cost_qual_eval(&fpinfo->local_conds_cost, fpinfo->local_conds, root);
/*
! * If we are going to estimate costs locally, estimate the join clause
! * selectivity here while we have special join info.
*/
! if (!fpinfo->use_remote_estimate)
fpinfo->joinclause_sel = clauselist_selectivity(root, fpinfo->joinclauses,
0, fpinfo->jointype,
extra->sjinfo);
/* Estimate costs for bare join relation */
estimate_path_cost_size(root, joinrel, NIL, NIL, &rows,
&width, &startup_cost, &total_cost);
*** a/contrib/postgres_fdw/sql/postgres_fdw.sql
--- b/contrib/postgres_fdw/sql/postgres_fdw.sql
***************
*** 485,532 **** EXPLAIN (COSTS false, VERBOSE)
SELECT t1."C 1" FROM "S 1"."T 1" t1, LATERAL (SELECT DISTINCT t2.c1, t3.c1 FROM ft1 t2, ft2 t3 WHERE t2.c1 = t3.c1 AND t2.c2 = t1.c2) q ORDER BY t1."C 1" OFFSET 10 LIMIT 10;
SELECT t1."C 1" FROM "S 1"."T 1" t1, LATERAL (SELECT DISTINCT t2.c1, t3.c1 FROM ft1 t2, ft2 t3 WHERE t2.c1 = t3.c1 AND t2.c2 = t1.c2) q ORDER BY t1."C 1" OFFSET 10 LIMIT 10;
- -- create another user for permission, user mapping, effective user tests
- CREATE USER view_owner;
- -- grant privileges on ft4 and ft5 to view_owner
- GRANT ALL ON ft4 TO view_owner;
- GRANT ALL ON ft5 TO view_owner;
- -- prepare statement with current session user
- PREPARE join_stmt AS SELECT t1.c1, t2.c1 FROM ft4 t1 LEFT JOIN ft5 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c1, t2.c1 OFFSET 10 LIMIT 10;
- EXPLAIN (COSTS OFF, VERBOSE) EXECUTE join_stmt;
- EXECUTE join_stmt;
- -- change the session user to view_owner and execute the statement. Because of
- -- change in session user, the plan should get invalidated and created again.
- -- The join will not be pushed down since the joining relations do not have a
- -- valid user mapping.
- SET SESSION ROLE view_owner;
- EXPLAIN (COSTS OFF, VERBOSE) EXECUTE join_stmt;
- RESET ROLE;
- DEALLOCATE join_stmt;
-
- CREATE VIEW v_ft5 AS SELECT * FROM ft5;
- -- change owner of v_ft5 to view_owner so that the effective user for scan on
- -- ft5 is view_owner and not the current user.
- ALTER VIEW v_ft5 OWNER TO view_owner;
- -- create a public user mapping for loopback server
- -- drop user mapping for current_user.
- DROP USER MAPPING FOR CURRENT_USER SERVER loopback;
- CREATE USER MAPPING FOR PUBLIC SERVER loopback;
- -- different effective user for permission check, but same user mapping for the
- -- joining sides, join pushed down, no result expected.
- PREPARE join_stmt AS SELECT t1.c1, t2.c1 FROM ft5 t1 JOIN v_ft5 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c1, t2.c1 OFFSET 100 LIMIT 10;
- EXPLAIN (COSTS false, VERBOSE) EXECUTE join_stmt;
- EXECUTE join_stmt;
- -- create user mapping for view_owner and execute the prepared statement
- -- the join should not be pushed down since joining relations now use two
- -- different user mappings
- CREATE USER MAPPING FOR view_owner SERVER loopback;
- EXPLAIN (COSTS false, VERBOSE) EXECUTE join_stmt;
- EXECUTE join_stmt;
-
- -- If a sub-join can't be pushed down, upper level join shouldn't be either.
- EXPLAIN (COSTS false, VERBOSE)
- SELECT t1.c1, t2.c1 FROM (ft5 t1 JOIN v_ft5 t2 ON (t1.c1 = t2.c1)) left join (ft5 t3 JOIN v_ft5 t4 ON (t3.c1 = t4.c1)) ON (t1.c1 = t3.c1);
-
-- non-Var items in targelist of the nullable rel of a join preventing
-- push-down in some cases
-- unable to push {ft1, ft2}
--- 485,490 ----
***************
*** 539,553 **** EXPLAIN (COSTS false, VERBOSE)
SELECT ft4.c1, q.* FROM ft4 LEFT JOIN (SELECT 13, ft1.c1, ft2.c1 FROM ft1 RIGHT JOIN ft2 ON (ft1.c1 = ft2.c1) WHERE ft1.c1 = 12) q(a, b, c) ON (ft4.c1 = q.b) WHERE ft4.c1 BETWEEN 10 AND 15;
SELECT ft4.c1, q.* FROM ft4 LEFT JOIN (SELECT 13, ft1.c1, ft2.c1 FROM ft1 RIGHT JOIN ft2 ON (ft1.c1 = ft2.c1) WHERE ft1.c1 = 12) q(a, b, c) ON (ft4.c1 = q.b) WHERE ft4.c1 BETWEEN 10 AND 15;
- -- recreate the dropped user mapping for further tests
- CREATE USER MAPPING FOR CURRENT_USER SERVER loopback;
- DROP USER MAPPING FOR PUBLIC SERVER loopback;
-
-- join with nullable side with some columns with null values
UPDATE ft5 SET c3 = null where c1 % 9 = 0;
EXPLAIN VERBOSE SELECT ft5, ft5.c1, ft5.c2, ft5.c3, ft4.c1, ft4.c2 FROM ft5 left join ft4 on ft5.c1 = ft4.c1 WHERE ft4.c1 BETWEEN 10 and 30 ORDER BY ft5.c1, ft4.c1;
SELECT ft5, ft5.c1, ft5.c2, ft5.c3, ft4.c1, ft4.c2 FROM ft5 left join ft4 on ft5.c1 = ft4.c1 WHERE ft4.c1 BETWEEN 10 and 30 ORDER BY ft5.c1, ft4.c1;
-- ===================================================================
-- parameterized queries
-- ===================================================================
--- 497,547 ----
SELECT ft4.c1, q.* FROM ft4 LEFT JOIN (SELECT 13, ft1.c1, ft2.c1 FROM ft1 RIGHT JOIN ft2 ON (ft1.c1 = ft2.c1) WHERE ft1.c1 = 12) q(a, b, c) ON (ft4.c1 = q.b) WHERE ft4.c1 BETWEEN 10 AND 15;
SELECT ft4.c1, q.* FROM ft4 LEFT JOIN (SELECT 13, ft1.c1, ft2.c1 FROM ft1 RIGHT JOIN ft2 ON (ft1.c1 = ft2.c1) WHERE ft1.c1 = 12) q(a, b, c) ON (ft4.c1 = q.b) WHERE ft4.c1 BETWEEN 10 AND 15;
-- join with nullable side with some columns with null values
UPDATE ft5 SET c3 = null where c1 % 9 = 0;
EXPLAIN VERBOSE SELECT ft5, ft5.c1, ft5.c2, ft5.c3, ft4.c1, ft4.c2 FROM ft5 left join ft4 on ft5.c1 = ft4.c1 WHERE ft4.c1 BETWEEN 10 and 30 ORDER BY ft5.c1, ft4.c1;
SELECT ft5, ft5.c1, ft5.c2, ft5.c3, ft4.c1, ft4.c2 FROM ft5 left join ft4 on ft5.c1 = ft4.c1 WHERE ft4.c1 BETWEEN 10 and 30 ORDER BY ft5.c1, ft4.c1;
+ -- join encapsulated in a view
+ DROP USER MAPPING FOR CURRENT_USER SERVER loopback;
+ CREATE USER MAPPING FOR PUBLIC SERVER loopback;
+ CREATE USER view_owner;
+ GRANT SELECT ON ft4 TO view_owner;
+ GRANT SELECT ON ft5 TO view_owner;
+ CREATE VIEW join_view AS SELECT t1.c1, t2.c2 FROM ft4 t1 LEFT JOIN ft5 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c1, t2.c1 OFFSET 10 LIMIT 10;
+ ALTER VIEW join_view OWNER TO view_owner;
+ EXPLAIN (COSTS false, VERBOSE)
+ SELECT * FROM join_view; -- can be pushed down
+ SELECT * FROM join_view;
+
+ -- join between two views
+ CREATE VIEW v4 AS SELECT * FROM ft4;
+ CREATE VIEW v5 AS SELECT * FROM ft5;
+ ALTER VIEW v5 OWNER TO view_owner;
+ EXPLAIN (COSTS false, VERBOSE)
+ SELECT t1.c1, t2.c2 FROM v4 t1 LEFT JOIN v5 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c1, t2.c1 OFFSET 10 LIMIT 10; -- can't be pushed down
+ SELECT t1.c1, t2.c2 FROM v4 t1 LEFT JOIN v5 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c1, t2.c1 OFFSET 10 LIMIT 10;
+ ALTER VIEW v4 OWNER TO view_owner;
+ EXPLAIN (COSTS false, VERBOSE)
+ SELECT t1.c1, t2.c2 FROM v4 t1 LEFT JOIN v5 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c1, t2.c1 OFFSET 10 LIMIT 10; -- can be pushed down
+ SELECT t1.c1, t2.c2 FROM v4 t1 LEFT JOIN v5 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c1, t2.c1 OFFSET 10 LIMIT 10;
+
+ -- join between a view and a foreign table
+ EXPLAIN (COSTS false, VERBOSE)
+ SELECT t1.c1, t2.c2 FROM v4 t1 LEFT JOIN ft5 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c1, t2.c1 OFFSET 10 LIMIT 10; -- can't be pushed down
+ SELECT t1.c1, t2.c2 FROM v4 t1 LEFT JOIN ft5 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c1, t2.c1 OFFSET 10 LIMIT 10;
+ ALTER VIEW v4 OWNER TO CURRENT_USER;
+ EXPLAIN (COSTS false, VERBOSE)
+ SELECT t1.c1, t2.c2 FROM v4 t1 LEFT JOIN ft5 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c1, t2.c1 OFFSET 10 LIMIT 10; -- can be pushed down
+ SELECT t1.c1, t2.c2 FROM v4 t1 LEFT JOIN ft5 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c1, t2.c1 OFFSET 10 LIMIT 10;
+ ALTER VIEW v4 OWNER TO view_owner;
+
+ -- cleanup
+ DROP OWNED BY view_owner;
+ DROP USER view_owner;
+ DROP USER MAPPING FOR PUBLIC SERVER loopback;
+ CREATE USER MAPPING FOR CURRENT_USER SERVER loopback;
+
-- ===================================================================
-- parameterized queries
-- ===================================================================
***************
*** 1360,1366 **** WHERE ftrelid = 'table30000'::regclass
AND ftoptions @> array['fetch_size=60000'];
ROLLBACK;
-
- -- Cleanup
- DROP OWNED BY view_owner;
- DROP USER view_owner;
--- 1354,1356 ----
*** a/src/backend/executor/execParallel.c
--- b/src/backend/executor/execParallel.c
***************
*** 160,166 **** ExecSerializePlan(Plan *plan, EState *estate)
pstmt->relationOids = NIL;
pstmt->invalItems = NIL; /* workers can't replan anyway... */
pstmt->hasRowSecurity = false;
- pstmt->hasForeignJoin = false;
/* Return serialized copy of our dummy PlannedStmt. */
return nodeToString(pstmt);
--- 160,165 ----
*** a/src/backend/foreign/foreign.c
--- b/src/backend/foreign/foreign.c
***************
*** 31,37 ****
extern Datum pg_options_to_table(PG_FUNCTION_ARGS);
extern Datum postgresql_fdw_validator(PG_FUNCTION_ARGS);
! static HeapTuple find_user_mapping(Oid userid, Oid serverid, bool missing_ok);
/*
* GetForeignDataWrapper - look up the foreign-data wrapper by OID.
--- 31,37 ----
extern Datum pg_options_to_table(PG_FUNCTION_ARGS);
extern Datum postgresql_fdw_validator(PG_FUNCTION_ARGS);
! static HeapTuple find_user_mapping(Oid userid, Oid serverid);
/*
* GetForeignDataWrapper - look up the foreign-data wrapper by OID.
***************
*** 223,229 **** GetUserMapping(Oid userid, Oid serverid)
bool isnull;
UserMapping *um;
! tp = find_user_mapping(userid, serverid, false);
um = (UserMapping *) palloc(sizeof(UserMapping));
um->umid = HeapTupleGetOid(tp);
--- 223,229 ----
bool isnull;
UserMapping *um;
! tp = find_user_mapping(userid, serverid);
um = (UserMapping *) palloc(sizeof(UserMapping));
um->umid = HeapTupleGetOid(tp);
***************
*** 250,272 **** GetUserMapping(Oid userid, Oid serverid)
*
* If no mapping is found for the supplied user, we also look for
* PUBLIC mappings (userid == InvalidOid).
- *
- * If missing_ok is true, the function returns InvalidOid when it does not find
- * required user mapping. Otherwise, find_user_mapping() throws error if it
- * does not find required user mapping.
*/
Oid
! GetUserMappingId(Oid userid, Oid serverid, bool missing_ok)
{
HeapTuple tp;
Oid umid;
! tp = find_user_mapping(userid, serverid, missing_ok);
!
! Assert(missing_ok || tp);
!
! if (!tp && missing_ok)
! return InvalidOid;
/* Extract the Oid */
umid = HeapTupleGetOid(tp);
--- 250,263 ----
*
* If no mapping is found for the supplied user, we also look for
* PUBLIC mappings (userid == InvalidOid).
*/
Oid
! GetUserMappingId(Oid userid, Oid serverid)
{
HeapTuple tp;
Oid umid;
! tp = find_user_mapping(userid, serverid);
/* Extract the Oid */
umid = HeapTupleGetOid(tp);
***************
*** 282,294 **** GetUserMappingId(Oid userid, Oid serverid, bool missing_ok)
*
* If no mapping is found for the supplied user, we also look for
* PUBLIC mappings (userid == InvalidOid).
- *
- * If missing_ok is true, the function returns NULL, if it does not find
- * the required user mapping. Otherwise, it throws error if it does not
- * find the required user mapping.
*/
static HeapTuple
! find_user_mapping(Oid userid, Oid serverid, bool missing_ok)
{
HeapTuple tp;
--- 273,281 ----
*
* If no mapping is found for the supplied user, we also look for
* PUBLIC mappings (userid == InvalidOid).
*/
static HeapTuple
! find_user_mapping(Oid userid, Oid serverid)
{
HeapTuple tp;
***************
*** 305,319 **** find_user_mapping(Oid userid, Oid serverid, bool missing_ok)
ObjectIdGetDatum(serverid));
if (!HeapTupleIsValid(tp))
! {
! if (missing_ok)
! return NULL;
! else
! ereport(ERROR,
! (errcode(ERRCODE_UNDEFINED_OBJECT),
! errmsg("user mapping not found for \"%s\"",
! MappingUserName(userid))));
! }
return tp;
}
--- 292,301 ----
ObjectIdGetDatum(serverid));
if (!HeapTupleIsValid(tp))
! ereport(ERROR,
! (errcode(ERRCODE_UNDEFINED_OBJECT),
! errmsg("user mapping not found for \"%s\"",
! MappingUserName(userid))));
return tp;
}
*** a/src/backend/nodes/copyfuncs.c
--- b/src/backend/nodes/copyfuncs.c
***************
*** 97,103 **** _copyPlannedStmt(const PlannedStmt *from)
COPY_SCALAR_FIELD(nParamExec);
COPY_SCALAR_FIELD(hasRowSecurity);
COPY_SCALAR_FIELD(parallelModeNeeded);
- COPY_SCALAR_FIELD(hasForeignJoin);
return newnode;
}
--- 97,102 ----
*** a/src/backend/nodes/outfuncs.c
--- b/src/backend/nodes/outfuncs.c
***************
*** 273,279 **** _outPlannedStmt(StringInfo str, const PlannedStmt *node)
WRITE_INT_FIELD(nParamExec);
WRITE_BOOL_FIELD(hasRowSecurity);
WRITE_BOOL_FIELD(parallelModeNeeded);
- WRITE_BOOL_FIELD(hasForeignJoin);
}
/*
--- 273,278 ----
***************
*** 2018,2024 **** _outPlannerGlobal(StringInfo str, const PlannerGlobal *node)
WRITE_BOOL_FIELD(hasRowSecurity);
WRITE_BOOL_FIELD(parallelModeOK);
WRITE_BOOL_FIELD(parallelModeNeeded);
- WRITE_BOOL_FIELD(hasForeignJoin);
}
static void
--- 2017,2022 ----
*** a/src/backend/nodes/readfuncs.c
--- b/src/backend/nodes/readfuncs.c
***************
*** 1402,1408 **** _readPlannedStmt(void)
READ_INT_FIELD(nParamExec);
READ_BOOL_FIELD(hasRowSecurity);
READ_BOOL_FIELD(parallelModeNeeded);
- READ_BOOL_FIELD(hasForeignJoin);
READ_DONE();
}
--- 1402,1407 ----
*** a/src/backend/optimizer/path/joinpath.c
--- b/src/backend/optimizer/path/joinpath.c
***************
*** 213,220 **** add_paths_to_joinrel(PlannerInfo *root,
/*
* 5. If inner and outer relations are foreign tables (or joins) belonging
! * to the same server and using the same user mapping, give the FDW a
! * chance to push down joins.
*/
if (joinrel->fdwroutine &&
joinrel->fdwroutine->GetForeignJoinPaths)
--- 213,220 ----
/*
* 5. If inner and outer relations are foreign tables (or joins) belonging
! * to the same server and assigned to the same user to check access
! * permissions as, give the FDW a chance to push down joins.
*/
if (joinrel->fdwroutine &&
joinrel->fdwroutine->GetForeignJoinPaths)
*** a/src/backend/optimizer/plan/createplan.c
--- b/src/backend/optimizer/plan/createplan.c
***************
*** 3247,3261 **** create_foreignscan_plan(PlannerInfo *root, ForeignPath *best_path,
scan_plan->fs_relids = best_path->path.parent->relids;
/*
- * If a join between foreign relations was pushed down, remember it. The
- * push-down safety of the join depends upon the server and user mapping
- * being same. That can change between planning and execution time, in
- * which case the plan should be invalidated.
- */
- if (scan_relid == 0)
- root->glob->hasForeignJoin = true;
-
- /*
* Replace any outer-relation variables with nestloop params in the qual,
* fdw_exprs and fdw_recheck_quals expressions. We do this last so that
* the FDW doesn't have to be involved. (Note that parts of fdw_exprs or
--- 3247,3252 ----
*** a/src/backend/optimizer/plan/planner.c
--- b/src/backend/optimizer/plan/planner.c
***************
*** 220,226 **** standard_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
glob->lastPlanNodeId = 0;
glob->transientPlan = false;
glob->hasRowSecurity = false;
- glob->hasForeignJoin = false;
/*
* Assess whether it's feasible to use parallel mode for this query. We
--- 220,225 ----
***************
*** 417,423 **** standard_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
result->nParamExec = glob->nParamExec;
result->hasRowSecurity = glob->hasRowSecurity;
result->parallelModeNeeded = glob->parallelModeNeeded;
- result->hasForeignJoin = glob->hasForeignJoin;
return result;
}
--- 416,421 ----
***************
*** 1960,1966 **** grouping_planner(PlannerInfo *root, bool inheritance_update,
* If the current_rel belongs to a single FDW, so does the final_rel.
*/
final_rel->serverid = current_rel->serverid;
! final_rel->umid = current_rel->umid;
final_rel->fdwroutine = current_rel->fdwroutine;
/*
--- 1958,1964 ----
* If the current_rel belongs to a single FDW, so does the final_rel.
*/
final_rel->serverid = current_rel->serverid;
! final_rel->userid = current_rel->userid;
final_rel->fdwroutine = current_rel->fdwroutine;
/*
***************
*** 3337,3343 **** create_grouping_paths(PlannerInfo *root,
* If the input rel belongs to a single FDW, so does the grouped rel.
*/
grouped_rel->serverid = input_rel->serverid;
! grouped_rel->umid = input_rel->umid;
grouped_rel->fdwroutine = input_rel->fdwroutine;
/*
--- 3335,3341 ----
* If the input rel belongs to a single FDW, so does the grouped rel.
*/
grouped_rel->serverid = input_rel->serverid;
! grouped_rel->userid = input_rel->userid;
grouped_rel->fdwroutine = input_rel->fdwroutine;
/*
***************
*** 3891,3897 **** create_window_paths(PlannerInfo *root,
* If the input rel belongs to a single FDW, so does the window rel.
*/
window_rel->serverid = input_rel->serverid;
! window_rel->umid = input_rel->umid;
window_rel->fdwroutine = input_rel->fdwroutine;
/*
--- 3889,3895 ----
* If the input rel belongs to a single FDW, so does the window rel.
*/
window_rel->serverid = input_rel->serverid;
! window_rel->userid = input_rel->userid;
window_rel->fdwroutine = input_rel->fdwroutine;
/*
***************
*** 4071,4077 **** create_distinct_paths(PlannerInfo *root,
* If the input rel belongs to a single FDW, so does the distinct_rel.
*/
distinct_rel->serverid = input_rel->serverid;
! distinct_rel->umid = input_rel->umid;
distinct_rel->fdwroutine = input_rel->fdwroutine;
/* Estimate number of distinct rows there will be */
--- 4069,4075 ----
* If the input rel belongs to a single FDW, so does the distinct_rel.
*/
distinct_rel->serverid = input_rel->serverid;
! distinct_rel->userid = input_rel->userid;
distinct_rel->fdwroutine = input_rel->fdwroutine;
/* Estimate number of distinct rows there will be */
***************
*** 4279,4285 **** create_ordered_paths(PlannerInfo *root,
* If the input rel belongs to a single FDW, so does the ordered_rel.
*/
ordered_rel->serverid = input_rel->serverid;
! ordered_rel->umid = input_rel->umid;
ordered_rel->fdwroutine = input_rel->fdwroutine;
foreach(lc, input_rel->pathlist)
--- 4277,4283 ----
* If the input rel belongs to a single FDW, so does the ordered_rel.
*/
ordered_rel->serverid = input_rel->serverid;
! ordered_rel->userid = input_rel->userid;
ordered_rel->fdwroutine = input_rel->fdwroutine;
foreach(lc, input_rel->pathlist)
*** a/src/backend/optimizer/util/relnode.c
--- b/src/backend/optimizer/util/relnode.c
***************
*** 14,22 ****
*/
#include "postgres.h"
- #include "miscadmin.h"
- #include "catalog/pg_class.h"
- #include "foreign/foreign.h"
#include "optimizer/clauses.h"
#include "optimizer/cost.h"
#include "optimizer/pathnode.h"
--- 14,19 ----
***************
*** 130,136 **** build_simple_rel(PlannerInfo *root, int relid, RelOptKind reloptkind)
rel->subroot = NULL;
rel->subplan_params = NIL;
rel->serverid = InvalidOid;
! rel->umid = InvalidOid;
rel->fdwroutine = NULL;
rel->fdw_private = NULL;
rel->baserestrictinfo = NIL;
--- 127,133 ----
rel->subroot = NULL;
rel->subplan_params = NIL;
rel->serverid = InvalidOid;
! rel->userid = rte->checkAsUser;
rel->fdwroutine = NULL;
rel->fdw_private = NULL;
rel->baserestrictinfo = NIL;
***************
*** 170,199 **** build_simple_rel(PlannerInfo *root, int relid, RelOptKind reloptkind)
break;
}
- /* For foreign tables get the user mapping */
- if (rte->relkind == RELKIND_FOREIGN_TABLE)
- {
- /*
- * This should match what ExecCheckRTEPerms() does.
- *
- * Note that if the plan ends up depending on the user OID in any way
- * - e.g. if it depends on the computed user mapping OID - we must
- * ensure that it gets invalidated in the case of a user OID change.
- * See RevalidateCachedQuery and more generally the hasForeignJoin
- * flags in PlannerGlobal and PlannedStmt.
- *
- * It's possible, and not necessarily an error, for rel->umid to be
- * InvalidOid even though rel->serverid is set. That just means there
- * is a server with no user mapping.
- */
- Oid userid;
-
- userid = OidIsValid(rte->checkAsUser) ? rte->checkAsUser : GetUserId();
- rel->umid = GetUserMappingId(userid, rel->serverid, true);
- }
- else
- rel->umid = InvalidOid;
-
/* Save the finished struct in the query's simple_rel_array */
root->simple_rel_array[relid] = rel;
--- 167,172 ----
***************
*** 424,430 **** build_join_rel(PlannerInfo *root,
joinrel->subroot = NULL;
joinrel->subplan_params = NIL;
joinrel->serverid = InvalidOid;
! joinrel->umid = InvalidOid;
joinrel->fdwroutine = NULL;
joinrel->fdw_private = NULL;
joinrel->baserestrictinfo = NIL;
--- 397,403 ----
joinrel->subroot = NULL;
joinrel->subplan_params = NIL;
joinrel->serverid = InvalidOid;
! joinrel->userid = InvalidOid;
joinrel->fdwroutine = NULL;
joinrel->fdw_private = NULL;
joinrel->baserestrictinfo = NIL;
***************
*** 435,457 **** build_join_rel(PlannerInfo *root,
/*
* Set up foreign-join fields if outer and inner relation are foreign
! * tables (or joins) belonging to the same server and using the same user
! * mapping.
*
* Otherwise those fields are left invalid, so FDW API will not be called
* for the join relation.
- *
- * For FDWs like file_fdw, which ignore user mapping, the user mapping id
- * associated with the joining relation may be invalid. A valid serverid
- * distinguishes between a pushed down join with no user mapping and a
- * join which can not be pushed down because of user mapping mismatch.
*/
if (OidIsValid(outer_rel->serverid) &&
inner_rel->serverid == outer_rel->serverid &&
! inner_rel->umid == outer_rel->umid)
{
joinrel->serverid = outer_rel->serverid;
! joinrel->umid = outer_rel->umid;
joinrel->fdwroutine = outer_rel->fdwroutine;
}
--- 408,425 ----
/*
* Set up foreign-join fields if outer and inner relation are foreign
! * tables (or joins) belonging to the same server and assigned to the same
! * user to check access permissions as.
*
* Otherwise those fields are left invalid, so FDW API will not be called
* for the join relation.
*/
if (OidIsValid(outer_rel->serverid) &&
inner_rel->serverid == outer_rel->serverid &&
! inner_rel->userid == outer_rel->userid)
{
joinrel->serverid = outer_rel->serverid;
! joinrel->userid = outer_rel->userid;
joinrel->fdwroutine = outer_rel->fdwroutine;
}
*** a/src/backend/utils/cache/plancache.c
--- b/src/backend/utils/cache/plancache.c
***************
*** 105,112 **** static TupleDesc PlanCacheComputeResultDesc(List *stmt_list);
static void PlanCacheRelCallback(Datum arg, Oid relid);
static void PlanCacheFuncCallback(Datum arg, int cacheid, uint32 hashvalue);
static void PlanCacheSysCallback(Datum arg, int cacheid, uint32 hashvalue);
! static void PlanCacheUserMappingCallback(Datum arg, int cacheid,
! uint32 hashvalue);
/*
--- 105,111 ----
static void PlanCacheRelCallback(Datum arg, Oid relid);
static void PlanCacheFuncCallback(Datum arg, int cacheid, uint32 hashvalue);
static void PlanCacheSysCallback(Datum arg, int cacheid, uint32 hashvalue);
!
/*
***************
*** 122,129 **** InitPlanCache(void)
CacheRegisterSyscacheCallback(NAMESPACEOID, PlanCacheSysCallback, (Datum) 0);
CacheRegisterSyscacheCallback(OPEROID, PlanCacheSysCallback, (Datum) 0);
CacheRegisterSyscacheCallback(AMOPOPID, PlanCacheSysCallback, (Datum) 0);
- /* User mapping change may invalidate plans with pushed down foreign join */
- CacheRegisterSyscacheCallback(USERMAPPINGOID, PlanCacheUserMappingCallback, (Datum) 0);
}
/*
--- 121,126 ----
***************
*** 610,628 **** RevalidateCachedQuery(CachedPlanSource *plansource)
plansource->is_valid = false;
/*
- * If we have a join pushed down to the foreign server and the current
- * user is different from the one for which the plan was created,
- * invalidate the generic plan since user mapping for the new user might
- * make the join unsafe to push down, or change which user mapping is
- * used.
- */
- if (plansource->is_valid &&
- plansource->gplan &&
- plansource->gplan->has_foreign_join &&
- plansource->planUserId != GetUserId())
- plansource->gplan->is_valid = false;
-
- /*
* If the query is currently valid, acquire locks on the referenced
* objects; then check again. We need to do it this way to cover the race
* condition that an invalidation message arrives before we get the locks.
--- 607,612 ----
***************
*** 902,908 **** BuildCachedPlan(CachedPlanSource *plansource, List *qlist,
bool spi_pushed;
MemoryContext plan_context;
MemoryContext oldcxt = CurrentMemoryContext;
- ListCell *lc;
/*
* Normally the querytree should be valid already, but if it's not,
--- 886,891 ----
***************
*** 1010,1029 **** BuildCachedPlan(CachedPlanSource *plansource, List *qlist,
plan->is_saved = false;
plan->is_valid = true;
- /*
- * Walk through the plist and set hasForeignJoin if any of the plans have
- * it set.
- */
- plan->has_foreign_join = false;
- foreach(lc, plist)
- {
- PlannedStmt *plan_stmt = (PlannedStmt *) lfirst(lc);
-
- if (IsA(plan_stmt, PlannedStmt))
- plan->has_foreign_join =
- plan->has_foreign_join || plan_stmt->hasForeignJoin;
- }
-
/* assign generation number to new plan */
plan->generation = ++(plansource->generation);
--- 993,998 ----
***************
*** 1888,1927 **** PlanCacheSysCallback(Datum arg, int cacheid, uint32 hashvalue)
}
/*
- * PlanCacheUserMappingCallback
- * Syscache inval callback function for user mapping cache invalidation.
- *
- * Invalidates plans which have pushed down foreign joins.
- */
- static void
- PlanCacheUserMappingCallback(Datum arg, int cacheid, uint32 hashvalue)
- {
- CachedPlanSource *plansource;
-
- for (plansource = first_saved_plan; plansource; plansource = plansource->next_saved)
- {
- Assert(plansource->magic == CACHEDPLANSOURCE_MAGIC);
-
- /* No work if it's already invalidated */
- if (!plansource->is_valid)
- continue;
-
- /* Never invalidate transaction control commands */
- if (IsTransactionStmtPlan(plansource))
- continue;
-
- /*
- * If the plan has pushed down foreign joins, those join may become
- * unsafe to push down because of user mapping changes. Invalidate
- * only the generic plan, since changes to user mapping do not
- * invalidate the parse tree.
- */
- if (plansource->gplan && plansource->gplan->has_foreign_join)
- plansource->gplan->is_valid = false;
- }
- }
-
- /*
* ResetPlanCache: invalidate all cached plans.
*/
void
--- 1857,1862 ----
*** a/src/include/foreign/foreign.h
--- b/src/include/foreign/foreign.h
***************
*** 72,78 **** typedef struct ForeignTable
extern ForeignServer *GetForeignServer(Oid serverid);
extern ForeignServer *GetForeignServerByName(const char *name, bool missing_ok);
extern UserMapping *GetUserMapping(Oid userid, Oid serverid);
! extern Oid GetUserMappingId(Oid userid, Oid serverid, bool missing_ok);
extern UserMapping *GetUserMappingById(Oid umid);
extern ForeignDataWrapper *GetForeignDataWrapper(Oid fdwid);
extern ForeignDataWrapper *GetForeignDataWrapperByName(const char *name,
--- 72,78 ----
extern ForeignServer *GetForeignServer(Oid serverid);
extern ForeignServer *GetForeignServerByName(const char *name, bool missing_ok);
extern UserMapping *GetUserMapping(Oid userid, Oid serverid);
! extern Oid GetUserMappingId(Oid userid, Oid serverid);
extern UserMapping *GetUserMappingById(Oid umid);
extern ForeignDataWrapper *GetForeignDataWrapper(Oid fdwid);
extern ForeignDataWrapper *GetForeignDataWrapperByName(const char *name,
*** a/src/include/nodes/plannodes.h
--- b/src/include/nodes/plannodes.h
***************
*** 73,79 **** typedef struct PlannedStmt
bool hasRowSecurity; /* row security applied? */
bool parallelModeNeeded; /* parallel mode required to execute? */
- bool hasForeignJoin; /* Plan has a pushed down foreign join */
} PlannedStmt;
/* macro for fetching the Plan associated with a SubPlan node */
--- 73,78 ----
*** a/src/include/nodes/relation.h
--- b/src/include/nodes/relation.h
***************
*** 126,133 **** typedef struct PlannerGlobal
bool parallelModeOK; /* parallel mode potentially OK? */
bool parallelModeNeeded; /* parallel mode actually required? */
-
- bool hasForeignJoin; /* does have a pushed down foreign join */
} PlannerGlobal;
/* macro for fetching the Plan associated with a SubPlan node */
--- 126,131 ----
***************
*** 426,436 **** typedef struct PlannerInfo
* in just as for a baserel, except we don't bother with lateral_vars.
*
* If the relation is either a foreign table or a join of foreign tables that
! * all belong to the same foreign server and use the same user mapping, these
! * fields will be set:
*
* serverid - OID of foreign server, if foreign table (else InvalidOid)
! * umid - OID of user mapping, if foreign table (else InvalidOid)
* fdwroutine - function hooks for FDW, if foreign table (else NULL)
* fdw_private - private state for FDW, if foreign table (else NULL)
*
--- 424,434 ----
* in just as for a baserel, except we don't bother with lateral_vars.
*
* If the relation is either a foreign table or a join of foreign tables that
! * all belong to the same foreign server and are assigned to the same user to
! * check access permissions as (ie, checkAsUser), these fields will be set:
*
* serverid - OID of foreign server, if foreign table (else InvalidOid)
! * userid - OID of user to check access as
* fdwroutine - function hooks for FDW, if foreign table (else NULL)
* fdw_private - private state for FDW, if foreign table (else NULL)
*
***************
*** 528,535 **** typedef struct RelOptInfo
/* Information about foreign tables and foreign joins */
Oid serverid; /* identifies server for the table or join */
! Oid umid; /* identifies user mapping for the table or
! * join */
/* use "struct FdwRoutine" to avoid including fdwapi.h here */
struct FdwRoutine *fdwroutine;
void *fdw_private;
--- 526,532 ----
/* Information about foreign tables and foreign joins */
Oid serverid; /* identifies server for the table or join */
! Oid userid; /* identifies user to check access as */
/* use "struct FdwRoutine" to avoid including fdwapi.h here */
struct FdwRoutine *fdwroutine;
void *fdw_private;
*** a/src/include/utils/plancache.h
--- b/src/include/utils/plancache.h
***************
*** 135,141 **** typedef struct CachedPlan
* changes from this value */
int generation; /* parent's generation number for this plan */
int refcount; /* count of live references to this struct */
- bool has_foreign_join; /* plan has pushed down a foreign join */
MemoryContext context; /* context containing this CachedPlan */
} CachedPlan;
--- 135,140 ----
^ permalink raw reply [nested|flat] 19+ messages in thread
* Re: Oddity in handling of cached plans for FDW queries
2016-07-12 12:40 Oddity in handling of cached plans for FDW queries Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>
2016-07-13 09:00 ` Re: Oddity in handling of cached plans for FDW queries Ashutosh Bapat <ashutosh.bapat@enterprisedb.com>
2016-07-14 11:40 ` Re: Oddity in handling of cached plans for FDW queries Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>
2016-07-14 12:26 ` Re: Oddity in handling of cached plans for FDW queries Ashutosh Bapat <ashutosh.bapat@enterprisedb.com>
2016-07-14 16:32 ` Re: Oddity in handling of cached plans for FDW queries Tom Lane <tgl@sss.pgh.pa.us>
2016-07-14 18:49 ` Re: Oddity in handling of cached plans for FDW queries Tom Lane <tgl@sss.pgh.pa.us>
2016-07-15 02:37 ` Re: Oddity in handling of cached plans for FDW queries Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>
2016-07-15 02:48 ` Re: Oddity in handling of cached plans for FDW queries Tom Lane <tgl@sss.pgh.pa.us>
2016-07-15 12:55 ` Re: Oddity in handling of cached plans for FDW queries Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>
@ 2016-07-15 13:35 ` Tom Lane <tgl@sss.pgh.pa.us>
2016-07-15 21:25 ` Re: Oddity in handling of cached plans for FDW queries Tom Lane <tgl@sss.pgh.pa.us>
0 siblings, 1 reply; 19+ messages in thread
From: Tom Lane @ 2016-07-15 13:35 UTC (permalink / raw)
To: Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>; +Cc: Ashutosh Bapat <ashutosh.bapat@enterprisedb.com>; pgsql-hackers
Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp> writes:
> On 2016/07/15 11:48, Tom Lane wrote:
>> If we add a mechanism to let us know that the FDW doesn't care, we could
>> relax the requirement for such cases. I don't have a strong opinion on
>> whether that's worthwhile. It'd depend in part on how many FDWs there
>> are that don't care, versus those that do; and I have no idea about that.
> So, I'd vote for leaving that for future work if necessary.
Makes sense to me.
> Here is a patch for that redesign proposed by you; reverts commits
> fbe5a3fb73102c2cfec11aaaa4a67943f4474383 and
> 5d4171d1c70edfe3e9be1de9e66603af28e3afe1, adds changes for that redesign
> to the core, and adjusts the postgres_fdw code to that changes. Also, I
> rearranged the postgres_fdw regression tests to match that changes.
OK, I'll review this later today.
regards, tom lane
--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers
^ permalink raw reply [nested|flat] 19+ messages in thread
* Re: Oddity in handling of cached plans for FDW queries
2016-07-12 12:40 Oddity in handling of cached plans for FDW queries Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>
2016-07-13 09:00 ` Re: Oddity in handling of cached plans for FDW queries Ashutosh Bapat <ashutosh.bapat@enterprisedb.com>
2016-07-14 11:40 ` Re: Oddity in handling of cached plans for FDW queries Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>
2016-07-14 12:26 ` Re: Oddity in handling of cached plans for FDW queries Ashutosh Bapat <ashutosh.bapat@enterprisedb.com>
2016-07-14 16:32 ` Re: Oddity in handling of cached plans for FDW queries Tom Lane <tgl@sss.pgh.pa.us>
2016-07-14 18:49 ` Re: Oddity in handling of cached plans for FDW queries Tom Lane <tgl@sss.pgh.pa.us>
2016-07-15 02:37 ` Re: Oddity in handling of cached plans for FDW queries Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>
2016-07-15 02:48 ` Re: Oddity in handling of cached plans for FDW queries Tom Lane <tgl@sss.pgh.pa.us>
2016-07-15 12:55 ` Re: Oddity in handling of cached plans for FDW queries Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>
2016-07-15 13:35 ` Re: Oddity in handling of cached plans for FDW queries Tom Lane <tgl@sss.pgh.pa.us>
@ 2016-07-15 21:25 ` Tom Lane <tgl@sss.pgh.pa.us>
2016-07-20 12:00 ` Re: Oddity in handling of cached plans for FDW queries Robert Haas <robertmhaas@gmail.com>
2016-07-21 07:30 ` Re: Oddity in handling of cached plans for FDW queries Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>
0 siblings, 2 replies; 19+ messages in thread
From: Tom Lane @ 2016-07-15 21:25 UTC (permalink / raw)
To: Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>; +Cc: Ashutosh Bapat <ashutosh.bapat@enterprisedb.com>; pgsql-hackers
I wrote:
> Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp> writes:
>> Here is a patch for that redesign proposed by you; reverts commits
>> fbe5a3fb73102c2cfec11aaaa4a67943f4474383 and
>> 5d4171d1c70edfe3e9be1de9e66603af28e3afe1, adds changes for that redesign
>> to the core, and adjusts the postgres_fdw code to that changes. Also, I
>> rearranged the postgres_fdw regression tests to match that changes.
> OK, I'll review this later today.
Pushed, after fooling around with it some more so that it would cover the
case we discussed where the join could be allowed if we restrict the plan
to be executed by the owner of a view used in the query.
regards, tom lane
--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers
^ permalink raw reply [nested|flat] 19+ messages in thread
* Re: Oddity in handling of cached plans for FDW queries
2016-07-12 12:40 Oddity in handling of cached plans for FDW queries Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>
2016-07-13 09:00 ` Re: Oddity in handling of cached plans for FDW queries Ashutosh Bapat <ashutosh.bapat@enterprisedb.com>
2016-07-14 11:40 ` Re: Oddity in handling of cached plans for FDW queries Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>
2016-07-14 12:26 ` Re: Oddity in handling of cached plans for FDW queries Ashutosh Bapat <ashutosh.bapat@enterprisedb.com>
2016-07-14 16:32 ` Re: Oddity in handling of cached plans for FDW queries Tom Lane <tgl@sss.pgh.pa.us>
2016-07-14 18:49 ` Re: Oddity in handling of cached plans for FDW queries Tom Lane <tgl@sss.pgh.pa.us>
2016-07-15 02:37 ` Re: Oddity in handling of cached plans for FDW queries Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>
2016-07-15 02:48 ` Re: Oddity in handling of cached plans for FDW queries Tom Lane <tgl@sss.pgh.pa.us>
2016-07-15 12:55 ` Re: Oddity in handling of cached plans for FDW queries Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>
2016-07-15 13:35 ` Re: Oddity in handling of cached plans for FDW queries Tom Lane <tgl@sss.pgh.pa.us>
2016-07-15 21:25 ` Re: Oddity in handling of cached plans for FDW queries Tom Lane <tgl@sss.pgh.pa.us>
@ 2016-07-20 12:00 ` Robert Haas <robertmhaas@gmail.com>
2016-07-20 14:15 ` Re: Oddity in handling of cached plans for FDW queries Tom Lane <tgl@sss.pgh.pa.us>
1 sibling, 1 reply; 19+ messages in thread
From: Robert Haas @ 2016-07-20 12:00 UTC (permalink / raw)
To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>; Ashutosh Bapat <ashutosh.bapat@enterprisedb.com>; pgsql-hackers
On Fri, Jul 15, 2016 at 5:25 PM, Tom Lane <tgl@sss.pgh.pa.us> wrote:
> I wrote:
>> Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp> writes:
>>> Here is a patch for that redesign proposed by you; reverts commits
>>> fbe5a3fb73102c2cfec11aaaa4a67943f4474383 and
>>> 5d4171d1c70edfe3e9be1de9e66603af28e3afe1, adds changes for that redesign
>>> to the core, and adjusts the postgres_fdw code to that changes. Also, I
>>> rearranged the postgres_fdw regression tests to match that changes.
>
>> OK, I'll review this later today.
>
> Pushed, after fooling around with it some more so that it would cover the
> case we discussed where the join could be allowed if we restrict the plan
> to be executed by the owner of a view used in the query.
Mumble. Why, exactly, was this a good idea? The upside of commit
45639a0525a58a2700cf46d4c934d6de78349dac is only that you do fewer
plan invalidations, but surely that's not a significant benefit for
most people: user mappings don't change that often. On the downside,
there are now cases where joins would have gotten pushed down
previously and now they won't. In other words, you've saved some
replanning activity at the cost of delivering worse plans. That seems
pretty suspect to me, although I grant that the scenarios where either
the old or the new behavior is actually a problem are all somewhat off
the beaten path.
--
Robert Haas
EnterpriseDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company
--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers
^ permalink raw reply [nested|flat] 19+ messages in thread
* Re: Oddity in handling of cached plans for FDW queries
2016-07-12 12:40 Oddity in handling of cached plans for FDW queries Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>
2016-07-13 09:00 ` Re: Oddity in handling of cached plans for FDW queries Ashutosh Bapat <ashutosh.bapat@enterprisedb.com>
2016-07-14 11:40 ` Re: Oddity in handling of cached plans for FDW queries Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>
2016-07-14 12:26 ` Re: Oddity in handling of cached plans for FDW queries Ashutosh Bapat <ashutosh.bapat@enterprisedb.com>
2016-07-14 16:32 ` Re: Oddity in handling of cached plans for FDW queries Tom Lane <tgl@sss.pgh.pa.us>
2016-07-14 18:49 ` Re: Oddity in handling of cached plans for FDW queries Tom Lane <tgl@sss.pgh.pa.us>
2016-07-15 02:37 ` Re: Oddity in handling of cached plans for FDW queries Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>
2016-07-15 02:48 ` Re: Oddity in handling of cached plans for FDW queries Tom Lane <tgl@sss.pgh.pa.us>
2016-07-15 12:55 ` Re: Oddity in handling of cached plans for FDW queries Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>
2016-07-15 13:35 ` Re: Oddity in handling of cached plans for FDW queries Tom Lane <tgl@sss.pgh.pa.us>
2016-07-15 21:25 ` Re: Oddity in handling of cached plans for FDW queries Tom Lane <tgl@sss.pgh.pa.us>
2016-07-20 12:00 ` Re: Oddity in handling of cached plans for FDW queries Robert Haas <robertmhaas@gmail.com>
@ 2016-07-20 14:15 ` Tom Lane <tgl@sss.pgh.pa.us>
2016-07-20 14:57 ` Re: Oddity in handling of cached plans for FDW queries Robert Haas <robertmhaas@gmail.com>
0 siblings, 1 reply; 19+ messages in thread
From: Tom Lane @ 2016-07-20 14:15 UTC (permalink / raw)
To: Robert Haas <robertmhaas@gmail.com>; +Cc: Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>; Ashutosh Bapat <ashutosh.bapat@enterprisedb.com>; pgsql-hackers
Robert Haas <robertmhaas@gmail.com> writes:
> Mumble. Why, exactly, was this a good idea? The upside of commit
> 45639a0525a58a2700cf46d4c934d6de78349dac is only that you do fewer
> plan invalidations, but surely that's not a significant benefit for
> most people: user mappings don't change that often. On the downside,
> there are now cases where joins would have gotten pushed down
> previously and now they won't. In other words, you've saved some
> replanning activity at the cost of delivering worse plans. That seems
> pretty suspect to me, although I grant that the scenarios where either
> the old or the new behavior is actually a problem are all somewhat off
> the beaten path.
I think that you are undervaluing the removal of user-mapping-based plan
invalidation. That was never more than a kluge, and here is the reason:
we have no way to lock user mappings. The system whereby we invalidate
plans as a consequence of table DDL changes is bulletproof, because we
(re) acquire locks on the tables used in the plan, then check for
invalidation signals, before deciding whether the plan is stale. The
corresponding scenario where a user mapping changes between that check
and execution time is unprotected, so that we could end up using a plan
that is insecure for the mappings selected at execution.
Another way we could have removed the race condition is the suggestion
made upthread of embedding the user mapping details right into the plan
instead of looking them up afresh at execution. But I didn't much like
that approach, per upthread discussion.
regards, tom lane
--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers
^ permalink raw reply [nested|flat] 19+ messages in thread
* Re: Oddity in handling of cached plans for FDW queries
2016-07-12 12:40 Oddity in handling of cached plans for FDW queries Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>
2016-07-13 09:00 ` Re: Oddity in handling of cached plans for FDW queries Ashutosh Bapat <ashutosh.bapat@enterprisedb.com>
2016-07-14 11:40 ` Re: Oddity in handling of cached plans for FDW queries Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>
2016-07-14 12:26 ` Re: Oddity in handling of cached plans for FDW queries Ashutosh Bapat <ashutosh.bapat@enterprisedb.com>
2016-07-14 16:32 ` Re: Oddity in handling of cached plans for FDW queries Tom Lane <tgl@sss.pgh.pa.us>
2016-07-14 18:49 ` Re: Oddity in handling of cached plans for FDW queries Tom Lane <tgl@sss.pgh.pa.us>
2016-07-15 02:37 ` Re: Oddity in handling of cached plans for FDW queries Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>
2016-07-15 02:48 ` Re: Oddity in handling of cached plans for FDW queries Tom Lane <tgl@sss.pgh.pa.us>
2016-07-15 12:55 ` Re: Oddity in handling of cached plans for FDW queries Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>
2016-07-15 13:35 ` Re: Oddity in handling of cached plans for FDW queries Tom Lane <tgl@sss.pgh.pa.us>
2016-07-15 21:25 ` Re: Oddity in handling of cached plans for FDW queries Tom Lane <tgl@sss.pgh.pa.us>
2016-07-20 12:00 ` Re: Oddity in handling of cached plans for FDW queries Robert Haas <robertmhaas@gmail.com>
2016-07-20 14:15 ` Re: Oddity in handling of cached plans for FDW queries Tom Lane <tgl@sss.pgh.pa.us>
@ 2016-07-20 14:57 ` Robert Haas <robertmhaas@gmail.com>
0 siblings, 0 replies; 19+ messages in thread
From: Robert Haas @ 2016-07-20 14:57 UTC (permalink / raw)
To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>; Ashutosh Bapat <ashutosh.bapat@enterprisedb.com>; pgsql-hackers
On Wed, Jul 20, 2016 at 10:15 AM, Tom Lane <tgl@sss.pgh.pa.us> wrote:
> Robert Haas <robertmhaas@gmail.com> writes:
>> Mumble. Why, exactly, was this a good idea? The upside of commit
>> 45639a0525a58a2700cf46d4c934d6de78349dac is only that you do fewer
>> plan invalidations, but surely that's not a significant benefit for
>> most people: user mappings don't change that often. On the downside,
>> there are now cases where joins would have gotten pushed down
>> previously and now they won't. In other words, you've saved some
>> replanning activity at the cost of delivering worse plans. That seems
>> pretty suspect to me, although I grant that the scenarios where either
>> the old or the new behavior is actually a problem are all somewhat off
>> the beaten path.
>
> I think that you are undervaluing the removal of user-mapping-based plan
> invalidation. That was never more than a kluge, and here is the reason:
> we have no way to lock user mappings. The system whereby we invalidate
> plans as a consequence of table DDL changes is bulletproof, because we
> (re) acquire locks on the tables used in the plan, then check for
> invalidation signals, before deciding whether the plan is stale. The
> corresponding scenario where a user mapping changes between that check
> and execution time is unprotected, so that we could end up using a plan
> that is insecure for the mappings selected at execution.
OK, that's a fair point. Thanks for explaining.
> Another way we could have removed the race condition is the suggestion
> made upthread of embedding the user mapping details right into the plan
> instead of looking them up afresh at execution. But I didn't much like
> that approach, per upthread discussion.
OK.
--
Robert Haas
EnterpriseDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company
--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers
^ permalink raw reply [nested|flat] 19+ messages in thread
* Re: Oddity in handling of cached plans for FDW queries
2016-07-12 12:40 Oddity in handling of cached plans for FDW queries Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>
2016-07-13 09:00 ` Re: Oddity in handling of cached plans for FDW queries Ashutosh Bapat <ashutosh.bapat@enterprisedb.com>
2016-07-14 11:40 ` Re: Oddity in handling of cached plans for FDW queries Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>
2016-07-14 12:26 ` Re: Oddity in handling of cached plans for FDW queries Ashutosh Bapat <ashutosh.bapat@enterprisedb.com>
2016-07-14 16:32 ` Re: Oddity in handling of cached plans for FDW queries Tom Lane <tgl@sss.pgh.pa.us>
2016-07-14 18:49 ` Re: Oddity in handling of cached plans for FDW queries Tom Lane <tgl@sss.pgh.pa.us>
2016-07-15 02:37 ` Re: Oddity in handling of cached plans for FDW queries Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>
2016-07-15 02:48 ` Re: Oddity in handling of cached plans for FDW queries Tom Lane <tgl@sss.pgh.pa.us>
2016-07-15 12:55 ` Re: Oddity in handling of cached plans for FDW queries Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>
2016-07-15 13:35 ` Re: Oddity in handling of cached plans for FDW queries Tom Lane <tgl@sss.pgh.pa.us>
2016-07-15 21:25 ` Re: Oddity in handling of cached plans for FDW queries Tom Lane <tgl@sss.pgh.pa.us>
@ 2016-07-21 07:30 ` Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>
2016-07-22 03:41 ` Re: Oddity in handling of cached plans for FDW queries Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>
1 sibling, 1 reply; 19+ messages in thread
From: Etsuro Fujita @ 2016-07-21 07:30 UTC (permalink / raw)
To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Ashutosh Bapat <ashutosh.bapat@enterprisedb.com>; pgsql-hackers
On 2016/07/16 6:25, Tom Lane wrote:
> Pushed, after fooling around with it some more so that it would cover the
> case we discussed where the join could be allowed if we restrict the plan
> to be executed by the owner of a view used in the query.
I left that for future work, but I'm happy to have that in 9.6. Thanks
for improving and committing the patch!
One thing I'd like to discuss is GetUserMappingById/GetUserMappingId.
Though those functions aren't used in any places, I didn't take them
out, because I thought somebody else would need them someday. But
considering that user mapping OIDs now aren't available in RelOptInfos,
at least the former might be rather useless. Should we keep them in core?
Best regards,
Etsuro Fujita
--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers
^ permalink raw reply [nested|flat] 19+ messages in thread
* Re: Oddity in handling of cached plans for FDW queries
2016-07-12 12:40 Oddity in handling of cached plans for FDW queries Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>
2016-07-13 09:00 ` Re: Oddity in handling of cached plans for FDW queries Ashutosh Bapat <ashutosh.bapat@enterprisedb.com>
2016-07-14 11:40 ` Re: Oddity in handling of cached plans for FDW queries Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>
2016-07-14 12:26 ` Re: Oddity in handling of cached plans for FDW queries Ashutosh Bapat <ashutosh.bapat@enterprisedb.com>
2016-07-14 16:32 ` Re: Oddity in handling of cached plans for FDW queries Tom Lane <tgl@sss.pgh.pa.us>
2016-07-14 18:49 ` Re: Oddity in handling of cached plans for FDW queries Tom Lane <tgl@sss.pgh.pa.us>
2016-07-15 02:37 ` Re: Oddity in handling of cached plans for FDW queries Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>
2016-07-15 02:48 ` Re: Oddity in handling of cached plans for FDW queries Tom Lane <tgl@sss.pgh.pa.us>
2016-07-15 12:55 ` Re: Oddity in handling of cached plans for FDW queries Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>
2016-07-15 13:35 ` Re: Oddity in handling of cached plans for FDW queries Tom Lane <tgl@sss.pgh.pa.us>
2016-07-15 21:25 ` Re: Oddity in handling of cached plans for FDW queries Tom Lane <tgl@sss.pgh.pa.us>
2016-07-21 07:30 ` Re: Oddity in handling of cached plans for FDW queries Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>
@ 2016-07-22 03:41 ` Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>
2016-07-22 15:33 ` Re: Oddity in handling of cached plans for FDW queries Tom Lane <tgl@sss.pgh.pa.us>
0 siblings, 1 reply; 19+ messages in thread
From: Etsuro Fujita @ 2016-07-22 03:41 UTC (permalink / raw)
To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Ashutosh Bapat <ashutosh.bapat@enterprisedb.com>; pgsql-hackers
On 2016/07/21 16:30, Etsuro Fujita wrote:
> One thing I'd like to discuss is GetUserMappingById/GetUserMappingId.
> Though those functions aren't used in any places, I didn't take them
> out, because I thought somebody else would need them someday. But
> considering that user mapping OIDs now aren't available in RelOptInfos,
> at least the former might be rather useless. Should we keep them in core?
I thought a bit more about this. ISTM that there isn't much value in
the latter either, because we can use GetUserMapping and get that OID
from the result, instead of using the latter, so I'd vote for removing
those functions. Attached is a patch for that.
Best regards,
Etsuro Fujita
--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers
Attachments:
remove-usermapping-helper-funcs.patch (binary/octet-stream, 5.5K) download
*** a/doc/src/sgml/fdwhandler.sgml
--- b/doc/src/sgml/fdwhandler.sgml
***************
*** 1323,1342 **** GetForeignTable(Oid relid);
<para>
<programlisting>
- UserMapping *
- GetUserMappingById(Oid umid);
- </programlisting>
-
- This function returns the <structname>UserMapping</structname> object for
- the given user mapping OID. The OID of a user mapping for a foreign scan
- is available in the <structname>RelOptInfo</structname>.
- If there is no mapping for the OID, this function will throw an error.
- A <structname>UserMapping</structname> object contains properties of the
- user mapping (see <filename>foreign/foreign.h</filename> for details).
- </para>
-
- <para>
- <programlisting>
List *
GetForeignColumnOptions(Oid relid, AttrNumber attnum);
</programlisting>
--- 1323,1328 ----
*** a/src/backend/foreign/foreign.c
--- b/src/backend/foreign/foreign.c
***************
*** 31,38 ****
extern Datum pg_options_to_table(PG_FUNCTION_ARGS);
extern Datum postgresql_fdw_validator(PG_FUNCTION_ARGS);
- static HeapTuple find_user_mapping(Oid userid, Oid serverid);
-
/*
* GetForeignDataWrapper - look up the foreign-data wrapper by OID.
--- 31,36 ----
***************
*** 161,214 **** GetForeignServerByName(const char *srvname, bool missing_ok)
return GetForeignServer(serverid);
}
- /*
- * GetUserMappingById - look up the user mapping by its OID.
- */
- UserMapping *
- GetUserMappingById(Oid umid)
- {
- Datum datum;
- HeapTuple tp;
- bool isnull;
- UserMapping *um;
-
- tp = SearchSysCache1(USERMAPPINGOID, ObjectIdGetDatum(umid));
- if (!HeapTupleIsValid(tp))
- elog(ERROR, "cache lookup failed for user mapping %u", umid);
-
- um = (UserMapping *) palloc(sizeof(UserMapping));
- um->umid = umid;
-
- /* Extract the umuser */
- datum = SysCacheGetAttr(USERMAPPINGOID,
- tp,
- Anum_pg_user_mapping_umuser,
- &isnull);
- Assert(!isnull);
- um->userid = DatumGetObjectId(datum);
-
- /* Extract the umserver */
- datum = SysCacheGetAttr(USERMAPPINGOID,
- tp,
- Anum_pg_user_mapping_umserver,
- &isnull);
- Assert(!isnull);
- um->serverid = DatumGetObjectId(datum);
-
- /* Extract the umoptions */
- datum = SysCacheGetAttr(USERMAPPINGOID,
- tp,
- Anum_pg_user_mapping_umoptions,
- &isnull);
- if (isnull)
- um->options = NIL;
- else
- um->options = untransformRelOptions(datum);
-
- ReleaseSysCache(tp);
-
- return um;
- }
/*
* GetUserMapping - look up the user mapping.
--- 159,164 ----
***************
*** 224,230 **** GetUserMapping(Oid userid, Oid serverid)
bool isnull;
UserMapping *um;
! tp = find_user_mapping(userid, serverid);
um = (UserMapping *) palloc(sizeof(UserMapping));
um->umid = HeapTupleGetOid(tp);
--- 174,196 ----
bool isnull;
UserMapping *um;
! tp = SearchSysCache2(USERMAPPINGUSERSERVER,
! ObjectIdGetDatum(userid),
! ObjectIdGetDatum(serverid));
!
! if (!HeapTupleIsValid(tp))
! {
! /* Not found for the specific user -- try PUBLIC */
! tp = SearchSysCache2(USERMAPPINGUSERSERVER,
! ObjectIdGetDatum(InvalidOid),
! ObjectIdGetDatum(serverid));
! }
!
! if (!HeapTupleIsValid(tp))
! ereport(ERROR,
! (errcode(ERRCODE_UNDEFINED_OBJECT),
! errmsg("user mapping not found for \"%s\"",
! MappingUserName(userid))));
um = (UserMapping *) palloc(sizeof(UserMapping));
um->umid = HeapTupleGetOid(tp);
***************
*** 246,305 **** GetUserMapping(Oid userid, Oid serverid)
return um;
}
- /*
- * GetUserMappingId - look up the user mapping, and return its OID
- *
- * If no mapping is found for the supplied user, we also look for
- * PUBLIC mappings (userid == InvalidOid).
- */
- Oid
- GetUserMappingId(Oid userid, Oid serverid)
- {
- HeapTuple tp;
- Oid umid;
-
- tp = find_user_mapping(userid, serverid);
-
- /* Extract the Oid */
- umid = HeapTupleGetOid(tp);
-
- ReleaseSysCache(tp);
-
- return umid;
- }
-
- /*
- * find_user_mapping - Guts of GetUserMapping family.
- *
- * If no mapping is found for the supplied user, we also look for
- * PUBLIC mappings (userid == InvalidOid).
- */
- static HeapTuple
- find_user_mapping(Oid userid, Oid serverid)
- {
- HeapTuple tp;
-
- tp = SearchSysCache2(USERMAPPINGUSERSERVER,
- ObjectIdGetDatum(userid),
- ObjectIdGetDatum(serverid));
-
- if (HeapTupleIsValid(tp))
- return tp;
-
- /* Not found for the specific user -- try PUBLIC */
- tp = SearchSysCache2(USERMAPPINGUSERSERVER,
- ObjectIdGetDatum(InvalidOid),
- ObjectIdGetDatum(serverid));
-
- if (!HeapTupleIsValid(tp))
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("user mapping not found for \"%s\"",
- MappingUserName(userid))));
-
- return tp;
- }
-
/*
* GetForeignTable - look up the foreign table definition by relation oid.
--- 212,217 ----
*** a/src/include/foreign/foreign.h
--- b/src/include/foreign/foreign.h
***************
*** 72,79 **** typedef struct ForeignTable
extern ForeignServer *GetForeignServer(Oid serverid);
extern ForeignServer *GetForeignServerByName(const char *name, bool missing_ok);
extern UserMapping *GetUserMapping(Oid userid, Oid serverid);
- extern Oid GetUserMappingId(Oid userid, Oid serverid);
- extern UserMapping *GetUserMappingById(Oid umid);
extern ForeignDataWrapper *GetForeignDataWrapper(Oid fdwid);
extern ForeignDataWrapper *GetForeignDataWrapperByName(const char *name,
bool missing_ok);
--- 72,77 ----
^ permalink raw reply [nested|flat] 19+ messages in thread
* Re: Oddity in handling of cached plans for FDW queries
2016-07-12 12:40 Oddity in handling of cached plans for FDW queries Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>
2016-07-13 09:00 ` Re: Oddity in handling of cached plans for FDW queries Ashutosh Bapat <ashutosh.bapat@enterprisedb.com>
2016-07-14 11:40 ` Re: Oddity in handling of cached plans for FDW queries Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>
2016-07-14 12:26 ` Re: Oddity in handling of cached plans for FDW queries Ashutosh Bapat <ashutosh.bapat@enterprisedb.com>
2016-07-14 16:32 ` Re: Oddity in handling of cached plans for FDW queries Tom Lane <tgl@sss.pgh.pa.us>
2016-07-14 18:49 ` Re: Oddity in handling of cached plans for FDW queries Tom Lane <tgl@sss.pgh.pa.us>
2016-07-15 02:37 ` Re: Oddity in handling of cached plans for FDW queries Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>
2016-07-15 02:48 ` Re: Oddity in handling of cached plans for FDW queries Tom Lane <tgl@sss.pgh.pa.us>
2016-07-15 12:55 ` Re: Oddity in handling of cached plans for FDW queries Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>
2016-07-15 13:35 ` Re: Oddity in handling of cached plans for FDW queries Tom Lane <tgl@sss.pgh.pa.us>
2016-07-15 21:25 ` Re: Oddity in handling of cached plans for FDW queries Tom Lane <tgl@sss.pgh.pa.us>
2016-07-21 07:30 ` Re: Oddity in handling of cached plans for FDW queries Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>
2016-07-22 03:41 ` Re: Oddity in handling of cached plans for FDW queries Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>
@ 2016-07-22 15:33 ` Tom Lane <tgl@sss.pgh.pa.us>
0 siblings, 0 replies; 19+ messages in thread
From: Tom Lane @ 2016-07-22 15:33 UTC (permalink / raw)
To: Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>; +Cc: Ashutosh Bapat <ashutosh.bapat@enterprisedb.com>; pgsql-hackers
Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp> writes:
> On 2016/07/21 16:30, Etsuro Fujita wrote:
>> One thing I'd like to discuss is GetUserMappingById/GetUserMappingId.
>> Though those functions aren't used in any places, I didn't take them
>> out, because I thought somebody else would need them someday. But
>> considering that user mapping OIDs now aren't available in RelOptInfos,
>> at least the former might be rather useless. Should we keep them in core?
> I thought a bit more about this. ISTM that there isn't much value in
> the latter either, because we can use GetUserMapping and get that OID
> from the result, instead of using the latter, so I'd vote for removing
> those functions. Attached is a patch for that.
Agreed - pushed.
regards, tom lane
--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers
^ permalink raw reply [nested|flat] 19+ messages in thread
* Re: Oddity in handling of cached plans for FDW queries
2016-07-12 12:40 Oddity in handling of cached plans for FDW queries Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>
2016-07-13 09:00 ` Re: Oddity in handling of cached plans for FDW queries Ashutosh Bapat <ashutosh.bapat@enterprisedb.com>
2016-07-14 11:40 ` Re: Oddity in handling of cached plans for FDW queries Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>
2016-07-14 12:26 ` Re: Oddity in handling of cached plans for FDW queries Ashutosh Bapat <ashutosh.bapat@enterprisedb.com>
2016-07-14 16:32 ` Re: Oddity in handling of cached plans for FDW queries Tom Lane <tgl@sss.pgh.pa.us>
2016-07-14 18:49 ` Re: Oddity in handling of cached plans for FDW queries Tom Lane <tgl@sss.pgh.pa.us>
@ 2016-07-15 05:27 ` Ashutosh Bapat <ashutosh.bapat@enterprisedb.com>
1 sibling, 0 replies; 19+ messages in thread
From: Ashutosh Bapat @ 2016-07-15 05:27 UTC (permalink / raw)
To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>; pgsql-hackers
On Fri, Jul 15, 2016 at 12:19 AM, Tom Lane <tgl@sss.pgh.pa.us> wrote:
> I wrote:
> > I concur with Etsuro-san's dislike for hasForeignJoin; that flag is
> > underspecified and doesn't convey nearly enough information. I do not
> > think a uses_user_mapping flag is much better. ISTM what should happen
> is
> > that any time we decide to push down a foreign join, we should record the
> > identity of the common user mapping that made that pushdown possible in
> > the plan's invalItems list. That would make it possible to invalidate
> > only the relevant plans when a user mapping is changed.
>
> I thought a bit more about this and realized that the above doesn't work
> too well. Initially, a join might have been pushed down on the strength
> of both userids mapping to a PUBLIC user mapping for the server. If now
> someone does CREATE USER MAPPING to install a new mapping for one of
> those userids, we should invalidate the plan --- but there is certainly
> not going to be anything in the plan matching the new user mapping.
>
I replied to your earlier mail before reading this. Ok, so we agree there.
>
> > Another way we could attack it would be to record the foreign server OID
> > as an invalItem for any query that has more than one foreign table
> > belonging to the same foreign server. Then, invalidate whenever any user
> > mapping for that server changes.
>
> And that doesn't work so well either, because the most that the plan inval
> code is going to have its hands on is (a hash of) the OID of the user
> mapping that changed. We can't tell which server that's for.
>
I assumed that there is a way to get server's oid from user mapping or we
record it to be passed to the invalidation logic. Looks like there's no
easy way to do that.
>
> On reflection, it seems to me that we've gone wrong by tying planning to
> equality of user mappings at all, and the best way to get out of this is
> to not do that. Instead, let's insist that a join can be pushed down only
> if the checkAsUser fields of the relevant RTEs are equal. If they are,
> then the same user mapping must apply to both at runtime, whatever it is
> --- and we don't need to predetermine that. With this approach, the need
> for plan invalidation due to user mapping changes goes away entirely.
>
I have already explained in my earlier mail, that the problem you described
doesn't exist. With the invalidation logic we are able to also support
pushing down joins between table with different effective user.
>
> This doesn't cost us anything at all in simple cases such as direct
> execution of a query, because all the checkAsUser fields will be equal
> (i.e., zero). And it also doesn't hurt if the potential foreign join is
> encapsulated in a view, where all the checkAsUser fields would contain
> the OID of the view owner.
>
> The situation where we potentially lose something is a case like
> Etsuro-san's original example, where the query contains one foreign table
> reference coming from a view and one coming from the outer query, or maybe
> from a different view. In the two-views case we would have to not push
> down the join if the views have different owners, even though perhaps both
> owners will use the PUBLIC mapping at runtime. I think that's a narrow
> enough case that we can just live with not optimizing it. In the
> view-and-outer-query case, the simplest answer is that we can't push down
> because zero is not equal to the view owner's OID. We could make that a
> little better if we know that the query will be executed as the view
> owner, so that the relevant user IDs will be the same at runtime. There
> is already some mechanism in the plan cache to track whether a plan
> depends on the identity of the user running it (for RLS), so we could use
> that to enforce that a plan containing such a pushed-down join is only run
> by the same user that owns the view.
>
>
Join between views on foreign tables or between foreign tables and views
containing foreign tables won't be rare. This feature is yet to be
released, so we don't know if PostgreSQL users would find it useful. But I
do see Oracle users joining views on dblink tables. I would guess same
would be the case in PostgreSQL. But I would like to hear from other
PostgreSQL FDW users. In such cases, being able to push down a join between
foreign tables across view boundaries will be useful.
--
Best Wishes,
Ashutosh Bapat
EnterpriseDB Corporation
The Postgres Database Company
^ permalink raw reply [nested|flat] 19+ messages in thread
* Re: Oddity in handling of cached plans for FDW queries
2016-07-12 12:40 Oddity in handling of cached plans for FDW queries Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>
2016-07-13 09:00 ` Re: Oddity in handling of cached plans for FDW queries Ashutosh Bapat <ashutosh.bapat@enterprisedb.com>
2016-07-14 11:40 ` Re: Oddity in handling of cached plans for FDW queries Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>
2016-07-14 12:26 ` Re: Oddity in handling of cached plans for FDW queries Ashutosh Bapat <ashutosh.bapat@enterprisedb.com>
2016-07-14 16:32 ` Re: Oddity in handling of cached plans for FDW queries Tom Lane <tgl@sss.pgh.pa.us>
@ 2016-07-15 05:13 ` Ashutosh Bapat <ashutosh.bapat@enterprisedb.com>
1 sibling, 0 replies; 19+ messages in thread
From: Ashutosh Bapat @ 2016-07-15 05:13 UTC (permalink / raw)
To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>; pgsql-hackers
On Thu, Jul 14, 2016 at 10:02 PM, Tom Lane <tgl@sss.pgh.pa.us> wrote:
> Ashutosh Bapat <ashutosh.bapat@enterprisedb.com> writes:
> > Exactly, for a rare scenario, should we be penalizing large number of
> plans
> > or just continue to use a previously prepared plan when an optimal plan
> has
> > become available because of changed condition. I would choose second over
> > the first as it doesn't make things worse than they are.
>
> You seem to be arguing from a premise that the worst consequence is use of
> an inefficient plan. This is false; the worst consequence is use of a
> *wrong* plan, specifically one where a join has been pushed down but doing
> so is no longer legal because of a user mapping change. That is, it was
> previously correct to access the two remote tables under the same remote
> userID but now they should be accessed under different userIDs. The
> result will be that one or the other remote table is accessed under a
> userID that is not what the current user mappings say should be used.
> That could lead to either unexpected permissions failures (if the
> actually-used userID lacks needed permissions) or security breakdowns
> (if the actually-used userID has permissions to do something but the
> query should not have been allowed to do it).
>
> I do not think fixing this is optional.
>
There is confusion here. The current situation is this:
If at the time of preparing a statement a join can be pushed down to
foreign server, we mark that plan as hasForeignJoin. Before execution, if
user mapping changes (add/modify/drop), all plans with hasForeignJoin are
invalidated. This means the situation you are describing above does not
exist in the current code. So, nothing needs to be fixed.
>
> I concur with Etsuro-san's dislike for hasForeignJoin; that flag is
> underspecified and doesn't convey nearly enough information. I do not
> think a uses_user_mapping flag is much better. ISTM what should happen is
> that any time we decide to push down a foreign join, we should record the
> identity of the common user mapping that made that pushdown possible in
> the plan's invalItems list. That would make it possible to invalidate
> only the relevant plans when a user mapping is changed.
>
This, as you have proposed, does not solve the problem either. Consider a
case when a public user mapping was associated with the foreign tables
being joined and the join was pushed down while preparing statement and
plan. Before execution, a user mapping was added which changed one of the
table's associated user mapping from public to the new one. Now the join is
not pushable, but the user mapping that was added/changed was not recorded
in invalItems, which contains the public user mapping. An improvement to
your proposal would be to invalidate plans related to a public user
mapping, when any user mapping is added/changed/dropped. But I guess, there
are also some problems there too. Adding/dropping/changing a user mapping
affects other user mappings as well, unlike say doing that to tables or
views. When implementing this, we debated whether it's worth to add that
much complexity. We favoured not adding the complexity that time. The code
as is not optimistic and might lead to using already created suboptimal
plans, but it doesn't have any known bugs there (assuming, I have explained
why the above situation doesn't lead to a bug).
>
> I believe what Ashutosh is focusing on is whether, when some user mapping
> changes, we should invalidate all plans that could potentially now use a
> pushed-down join but did not before. I tend to agree that that's probably
> not something we want to do, as it would be very hard to identify just the
> plans likely to benefit. So we would cause replanning of a lot of queries
> that won't actually benefit, and in this direction it is indeed only an
> optimization not a correctness matter.
>
Right, that's my argument.
>
> Another way we could attack it would be to record the foreign server OID
> as an invalItem for any query that has more than one foreign table
> belonging to the same foreign server. Then, invalidate whenever any user
> mapping for that server changes. This would take care of both the case
> where a join pushdown becomes possible and where it stops becoming
> possible. But I'm not sure that the extra invalidations would be
> worthwhile.
>
Yes. That wouldn't have the problem I described above. Again, I am not sure
whether it's worth making code complex for that case. User mappings are not
something added/dropped/modified very frequently.
>
> I'm not excited about Etsuro-san's proposal to record user mapping info
> in the plan and skip execution-time mapping lookups altogether. I think
> (1) that's solving a problem that hasn't been proven to be a problem,
> (2) it doesn't help unless the FDW code is changed to take advantage of
> it, which is unlikely to happen for third-party FDWs, and (3) it opens
> the door to a class of new bugs, as any failure to invalidate after a
> mapping change would become a security fail even for non-join situations.
>
Yes, I agree.
--
Best Wishes,
Ashutosh Bapat
EnterpriseDB Corporation
The Postgres Database Company
^ permalink raw reply [nested|flat] 19+ messages in thread
end of thread, other threads:[~2016-07-22 15:33 UTC | newest]
Thread overview: 19+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2016-07-12 12:40 Oddity in handling of cached plans for FDW queries Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>
2016-07-13 09:00 ` Ashutosh Bapat <ashutosh.bapat@enterprisedb.com>
2016-07-14 11:40 ` Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>
2016-07-14 12:26 ` Ashutosh Bapat <ashutosh.bapat@enterprisedb.com>
2016-07-14 16:32 ` Tom Lane <tgl@sss.pgh.pa.us>
2016-07-14 18:49 ` Tom Lane <tgl@sss.pgh.pa.us>
2016-07-15 02:37 ` Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>
2016-07-15 02:48 ` Tom Lane <tgl@sss.pgh.pa.us>
2016-07-15 12:55 ` Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>
2016-07-15 13:35 ` Tom Lane <tgl@sss.pgh.pa.us>
2016-07-15 21:25 ` Tom Lane <tgl@sss.pgh.pa.us>
2016-07-20 12:00 ` Robert Haas <robertmhaas@gmail.com>
2016-07-20 14:15 ` Tom Lane <tgl@sss.pgh.pa.us>
2016-07-20 14:57 ` Robert Haas <robertmhaas@gmail.com>
2016-07-21 07:30 ` Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>
2016-07-22 03:41 ` Etsuro Fujita <fujita.etsuro@lab.ntt.co.jp>
2016-07-22 15:33 ` Tom Lane <tgl@sss.pgh.pa.us>
2016-07-15 05:27 ` Ashutosh Bapat <ashutosh.bapat@enterprisedb.com>
2016-07-15 05:13 ` Ashutosh Bapat <ashutosh.bapat@enterprisedb.com>
This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox