Branch data Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * postgres_fdw.c
4 : : * Foreign-data wrapper for remote PostgreSQL servers
5 : : *
6 : : * Portions Copyright (c) 2012-2026, PostgreSQL Global Development Group
7 : : *
8 : : * IDENTIFICATION
9 : : * contrib/postgres_fdw/postgres_fdw.c
10 : : *
11 : : *-------------------------------------------------------------------------
12 : : */
13 : : #include "postgres.h"
14 : :
15 : : #include <limits.h>
16 : :
17 : : #include "access/htup_details.h"
18 : : #include "access/sysattr.h"
19 : : #include "access/table.h"
20 : : #include "catalog/pg_opfamily.h"
21 : : #include "commands/defrem.h"
22 : : #include "commands/explain_format.h"
23 : : #include "commands/explain_state.h"
24 : : #include "commands/vacuum.h"
25 : : #include "executor/execAsync.h"
26 : : #include "executor/instrument.h"
27 : : #include "foreign/fdwapi.h"
28 : : #include "funcapi.h"
29 : : #include "miscadmin.h"
30 : : #include "nodes/makefuncs.h"
31 : : #include "nodes/nodeFuncs.h"
32 : : #include "optimizer/appendinfo.h"
33 : : #include "optimizer/clauses.h"
34 : : #include "optimizer/cost.h"
35 : : #include "optimizer/inherit.h"
36 : : #include "optimizer/optimizer.h"
37 : : #include "optimizer/pathnode.h"
38 : : #include "optimizer/paths.h"
39 : : #include "optimizer/planmain.h"
40 : : #include "optimizer/prep.h"
41 : : #include "optimizer/restrictinfo.h"
42 : : #include "optimizer/tlist.h"
43 : : #include "parser/parsetree.h"
44 : : #include "pgstat.h"
45 : : #include "postgres_fdw.h"
46 : : #include "statistics/statistics.h"
47 : : #include "storage/latch.h"
48 : : #include "utils/builtins.h"
49 : : #include "utils/float.h"
50 : : #include "utils/fmgroids.h"
51 : : #include "utils/guc.h"
52 : : #include "utils/lsyscache.h"
53 : : #include "utils/memutils.h"
54 : : #include "utils/rel.h"
55 : : #include "utils/sampling.h"
56 : : #include "utils/selfuncs.h"
57 : : #include "utils/timestamp.h"
58 : : #include "utils/typcache.h"
59 : :
60 : 39 : PG_MODULE_MAGIC_EXT(
61 : : .name = "postgres_fdw",
62 : : .version = PG_VERSION
63 : : );
64 : :
65 : : /* Default CPU cost to start up a foreign query. */
66 : : #define DEFAULT_FDW_STARTUP_COST 100.0
67 : :
68 : : /* Default CPU cost to process 1 row (above and beyond cpu_tuple_cost). */
69 : : #define DEFAULT_FDW_TUPLE_COST 0.2
70 : :
71 : : /* If no remote estimates, assume a sort costs 20% extra */
72 : : #define DEFAULT_FDW_SORT_MULTIPLIER 1.2
73 : :
74 : : /*
75 : : * Indexes of FDW-private information stored in fdw_private lists.
76 : : *
77 : : * These items are indexed with the enum FdwScanPrivateIndex, so an item
78 : : * can be fetched with list_nth(). For example, to get the SELECT statement:
79 : : * sql = strVal(list_nth(fdw_private, FdwScanPrivateSelectSql));
80 : : */
81 : : enum FdwScanPrivateIndex
82 : : {
83 : : /* SQL statement to execute remotely (as a String node) */
84 : : FdwScanPrivateSelectSql,
85 : : /* Integer list of attribute numbers retrieved by the SELECT */
86 : : FdwScanPrivateRetrievedAttrs,
87 : : /* Integer representing the desired fetch_size */
88 : : FdwScanPrivateFetchSize,
89 : :
90 : : /*
91 : : * String describing join i.e. names of relations being joined and types
92 : : * of join, added when the scan is join
93 : : */
94 : : FdwScanPrivateRelations,
95 : :
96 : : /*
97 : : * List of per-RTE function metadata, indexed by base RTI offset. Each
98 : : * element is either NULL (for non-RTE_FUNCTION rels in this scan) or a
99 : : * list of three-element lists (funcid, funcrettype, funccollation) -- one
100 : : * inner list per function in the RTE. Allows the executor to rebuild
101 : : * TupleDesc entries for whole-row references to function RTEs.
102 : : */
103 : : FdwScanPrivateFunctions,
104 : :
105 : : /*
106 : : * Integer node: minimum base RT index covered by the scan, used to
107 : : * translate scan-local indexes to estate-rtable indexes after setrefs.c
108 : : * flattens rtables.
109 : : */
110 : : FdwScanPrivateMinRTIndex,
111 : : };
112 : :
113 : : /*
114 : : * Similarly, this enum describes what's kept in the fdw_private list for
115 : : * a ModifyTable node referencing a postgres_fdw foreign table. We store:
116 : : *
117 : : * 1) INSERT/UPDATE/DELETE statement text to be sent to the remote server
118 : : * 2) Integer list of target attribute numbers for INSERT/UPDATE
119 : : * (NIL for a DELETE)
120 : : * 3) Length till the end of VALUES clause for INSERT
121 : : * (-1 for a DELETE/UPDATE)
122 : : * 4) Boolean flag showing if the remote query has a RETURNING clause
123 : : * 5) Integer list of attribute numbers retrieved by RETURNING, if any
124 : : */
125 : : enum FdwModifyPrivateIndex
126 : : {
127 : : /* SQL statement to execute remotely (as a String node) */
128 : : FdwModifyPrivateUpdateSql,
129 : : /* Integer list of target attribute numbers for INSERT/UPDATE */
130 : : FdwModifyPrivateTargetAttnums,
131 : : /* Length till the end of VALUES clause (as an Integer node) */
132 : : FdwModifyPrivateLen,
133 : : /* has-returning flag (as a Boolean node) */
134 : : FdwModifyPrivateHasReturning,
135 : : /* Integer list of attribute numbers retrieved by RETURNING */
136 : : FdwModifyPrivateRetrievedAttrs,
137 : : };
138 : :
139 : : /*
140 : : * Similarly, this enum describes what's kept in the fdw_private list for
141 : : * a ForeignScan node that modifies a foreign table directly. We store:
142 : : *
143 : : * 1) UPDATE/DELETE statement text to be sent to the remote server
144 : : * 2) Boolean flag showing if the remote query has a RETURNING clause
145 : : * 3) Integer list of attribute numbers retrieved by RETURNING, if any
146 : : * 4) Boolean flag showing if we set the command es_processed
147 : : * 5) Per-RTE function metadata (mirrors FdwScanPrivateFunctions; lets
148 : : * the executor rebuild TupleDesc entries for whole-row Vars over
149 : : * function RTEs absorbed into a foreign join)
150 : : * 6) Integer node: minimum base RT index of the scan (mirrors
151 : : * FdwScanPrivateMinRTIndex)
152 : : */
153 : : enum FdwDirectModifyPrivateIndex
154 : : {
155 : : /* SQL statement to execute remotely (as a String node) */
156 : : FdwDirectModifyPrivateUpdateSql,
157 : : /* has-returning flag (as a Boolean node) */
158 : : FdwDirectModifyPrivateHasReturning,
159 : : /* Integer list of attribute numbers retrieved by RETURNING */
160 : : FdwDirectModifyPrivateRetrievedAttrs,
161 : : /* set-processed flag (as a Boolean node) */
162 : : FdwDirectModifyPrivateSetProcessed,
163 : : /* Per-RTE function metadata, indexed by base RTI offset */
164 : : FdwDirectModifyPrivateFunctions,
165 : : /* Integer node: minimum base RT index in the scan */
166 : : FdwDirectModifyPrivateMinRTIndex,
167 : : };
168 : :
169 : : /*
170 : : * Execution state of a foreign scan using postgres_fdw.
171 : : */
172 : : typedef struct PgFdwScanState
173 : : {
174 : : Relation rel; /* relcache entry for the foreign table. NULL
175 : : * for a foreign join scan. */
176 : : TupleDesc tupdesc; /* tuple descriptor of scan */
177 : : AttInMetadata *attinmeta; /* attribute datatype conversion metadata */
178 : :
179 : : /* extracted fdw_private data */
180 : : char *query; /* text of SELECT command */
181 : : List *retrieved_attrs; /* list of retrieved attribute numbers */
182 : :
183 : : /* for remote query execution */
184 : : PGconn *conn; /* connection for the scan */
185 : : PgFdwConnState *conn_state; /* extra per-connection state */
186 : : unsigned int cursor_number; /* quasi-unique ID for my cursor */
187 : : bool cursor_exists; /* have we created the cursor? */
188 : : int numParams; /* number of parameters passed to query */
189 : : FmgrInfo *param_flinfo; /* output conversion functions for them */
190 : : List *param_exprs; /* executable expressions for param values */
191 : : const char **param_values; /* textual values of query parameters */
192 : :
193 : : /* for storing result tuples */
194 : : HeapTuple *tuples; /* array of currently-retrieved tuples */
195 : : int num_tuples; /* # of tuples in array */
196 : : int next_tuple; /* index of next one to return */
197 : :
198 : : /* batch-level state, for optimizing rewinds and avoiding useless fetch */
199 : : int fetch_ct_2; /* Min(# of fetches done, 2) */
200 : : bool eof_reached; /* true if last fetch reached EOF */
201 : :
202 : : /* for asynchronous execution */
203 : : bool async_capable; /* engage asynchronous-capable logic? */
204 : :
205 : : /* working memory contexts */
206 : : MemoryContext batch_cxt; /* context holding current batch of tuples */
207 : : MemoryContext temp_cxt; /* context for per-tuple temporary data */
208 : :
209 : : int fetch_size; /* number of tuples per fetch */
210 : : } PgFdwScanState;
211 : :
212 : : /*
213 : : * Execution state of a foreign insert/update/delete operation.
214 : : */
215 : : typedef struct PgFdwModifyState
216 : : {
217 : : Relation rel; /* relcache entry for the foreign table */
218 : : AttInMetadata *attinmeta; /* attribute datatype conversion metadata */
219 : :
220 : : /* for remote query execution */
221 : : PGconn *conn; /* connection for the scan */
222 : : PgFdwConnState *conn_state; /* extra per-connection state */
223 : : char *p_name; /* name of prepared statement, if created */
224 : :
225 : : /* extracted fdw_private data */
226 : : char *query; /* text of INSERT/UPDATE/DELETE command */
227 : : char *orig_query; /* original text of INSERT command */
228 : : List *target_attrs; /* list of target attribute numbers */
229 : : int values_end; /* length up to the end of VALUES */
230 : : int batch_size; /* value of FDW option "batch_size" */
231 : : bool has_returning; /* is there a RETURNING clause? */
232 : : List *retrieved_attrs; /* attr numbers retrieved by RETURNING */
233 : :
234 : : /* info about parameters for prepared statement */
235 : : AttrNumber ctidAttno; /* attnum of input resjunk ctid column */
236 : : int p_nums; /* number of parameters to transmit */
237 : : FmgrInfo *p_flinfo; /* output conversion functions for them */
238 : :
239 : : /* batch operation stuff */
240 : : int num_slots; /* number of slots to insert */
241 : :
242 : : /* working memory context */
243 : : MemoryContext temp_cxt; /* context for per-tuple temporary data */
244 : :
245 : : /* for update row movement if subplan result rel */
246 : : struct PgFdwModifyState *aux_fmstate; /* foreign-insert state, if
247 : : * created */
248 : : } PgFdwModifyState;
249 : :
250 : : /*
251 : : * Execution state of a foreign scan that modifies a foreign table directly.
252 : : */
253 : : typedef struct PgFdwDirectModifyState
254 : : {
255 : : Relation rel; /* relcache entry for the foreign table */
256 : : AttInMetadata *attinmeta; /* attribute datatype conversion metadata */
257 : :
258 : : /* extracted fdw_private data */
259 : : char *query; /* text of UPDATE/DELETE command */
260 : : bool has_returning; /* is there a RETURNING clause? */
261 : : List *retrieved_attrs; /* attr numbers retrieved by RETURNING */
262 : : bool set_processed; /* do we set the command es_processed? */
263 : :
264 : : /* for remote query execution */
265 : : PGconn *conn; /* connection for the update */
266 : : PgFdwConnState *conn_state; /* extra per-connection state */
267 : : int numParams; /* number of parameters passed to query */
268 : : FmgrInfo *param_flinfo; /* output conversion functions for them */
269 : : List *param_exprs; /* executable expressions for param values */
270 : : const char **param_values; /* textual values of query parameters */
271 : :
272 : : /* for storing result tuples */
273 : : PGresult *result; /* result for query */
274 : : int num_tuples; /* # of result tuples */
275 : : int next_tuple; /* index of next one to return */
276 : : Relation resultRel; /* relcache entry for the target relation */
277 : : AttrNumber *attnoMap; /* array of attnums of input user columns */
278 : : AttrNumber ctidAttno; /* attnum of input ctid column */
279 : : AttrNumber oidAttno; /* attnum of input oid column */
280 : : bool hasSystemCols; /* are there system columns of resultRel? */
281 : :
282 : : /* working memory context */
283 : : MemoryContext temp_cxt; /* context for per-tuple temporary data */
284 : : } PgFdwDirectModifyState;
285 : :
286 : : /*
287 : : * Workspace for analyzing a foreign table.
288 : : */
289 : : typedef struct PgFdwAnalyzeState
290 : : {
291 : : Relation rel; /* relcache entry for the foreign table */
292 : : AttInMetadata *attinmeta; /* attribute datatype conversion metadata */
293 : : List *retrieved_attrs; /* attr numbers retrieved by query */
294 : :
295 : : /* collected sample rows */
296 : : HeapTuple *rows; /* array of size targrows */
297 : : int targrows; /* target # of sample rows */
298 : : int numrows; /* # of sample rows collected */
299 : :
300 : : /* for random sampling */
301 : : double samplerows; /* # of rows fetched */
302 : : double rowstoskip; /* # of rows to skip before next sample */
303 : : ReservoirStateData rstate; /* state for reservoir sampling */
304 : :
305 : : /* working memory contexts */
306 : : MemoryContext anl_cxt; /* context for per-analyze lifespan data */
307 : : MemoryContext temp_cxt; /* context for per-tuple temporary data */
308 : : } PgFdwAnalyzeState;
309 : :
310 : : /*
311 : : * This enum describes what's kept in the fdw_private list for a ForeignPath.
312 : : * We store:
313 : : *
314 : : * 1) Boolean flag showing if the remote query has the final sort
315 : : * 2) Boolean flag showing if the remote query has the LIMIT clause
316 : : */
317 : : enum FdwPathPrivateIndex
318 : : {
319 : : /* has-final-sort flag (as a Boolean node) */
320 : : FdwPathPrivateHasFinalSort,
321 : : /* has-limit flag (as a Boolean node) */
322 : : FdwPathPrivateHasLimit,
323 : : };
324 : :
325 : : /* Struct for extra information passed to estimate_path_cost_size() */
326 : : typedef struct
327 : : {
328 : : PathTarget *target;
329 : : bool has_final_sort;
330 : : bool has_limit;
331 : : double limit_tuples;
332 : : int64 count_est;
333 : : int64 offset_est;
334 : : } PgFdwPathExtraData;
335 : :
336 : : /*
337 : : * Identify the attribute where data conversion fails.
338 : : */
339 : : typedef struct ConversionLocation
340 : : {
341 : : AttrNumber cur_attno; /* attribute number being processed, or 0 */
342 : : Relation rel; /* foreign table being processed, or NULL */
343 : : ForeignScanState *fsstate; /* plan node being processed, or NULL */
344 : : } ConversionLocation;
345 : :
346 : : /* Callback argument for ec_member_matches_foreign */
347 : : typedef struct
348 : : {
349 : : Expr *current; /* current expr, or NULL if not yet found */
350 : : List *already_used; /* expressions already dealt with */
351 : : } ec_member_foreign_arg;
352 : :
353 : : /* Column order in relation stats query */
354 : : enum RelStatsColumns
355 : : {
356 : : RELSTATS_RELPAGES = 0,
357 : : RELSTATS_RELTUPLES,
358 : : RELSTATS_RELKIND,
359 : : RELSTATS_RELHASSUBCLASS,
360 : : RELSTATS_NUM_FIELDS,
361 : : };
362 : :
363 : : /* Column order in attribute stats query */
364 : : enum AttStatsColumns
365 : : {
366 : : ATTSTATS_ATTNAME = 0,
367 : : ATTSTATS_NULL_FRAC,
368 : : ATTSTATS_AVG_WIDTH,
369 : : ATTSTATS_N_DISTINCT,
370 : : ATTSTATS_MOST_COMMON_VALS,
371 : : ATTSTATS_MOST_COMMON_FREQS,
372 : : ATTSTATS_HISTOGRAM_BOUNDS,
373 : : ATTSTATS_CORRELATION,
374 : : ATTSTATS_MOST_COMMON_ELEMS,
375 : : ATTSTATS_MOST_COMMON_ELEM_FREQS,
376 : : ATTSTATS_ELEM_COUNT_HISTOGRAM,
377 : : ATTSTATS_RANGE_LENGTH_HISTOGRAM,
378 : : ATTSTATS_RANGE_EMPTY_FRAC,
379 : : ATTSTATS_RANGE_BOUNDS_HISTOGRAM,
380 : : ATTSTATS_NUM_FIELDS,
381 : : };
382 : :
383 : : /* Results that are returned from a foreign statistics scan */
384 : : typedef struct
385 : : {
386 : : int version; /* version of remote server */
387 : : BlockNumber relpages; /* # of pages in remote table */
388 : : double reltuples; /* # of tuples in remote table */
389 : : PGresult *rel; /* result for relation stats query */
390 : : PGresult *att; /* result for attribute stats query */
391 : : } RemoteStatsResults;
392 : :
393 : : /* Pairs of remote columns with local columns */
394 : : typedef struct
395 : : {
396 : : AttrNumber local_attnum; /* attribute number of local column */
397 : : char *local_attname; /* attribute name of local column */
398 : : char *remote_attname; /* attribute name of remote column */
399 : : int res_index; /* index of row in attribute stats result */
400 : : } RemoteAttributeMapping;
401 : :
402 : : /*
403 : : * SQL functions
404 : : */
405 : 20 : PG_FUNCTION_INFO_V1(postgres_fdw_handler);
406 : :
407 : : /*
408 : : * FDW callback routines
409 : : */
410 : : static void postgresGetForeignRelSize(PlannerInfo *root,
411 : : RelOptInfo *baserel,
412 : : Oid foreigntableid);
413 : : static void postgresGetForeignPaths(PlannerInfo *root,
414 : : RelOptInfo *baserel,
415 : : Oid foreigntableid);
416 : : static ForeignScan *postgresGetForeignPlan(PlannerInfo *root,
417 : : RelOptInfo *foreignrel,
418 : : Oid foreigntableid,
419 : : ForeignPath *best_path,
420 : : List *tlist,
421 : : List *scan_clauses,
422 : : Plan *outer_plan);
423 : : static void postgresBeginForeignScan(ForeignScanState *node, int eflags);
424 : : static TupleTableSlot *postgresIterateForeignScan(ForeignScanState *node);
425 : : static void postgresReScanForeignScan(ForeignScanState *node);
426 : : static void postgresEndForeignScan(ForeignScanState *node);
427 : : static void postgresAddForeignUpdateTargets(PlannerInfo *root,
428 : : Index rtindex,
429 : : RangeTblEntry *target_rte,
430 : : Relation target_relation);
431 : : static List *postgresPlanForeignModify(PlannerInfo *root,
432 : : ModifyTable *plan,
433 : : Index resultRelation,
434 : : int subplan_index);
435 : : static void postgresBeginForeignModify(ModifyTableState *mtstate,
436 : : ResultRelInfo *resultRelInfo,
437 : : List *fdw_private,
438 : : int subplan_index,
439 : : int eflags);
440 : : static TupleTableSlot *postgresExecForeignInsert(EState *estate,
441 : : ResultRelInfo *resultRelInfo,
442 : : TupleTableSlot *slot,
443 : : TupleTableSlot *planSlot);
444 : : static TupleTableSlot **postgresExecForeignBatchInsert(EState *estate,
445 : : ResultRelInfo *resultRelInfo,
446 : : TupleTableSlot **slots,
447 : : TupleTableSlot **planSlots,
448 : : int *numSlots);
449 : : static int postgresGetForeignModifyBatchSize(ResultRelInfo *resultRelInfo);
450 : : static TupleTableSlot *postgresExecForeignUpdate(EState *estate,
451 : : ResultRelInfo *resultRelInfo,
452 : : TupleTableSlot *slot,
453 : : TupleTableSlot *planSlot);
454 : : static TupleTableSlot *postgresExecForeignDelete(EState *estate,
455 : : ResultRelInfo *resultRelInfo,
456 : : TupleTableSlot *slot,
457 : : TupleTableSlot *planSlot);
458 : : static void postgresEndForeignModify(EState *estate,
459 : : ResultRelInfo *resultRelInfo);
460 : : static void postgresBeginForeignInsert(ModifyTableState *mtstate,
461 : : ResultRelInfo *resultRelInfo);
462 : : static void postgresEndForeignInsert(EState *estate,
463 : : ResultRelInfo *resultRelInfo);
464 : : static int postgresIsForeignRelUpdatable(Relation rel);
465 : : static bool postgresPlanDirectModify(PlannerInfo *root,
466 : : ModifyTable *plan,
467 : : Index resultRelation,
468 : : int subplan_index);
469 : : static void postgresBeginDirectModify(ForeignScanState *node, int eflags);
470 : : static TupleTableSlot *postgresIterateDirectModify(ForeignScanState *node);
471 : : static void postgresEndDirectModify(ForeignScanState *node);
472 : : static void postgresExplainForeignScan(ForeignScanState *node,
473 : : ExplainState *es);
474 : : static void postgresExplainForeignModify(ModifyTableState *mtstate,
475 : : ResultRelInfo *rinfo,
476 : : List *fdw_private,
477 : : int subplan_index,
478 : : ExplainState *es);
479 : : static void postgresExplainDirectModify(ForeignScanState *node,
480 : : ExplainState *es);
481 : : static void postgresExecForeignTruncate(List *rels,
482 : : DropBehavior behavior,
483 : : bool restart_seqs);
484 : : static bool postgresAnalyzeForeignTable(Relation relation,
485 : : AcquireSampleRowsFunc *func,
486 : : BlockNumber *totalpages);
487 : : static bool postgresImportForeignStatistics(Relation relation,
488 : : List *va_cols,
489 : : int elevel);
490 : : static List *postgresImportForeignSchema(ImportForeignSchemaStmt *stmt,
491 : : Oid serverOid);
492 : : static void postgresGetForeignJoinPaths(PlannerInfo *root,
493 : : RelOptInfo *joinrel,
494 : : RelOptInfo *outerrel,
495 : : RelOptInfo *innerrel,
496 : : JoinType jointype,
497 : : JoinPathExtraData *extra);
498 : : static bool postgresRecheckForeignScan(ForeignScanState *node,
499 : : TupleTableSlot *slot);
500 : : static void postgresGetForeignUpperPaths(PlannerInfo *root,
501 : : UpperRelationKind stage,
502 : : RelOptInfo *input_rel,
503 : : RelOptInfo *output_rel,
504 : : void *extra);
505 : : static bool postgresIsForeignPathAsyncCapable(ForeignPath *path);
506 : : static void postgresForeignAsyncRequest(AsyncRequest *areq);
507 : : static void postgresForeignAsyncConfigureWait(AsyncRequest *areq);
508 : : static void postgresForeignAsyncNotify(AsyncRequest *areq);
509 : :
510 : : /*
511 : : * Helper functions
512 : : */
513 : : static void estimate_path_cost_size(PlannerInfo *root,
514 : : RelOptInfo *foreignrel,
515 : : List *param_join_conds,
516 : : List *pathkeys,
517 : : PgFdwPathExtraData *fpextra,
518 : : double *p_rows, int *p_width,
519 : : int *p_disabled_nodes,
520 : : Cost *p_startup_cost, Cost *p_total_cost);
521 : : static void get_remote_estimate(const char *sql,
522 : : PGconn *conn,
523 : : double *rows,
524 : : int *width,
525 : : Cost *startup_cost,
526 : : Cost *total_cost);
527 : : static void adjust_foreign_grouping_path_cost(PlannerInfo *root,
528 : : List *pathkeys,
529 : : double retrieved_rows,
530 : : double width,
531 : : double limit_tuples,
532 : : int *p_disabled_nodes,
533 : : Cost *p_startup_cost,
534 : : Cost *p_run_cost);
535 : : static bool ec_member_matches_foreign(PlannerInfo *root, RelOptInfo *rel,
536 : : EquivalenceClass *ec, EquivalenceMember *em,
537 : : void *arg);
538 : : static void create_cursor(ForeignScanState *node);
539 : : static void fetch_more_data(ForeignScanState *node);
540 : : static void close_cursor(PGconn *conn, unsigned int cursor_number,
541 : : PgFdwConnState *conn_state);
542 : : static PgFdwModifyState *create_foreign_modify(EState *estate,
543 : : RangeTblEntry *rte,
544 : : ResultRelInfo *resultRelInfo,
545 : : CmdType operation,
546 : : Plan *subplan,
547 : : char *query,
548 : : List *target_attrs,
549 : : int values_end,
550 : : bool has_returning,
551 : : List *retrieved_attrs);
552 : : static TupleTableSlot **execute_foreign_modify(EState *estate,
553 : : ResultRelInfo *resultRelInfo,
554 : : CmdType operation,
555 : : TupleTableSlot **slots,
556 : : TupleTableSlot **planSlots,
557 : : int *numSlots);
558 : : static void prepare_foreign_modify(PgFdwModifyState *fmstate);
559 : : static const char **convert_prep_stmt_params(PgFdwModifyState *fmstate,
560 : : ItemPointer tupleid,
561 : : TupleTableSlot **slots,
562 : : int numSlots);
563 : : static void store_returning_result(PgFdwModifyState *fmstate,
564 : : TupleTableSlot *slot, PGresult *res);
565 : : static void finish_foreign_modify(PgFdwModifyState *fmstate);
566 : : static void deallocate_query(PgFdwModifyState *fmstate);
567 : : static List *build_remote_returning(Index rtindex, Relation rel,
568 : : List *returningList);
569 : : static void rebuild_fdw_scan_tlist(ForeignScan *fscan, List *tlist);
570 : : static void execute_dml_stmt(ForeignScanState *node);
571 : : static TupleTableSlot *get_returning_data(ForeignScanState *node);
572 : : static void init_returning_filter(PgFdwDirectModifyState *dmstate,
573 : : List *fdw_scan_tlist,
574 : : Index rtindex);
575 : : static TupleTableSlot *apply_returning_filter(PgFdwDirectModifyState *dmstate,
576 : : ResultRelInfo *resultRelInfo,
577 : : TupleTableSlot *slot,
578 : : EState *estate);
579 : : static void prepare_query_params(PlanState *node,
580 : : List *fdw_exprs,
581 : : int numParams,
582 : : FmgrInfo **param_flinfo,
583 : : List **param_exprs,
584 : : const char ***param_values);
585 : : static void process_query_params(ExprContext *econtext,
586 : : FmgrInfo *param_flinfo,
587 : : List *param_exprs,
588 : : const char **param_values);
589 : : static int postgresAcquireSampleRowsFunc(Relation relation, int elevel,
590 : : HeapTuple *rows, int targrows,
591 : : double *totalrows,
592 : : double *totaldeadrows);
593 : : static void analyze_row_processor(PGresult *res, int row,
594 : : PgFdwAnalyzeState *astate);
595 : : static bool fetch_remote_statistics(Relation relation,
596 : : List *va_cols,
597 : : const char *local_schemaname,
598 : : const char *local_relname,
599 : : ForeignTable *table,
600 : : ForeignServer *server,
601 : : RemoteStatsResults *remstats,
602 : : RemoteAttributeMapping **p_remattrmap,
603 : : int *p_attrcnt);
604 : : static PGresult *fetch_relstats(PGconn *conn, Relation relation);
605 : : static PGresult *fetch_attstats(PGconn *conn, int server_version_num,
606 : : const char *remote_schemaname, const char *remote_relname,
607 : : const char *column_list);
608 : : static RemoteAttributeMapping *build_remattrmap(Relation relation, List *va_cols,
609 : : int *p_attrcnt, StringInfo column_list);
610 : : static void free_remattrmap(RemoteAttributeMapping *map, int len);
611 : : static bool attname_in_list(const char *attname, List *va_cols);
612 : : static int remattrmap_cmp(const void *v1, const void *v2);
613 : : static bool match_attrmap(PGresult *res,
614 : : const char *local_schemaname,
615 : : const char *local_relname,
616 : : const char *remote_schemaname,
617 : : const char *remote_relname,
618 : : RemoteAttributeMapping *remattrmap,
619 : : int attrcnt);
620 : : static bool import_fetched_statistics(Relation relation,
621 : : const char *schemaname,
622 : : const char *relname,
623 : : RemoteStatsResults *remstats,
624 : : const RemoteAttributeMapping *remattrmap,
625 : : int attrcnt);
626 : : static char *get_opt_value(PGresult *res, int row, int col);
627 : : static void set_text_arg(NullableDatum *arg, const char *s);
628 : : static void set_int32_arg(NullableDatum *arg, const char *s);
629 : : static void set_float_arg(NullableDatum *arg, const char *s);
630 : : static void set_floatarr_arg(NullableDatum *arg, const char *s);
631 : : static void produce_tuple_asynchronously(AsyncRequest *areq, bool fetch);
632 : : static void fetch_more_data_begin(AsyncRequest *areq);
633 : : static void complete_pending_request(AsyncRequest *areq);
634 : : static HeapTuple make_tuple_from_result_row(PGresult *res,
635 : : int row,
636 : : Relation rel,
637 : : AttInMetadata *attinmeta,
638 : : List *retrieved_attrs,
639 : : ForeignScanState *fsstate,
640 : : MemoryContext temp_context);
641 : : static void conversion_error_callback(void *arg);
642 : : static bool foreign_join_ok(PlannerInfo *root, RelOptInfo *joinrel,
643 : : JoinType jointype, RelOptInfo *outerrel, RelOptInfo *innerrel,
644 : : JoinPathExtraData *extra);
645 : : static bool foreign_grouping_ok(PlannerInfo *root, RelOptInfo *grouped_rel,
646 : : Node *havingQual);
647 : : static List *get_useful_pathkeys_for_relation(PlannerInfo *root,
648 : : RelOptInfo *rel);
649 : : static List *get_useful_ecs_for_relation(PlannerInfo *root, RelOptInfo *rel);
650 : : static Relids get_base_relids(PlannerInfo *root, RelOptInfo *rel);
651 : : static int get_min_base_rti(PlannerInfo *root, RelOptInfo *rel);
652 : : static List *get_functions_data(PlannerInfo *root, RelOptInfo *rel);
653 : : static void add_paths_with_pathkeys_for_rel(PlannerInfo *root, RelOptInfo *rel,
654 : : Path *epq_path, List *restrictlist);
655 : : static void add_foreign_grouping_paths(PlannerInfo *root,
656 : : RelOptInfo *input_rel,
657 : : RelOptInfo *grouped_rel,
658 : : GroupPathExtraData *extra);
659 : : static void add_foreign_ordered_paths(PlannerInfo *root,
660 : : RelOptInfo *input_rel,
661 : : RelOptInfo *ordered_rel);
662 : : static void add_foreign_final_paths(PlannerInfo *root,
663 : : RelOptInfo *input_rel,
664 : : RelOptInfo *final_rel,
665 : : FinalPathExtraData *extra);
666 : : static void apply_server_options(PgFdwRelationInfo *fpinfo);
667 : : static void apply_table_options(PgFdwRelationInfo *fpinfo);
668 : : static void merge_fdw_options(PgFdwRelationInfo *fpinfo,
669 : : const PgFdwRelationInfo *fpinfo_o,
670 : : const PgFdwRelationInfo *fpinfo_i);
671 : : static int get_batch_size_option(Relation rel);
672 : :
673 : :
674 : : /*
675 : : * Foreign-data wrapper handler function: return a struct with pointers
676 : : * to my callback routines.
677 : : */
678 : : Datum
679 : 768 : postgres_fdw_handler(PG_FUNCTION_ARGS)
680 : : {
681 : 768 : FdwRoutine *routine = makeNode(FdwRoutine);
682 : :
683 : : /* Functions for scanning foreign tables */
684 : 768 : routine->GetForeignRelSize = postgresGetForeignRelSize;
685 : 768 : routine->GetForeignPaths = postgresGetForeignPaths;
686 : 768 : routine->GetForeignPlan = postgresGetForeignPlan;
687 : 768 : routine->BeginForeignScan = postgresBeginForeignScan;
688 : 768 : routine->IterateForeignScan = postgresIterateForeignScan;
689 : 768 : routine->ReScanForeignScan = postgresReScanForeignScan;
690 : 768 : routine->EndForeignScan = postgresEndForeignScan;
691 : :
692 : : /* Functions for updating foreign tables */
693 : 768 : routine->AddForeignUpdateTargets = postgresAddForeignUpdateTargets;
694 : 768 : routine->PlanForeignModify = postgresPlanForeignModify;
695 : 768 : routine->BeginForeignModify = postgresBeginForeignModify;
696 : 768 : routine->ExecForeignInsert = postgresExecForeignInsert;
697 : 768 : routine->ExecForeignBatchInsert = postgresExecForeignBatchInsert;
698 : 768 : routine->GetForeignModifyBatchSize = postgresGetForeignModifyBatchSize;
699 : 768 : routine->ExecForeignUpdate = postgresExecForeignUpdate;
700 : 768 : routine->ExecForeignDelete = postgresExecForeignDelete;
701 : 768 : routine->EndForeignModify = postgresEndForeignModify;
702 : 768 : routine->BeginForeignInsert = postgresBeginForeignInsert;
703 : 768 : routine->EndForeignInsert = postgresEndForeignInsert;
704 : 768 : routine->IsForeignRelUpdatable = postgresIsForeignRelUpdatable;
705 : 768 : routine->PlanDirectModify = postgresPlanDirectModify;
706 : 768 : routine->BeginDirectModify = postgresBeginDirectModify;
707 : 768 : routine->IterateDirectModify = postgresIterateDirectModify;
708 : 768 : routine->EndDirectModify = postgresEndDirectModify;
709 : :
710 : : /* Function for EvalPlanQual rechecks */
711 : 768 : routine->RecheckForeignScan = postgresRecheckForeignScan;
712 : : /* Support functions for EXPLAIN */
713 : 768 : routine->ExplainForeignScan = postgresExplainForeignScan;
714 : 768 : routine->ExplainForeignModify = postgresExplainForeignModify;
715 : 768 : routine->ExplainDirectModify = postgresExplainDirectModify;
716 : :
717 : : /* Support function for TRUNCATE */
718 : 768 : routine->ExecForeignTruncate = postgresExecForeignTruncate;
719 : :
720 : : /* Support functions for ANALYZE */
721 : 768 : routine->AnalyzeForeignTable = postgresAnalyzeForeignTable;
722 : 768 : routine->ImportForeignStatistics = postgresImportForeignStatistics;
723 : :
724 : : /* Support functions for IMPORT FOREIGN SCHEMA */
725 : 768 : routine->ImportForeignSchema = postgresImportForeignSchema;
726 : :
727 : : /* Support functions for join push-down */
728 : 768 : routine->GetForeignJoinPaths = postgresGetForeignJoinPaths;
729 : :
730 : : /* Support functions for upper relation push-down */
731 : 768 : routine->GetForeignUpperPaths = postgresGetForeignUpperPaths;
732 : :
733 : : /* Support functions for asynchronous execution */
734 : 768 : routine->IsForeignPathAsyncCapable = postgresIsForeignPathAsyncCapable;
735 : 768 : routine->ForeignAsyncRequest = postgresForeignAsyncRequest;
736 : 768 : routine->ForeignAsyncConfigureWait = postgresForeignAsyncConfigureWait;
737 : 768 : routine->ForeignAsyncNotify = postgresForeignAsyncNotify;
738 : :
739 : 768 : PG_RETURN_POINTER(routine);
740 : : }
741 : :
742 : : /*
743 : : * postgresGetForeignRelSize
744 : : * Estimate # of rows and width of the result of the scan
745 : : *
746 : : * We should consider the effect of all baserestrictinfo clauses here, but
747 : : * not any join clauses.
748 : : */
749 : : static void
750 : 1351 : postgresGetForeignRelSize(PlannerInfo *root,
751 : : RelOptInfo *baserel,
752 : : Oid foreigntableid)
753 : : {
754 : : PgFdwRelationInfo *fpinfo;
755 : : ListCell *lc;
756 : :
757 : : /*
758 : : * We use PgFdwRelationInfo to pass various information to subsequent
759 : : * functions.
760 : : */
761 : 1351 : fpinfo = palloc0_object(PgFdwRelationInfo);
762 : 1351 : baserel->fdw_private = fpinfo;
763 : :
764 : : /* Base foreign tables need to be pushed down always. */
765 : 1351 : fpinfo->pushdown_safe = true;
766 : :
767 : : /* Look up foreign-table catalog info. */
768 : 1351 : fpinfo->table = GetForeignTable(foreigntableid);
769 : 1351 : fpinfo->server = GetForeignServer(fpinfo->table->serverid);
770 : :
771 : : /*
772 : : * Extract user-settable option values. Note that per-table settings of
773 : : * use_remote_estimate, fetch_size and async_capable override per-server
774 : : * settings of them, respectively.
775 : : */
776 : 1351 : fpinfo->use_remote_estimate = false;
777 : 1351 : fpinfo->fdw_startup_cost = DEFAULT_FDW_STARTUP_COST;
778 : 1351 : fpinfo->fdw_tuple_cost = DEFAULT_FDW_TUPLE_COST;
779 : 1351 : fpinfo->shippable_extensions = NIL;
780 : 1351 : fpinfo->fetch_size = 100;
781 : 1351 : fpinfo->async_capable = false;
782 : :
783 : 1351 : apply_server_options(fpinfo);
784 : 1351 : apply_table_options(fpinfo);
785 : :
786 : : /*
787 : : * If the table or the server is configured to use remote estimates,
788 : : * identify which user to do remote access as during planning. This
789 : : * should match what ExecCheckPermissions() does. If we fail due to lack
790 : : * of permissions, the query would have failed at runtime anyway.
791 : : */
792 [ + + ]: 1351 : if (fpinfo->use_remote_estimate)
793 : : {
794 : : Oid userid;
795 : :
796 [ + + ]: 317 : userid = OidIsValid(baserel->userid) ? baserel->userid : GetUserId();
797 : 317 : fpinfo->user = GetUserMapping(userid, fpinfo->server->serverid);
798 : : }
799 : : else
800 : 1034 : fpinfo->user = NULL;
801 : :
802 : : /*
803 : : * Identify which baserestrictinfo clauses can be sent to the remote
804 : : * server and which can't.
805 : : */
806 : 1349 : classifyConditions(root, baserel, fpinfo, baserel->baserestrictinfo,
807 : : &fpinfo->remote_conds, &fpinfo->local_conds);
808 : :
809 : : /*
810 : : * Identify which attributes will need to be retrieved from the remote
811 : : * server. These include all attrs needed for joins or final output, plus
812 : : * all attrs used in the local_conds. (Note: if we end up using a
813 : : * parameterized scan, it's possible that some of the join clauses will be
814 : : * sent to the remote and thus we wouldn't really need to retrieve the
815 : : * columns used in them. Doesn't seem worth detecting that case though.)
816 : : */
817 : 1349 : fpinfo->attrs_used = NULL;
818 : 1349 : pull_varattnos((Node *) baserel->reltarget->exprs, baserel->relid,
819 : : &fpinfo->attrs_used);
820 [ + + + + : 1442 : foreach(lc, fpinfo->local_conds)
+ + ]
821 : : {
822 : 93 : RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc);
823 : :
824 : 93 : pull_varattnos((Node *) rinfo->clause, baserel->relid,
825 : : &fpinfo->attrs_used);
826 : : }
827 : :
828 : : /*
829 : : * Compute the selectivity and cost of the local_conds, so we don't have
830 : : * to do it over again for each path. The best we can do for these
831 : : * conditions is to estimate selectivity on the basis of local statistics.
832 : : */
833 : 2698 : fpinfo->local_conds_sel = clauselist_selectivity(root,
834 : : fpinfo->local_conds,
835 : 1349 : baserel->relid,
836 : : JOIN_INNER,
837 : : NULL);
838 : :
839 : 1349 : cost_qual_eval(&fpinfo->local_conds_cost, fpinfo->local_conds, root);
840 : :
841 : : /*
842 : : * Set # of retrieved rows and cached relation costs to some negative
843 : : * value, so that we can detect when they are set to some sensible values,
844 : : * during one (usually the first) of the calls to estimate_path_cost_size.
845 : : */
846 : 1349 : fpinfo->retrieved_rows = -1;
847 : 1349 : fpinfo->rel_startup_cost = -1;
848 : 1349 : fpinfo->rel_total_cost = -1;
849 : :
850 : : /*
851 : : * If the table or the server is configured to use remote estimates,
852 : : * connect to the foreign server and execute EXPLAIN to estimate the
853 : : * number of rows selected by the restriction clauses, as well as the
854 : : * average row width. Otherwise, estimate using whatever statistics we
855 : : * have locally, in a way similar to ordinary tables.
856 : : */
857 [ + + ]: 1349 : if (fpinfo->use_remote_estimate)
858 : : {
859 : : /*
860 : : * Get cost/size estimates with help of remote server. Save the
861 : : * values in fpinfo so we don't need to do it again to generate the
862 : : * basic foreign path.
863 : : */
864 : 315 : estimate_path_cost_size(root, baserel, NIL, NIL, NULL,
865 : : &fpinfo->rows, &fpinfo->width,
866 : : &fpinfo->disabled_nodes,
867 : : &fpinfo->startup_cost, &fpinfo->total_cost);
868 : :
869 : : /* Report estimated baserel size to planner. */
870 : 315 : baserel->rows = fpinfo->rows;
871 : 315 : baserel->reltarget->width = fpinfo->width;
872 : : }
873 : : else
874 : : {
875 : : /*
876 : : * If the foreign table has never been ANALYZEd, it will have
877 : : * reltuples < 0, meaning "unknown". We can't do much if we're not
878 : : * allowed to consult the remote server, but we can use a hack similar
879 : : * to plancat.c's treatment of empty relations: use a minimum size
880 : : * estimate of 10 pages, and divide by the column-datatype-based width
881 : : * estimate to get the corresponding number of tuples.
882 : : */
883 [ + + ]: 1034 : if (baserel->tuples < 0)
884 : : {
885 : 344 : baserel->pages = 10;
886 : 344 : baserel->tuples =
887 : 344 : (10 * BLCKSZ) / (baserel->reltarget->width +
888 : : MAXALIGN(SizeofHeapTupleHeader));
889 : : }
890 : :
891 : : /* Estimate baserel size as best we can with local statistics. */
892 : 1034 : set_baserel_size_estimates(root, baserel);
893 : :
894 : : /* Fill in basically-bogus cost estimates for use later. */
895 : 1034 : estimate_path_cost_size(root, baserel, NIL, NIL, NULL,
896 : : &fpinfo->rows, &fpinfo->width,
897 : : &fpinfo->disabled_nodes,
898 : : &fpinfo->startup_cost, &fpinfo->total_cost);
899 : : }
900 : :
901 : : /*
902 : : * fpinfo->relation_name gets the numeric rangetable index of the foreign
903 : : * table RTE. (If this query gets EXPLAIN'd, we'll convert that to a
904 : : * human-readable string at that time.)
905 : : */
906 : 1349 : fpinfo->relation_name = psprintf("%u", baserel->relid);
907 : :
908 : : /* No outer and inner relations. */
909 : 1349 : fpinfo->make_outerrel_subquery = false;
910 : 1349 : fpinfo->make_innerrel_subquery = false;
911 : 1349 : fpinfo->lower_subquery_rels = NULL;
912 : 1349 : fpinfo->hidden_subquery_rels = NULL;
913 : : /* Set the relation index. */
914 : 1349 : fpinfo->relation_index = baserel->relid;
915 : 1349 : }
916 : :
917 : : /*
918 : : * get_useful_ecs_for_relation
919 : : * Determine which EquivalenceClasses might be involved in useful
920 : : * orderings of this relation.
921 : : *
922 : : * This function is in some respects a mirror image of the core function
923 : : * pathkeys_useful_for_merging: for a regular table, we know what indexes
924 : : * we have and want to test whether any of them are useful. For a foreign
925 : : * table, we don't know what indexes are present on the remote side but
926 : : * want to speculate about which ones we'd like to use if they existed.
927 : : *
928 : : * This function returns a list of potentially-useful equivalence classes,
929 : : * but it does not guarantee that an EquivalenceMember exists which contains
930 : : * Vars only from the given relation. For example, given ft1 JOIN t1 ON
931 : : * ft1.x + t1.x = 0, this function will say that the equivalence class
932 : : * containing ft1.x + t1.x is potentially useful. Supposing ft1 is remote and
933 : : * t1 is local (or on a different server), it will turn out that no useful
934 : : * ORDER BY clause can be generated. It's not our job to figure that out
935 : : * here; we're only interested in identifying relevant ECs.
936 : : */
937 : : static List *
938 : 542 : get_useful_ecs_for_relation(PlannerInfo *root, RelOptInfo *rel)
939 : : {
940 : 542 : List *useful_eclass_list = NIL;
941 : : ListCell *lc;
942 : : Relids relids;
943 : :
944 : : /*
945 : : * First, consider whether any active EC is potentially useful for a merge
946 : : * join against this relation.
947 : : */
948 [ + + ]: 542 : if (rel->has_eclass_joins)
949 : : {
950 [ + - + + : 704 : foreach(lc, root->eq_classes)
+ + ]
951 : : {
952 : 481 : EquivalenceClass *cur_ec = (EquivalenceClass *) lfirst(lc);
953 : :
954 [ + + ]: 481 : if (eclass_useful_for_merging(root, cur_ec, rel))
955 : 257 : useful_eclass_list = lappend(useful_eclass_list, cur_ec);
956 : : }
957 : : }
958 : :
959 : : /*
960 : : * Next, consider whether there are any non-EC derivable join clauses that
961 : : * are merge-joinable. If the joininfo list is empty, we can exit
962 : : * quickly.
963 : : */
964 [ + + ]: 542 : if (rel->joininfo == NIL)
965 : 400 : return useful_eclass_list;
966 : :
967 : : /* If this is a child rel, we must use the topmost parent rel to search. */
968 [ + + + - : 142 : if (IS_OTHER_REL(rel))
- + ]
969 : : {
970 : : Assert(!bms_is_empty(rel->top_parent_relids));
971 : 20 : relids = rel->top_parent_relids;
972 : : }
973 : : else
974 : 122 : relids = rel->relids;
975 : :
976 : : /* Check each join clause in turn. */
977 [ + - + + : 345 : foreach(lc, rel->joininfo)
+ + ]
978 : : {
979 : 203 : RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(lc);
980 : :
981 : : /* Consider only mergejoinable clauses */
982 [ + + ]: 203 : if (restrictinfo->mergeopfamilies == NIL)
983 : 14 : continue;
984 : :
985 : : /* Make sure we've got canonical ECs. */
986 : 189 : update_mergeclause_eclasses(root, restrictinfo);
987 : :
988 : : /*
989 : : * restrictinfo->mergeopfamilies != NIL is sufficient to guarantee
990 : : * that left_ec and right_ec will be initialized, per comments in
991 : : * distribute_qual_to_rels.
992 : : *
993 : : * We want to identify which side of this merge-joinable clause
994 : : * contains columns from the relation produced by this RelOptInfo. We
995 : : * test for overlap, not containment, because there could be extra
996 : : * relations on either side. For example, suppose we've got something
997 : : * like ((A JOIN B ON A.x = B.x) JOIN C ON A.y = C.y) LEFT JOIN D ON
998 : : * A.y = D.y. The input rel might be the joinrel between A and B, and
999 : : * we'll consider the join clause A.y = D.y. relids contains a
1000 : : * relation not involved in the join class (B) and the equivalence
1001 : : * class for the left-hand side of the clause contains a relation not
1002 : : * involved in the input rel (C). Despite the fact that we have only
1003 : : * overlap and not containment in either direction, A.y is potentially
1004 : : * useful as a sort column.
1005 : : *
1006 : : * Note that it's even possible that relids overlaps neither side of
1007 : : * the join clause. For example, consider A LEFT JOIN B ON A.x = B.x
1008 : : * AND A.x = 1. The clause A.x = 1 will appear in B's joininfo list,
1009 : : * but overlaps neither side of B. In that case, we just skip this
1010 : : * join clause, since it doesn't suggest a useful sort order for this
1011 : : * relation.
1012 : : */
1013 [ + + ]: 189 : if (bms_overlap(relids, restrictinfo->right_ec->ec_relids))
1014 : 86 : useful_eclass_list = list_append_unique_ptr(useful_eclass_list,
1015 : 86 : restrictinfo->right_ec);
1016 [ + + ]: 103 : else if (bms_overlap(relids, restrictinfo->left_ec->ec_relids))
1017 : 94 : useful_eclass_list = list_append_unique_ptr(useful_eclass_list,
1018 : 94 : restrictinfo->left_ec);
1019 : : }
1020 : :
1021 : 142 : return useful_eclass_list;
1022 : : }
1023 : :
1024 : : /*
1025 : : * get_useful_pathkeys_for_relation
1026 : : * Determine which orderings of a relation might be useful.
1027 : : *
1028 : : * Getting data in sorted order can be useful either because the requested
1029 : : * order matches the final output ordering for the overall query we're
1030 : : * planning, or because it enables an efficient merge join. Here, we try
1031 : : * to figure out which pathkeys to consider.
1032 : : */
1033 : : static List *
1034 : 1730 : get_useful_pathkeys_for_relation(PlannerInfo *root, RelOptInfo *rel)
1035 : : {
1036 : 1730 : List *useful_pathkeys_list = NIL;
1037 : : List *useful_eclass_list;
1038 : 1730 : PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) rel->fdw_private;
1039 : 1730 : EquivalenceClass *query_ec = NULL;
1040 : : ListCell *lc;
1041 : :
1042 : : /*
1043 : : * Pushing the query_pathkeys to the remote server is always worth
1044 : : * considering, because it might let us avoid a local sort.
1045 : : */
1046 : 1730 : fpinfo->qp_is_pushdown_safe = false;
1047 [ + + ]: 1730 : if (root->query_pathkeys)
1048 : : {
1049 : 732 : bool query_pathkeys_ok = true;
1050 : :
1051 [ + - + + : 1412 : foreach(lc, root->query_pathkeys)
+ + ]
1052 : : {
1053 : 929 : PathKey *pathkey = (PathKey *) lfirst(lc);
1054 : :
1055 : : /*
1056 : : * The planner and executor don't have any clever strategy for
1057 : : * taking data sorted by a prefix of the query's pathkeys and
1058 : : * getting it to be sorted by all of those pathkeys. We'll just
1059 : : * end up resorting the entire data set. So, unless we can push
1060 : : * down all of the query pathkeys, forget it.
1061 : : */
1062 [ + + ]: 929 : if (!is_foreign_pathkey(root, rel, pathkey))
1063 : : {
1064 : 249 : query_pathkeys_ok = false;
1065 : 249 : break;
1066 : : }
1067 : : }
1068 : :
1069 [ + + ]: 732 : if (query_pathkeys_ok)
1070 : : {
1071 : 483 : useful_pathkeys_list = list_make1(list_copy(root->query_pathkeys));
1072 : 483 : fpinfo->qp_is_pushdown_safe = true;
1073 : : }
1074 : : }
1075 : :
1076 : : /*
1077 : : * Even if we're not using remote estimates, having the remote side do the
1078 : : * sort generally won't be any worse than doing it locally, and it might
1079 : : * be much better if the remote side can generate data in the right order
1080 : : * without needing a sort at all. However, what we're going to do next is
1081 : : * try to generate pathkeys that seem promising for possible merge joins,
1082 : : * and that's more speculative. A wrong choice might hurt quite a bit, so
1083 : : * bail out if we can't use remote estimates.
1084 : : */
1085 [ + + ]: 1730 : if (!fpinfo->use_remote_estimate)
1086 : 1188 : return useful_pathkeys_list;
1087 : :
1088 : : /* Get the list of interesting EquivalenceClasses. */
1089 : 542 : useful_eclass_list = get_useful_ecs_for_relation(root, rel);
1090 : :
1091 : : /* Extract unique EC for query, if any, so we don't consider it again. */
1092 [ + + ]: 542 : if (list_length(root->query_pathkeys) == 1)
1093 : : {
1094 : 181 : PathKey *query_pathkey = linitial(root->query_pathkeys);
1095 : :
1096 : 181 : query_ec = query_pathkey->pk_eclass;
1097 : : }
1098 : :
1099 : : /*
1100 : : * As a heuristic, the only pathkeys we consider here are those of length
1101 : : * one. It's surely possible to consider more, but since each one we
1102 : : * choose to consider will generate a round-trip to the remote side, we
1103 : : * need to be a bit cautious here. It would sure be nice to have a local
1104 : : * cache of information about remote index definitions...
1105 : : */
1106 [ + + + + : 952 : foreach(lc, useful_eclass_list)
+ + ]
1107 : : {
1108 : 410 : EquivalenceClass *cur_ec = lfirst(lc);
1109 : : PathKey *pathkey;
1110 : :
1111 : : /* If redundant with what we did above, skip it. */
1112 [ + + ]: 410 : if (cur_ec == query_ec)
1113 : 33 : continue;
1114 : :
1115 : : /* Can't push down the sort if the EC's opfamily is not shippable. */
1116 [ - + ]: 377 : if (!is_shippable(linitial_oid(cur_ec->ec_opfamilies),
1117 : : OperatorFamilyRelationId, fpinfo))
1118 : 0 : continue;
1119 : :
1120 : : /* If no pushable expression for this rel, skip it. */
1121 [ + + ]: 377 : if (find_em_for_rel(root, cur_ec, rel) == NULL)
1122 : 50 : continue;
1123 : :
1124 : : /* Looks like we can generate a pathkey, so let's do it. */
1125 : 327 : pathkey = make_canonical_pathkey(root, cur_ec,
1126 : 327 : linitial_oid(cur_ec->ec_opfamilies),
1127 : : COMPARE_LT,
1128 : : false);
1129 : 327 : useful_pathkeys_list = lappend(useful_pathkeys_list,
1130 : 327 : list_make1(pathkey));
1131 : : }
1132 : :
1133 : 542 : return useful_pathkeys_list;
1134 : : }
1135 : :
1136 : : /*
1137 : : * postgresGetForeignPaths
1138 : : * Create possible scan paths for a scan on the foreign table
1139 : : */
1140 : : static void
1141 : 1349 : postgresGetForeignPaths(PlannerInfo *root,
1142 : : RelOptInfo *baserel,
1143 : : Oid foreigntableid)
1144 : : {
1145 : 1349 : PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) baserel->fdw_private;
1146 : : ForeignPath *path;
1147 : : List *ppi_list;
1148 : : ListCell *lc;
1149 : :
1150 : : /*
1151 : : * Create simplest ForeignScan path node and add it to baserel. This path
1152 : : * corresponds to SeqScan path of regular tables (though depending on what
1153 : : * baserestrict conditions we were able to send to remote, there might
1154 : : * actually be an indexscan happening there). We already did all the work
1155 : : * to estimate cost and size of this path.
1156 : : *
1157 : : * Although this path uses no join clauses, it could still have required
1158 : : * parameterization due to LATERAL refs in its tlist.
1159 : : */
1160 : 1349 : path = create_foreignscan_path(root, baserel,
1161 : : NULL, /* default pathtarget */
1162 : : fpinfo->rows,
1163 : : fpinfo->disabled_nodes,
1164 : : fpinfo->startup_cost,
1165 : : fpinfo->total_cost,
1166 : : NIL, /* no pathkeys */
1167 : : baserel->lateral_relids,
1168 : : NULL, /* no extra plan */
1169 : : NIL, /* no fdw_restrictinfo list */
1170 : : NIL); /* no fdw_private list */
1171 : 1349 : add_path(baserel, (Path *) path);
1172 : :
1173 : : /* Add paths with pathkeys */
1174 : 1349 : add_paths_with_pathkeys_for_rel(root, baserel, NULL, NIL);
1175 : :
1176 : : /*
1177 : : * If we're not using remote estimates, stop here. We have no way to
1178 : : * estimate whether any join clauses would be worth sending across, so
1179 : : * don't bother building parameterized paths.
1180 : : */
1181 [ + + ]: 1349 : if (!fpinfo->use_remote_estimate)
1182 : 1034 : return;
1183 : :
1184 : : /*
1185 : : * Thumb through all join clauses for the rel to identify which outer
1186 : : * relations could supply one or more safe-to-send-to-remote join clauses.
1187 : : * We'll build a parameterized path for each such outer relation.
1188 : : *
1189 : : * It's convenient to manage this by representing each candidate outer
1190 : : * relation by the ParamPathInfo node for it. We can then use the
1191 : : * ppi_clauses list in the ParamPathInfo node directly as a list of the
1192 : : * interesting join clauses for that rel. This takes care of the
1193 : : * possibility that there are multiple safe join clauses for such a rel,
1194 : : * and also ensures that we account for unsafe join clauses that we'll
1195 : : * still have to enforce locally (since the parameterized-path machinery
1196 : : * insists that we handle all movable clauses).
1197 : : */
1198 : 315 : ppi_list = NIL;
1199 [ + + + + : 456 : foreach(lc, baserel->joininfo)
+ + ]
1200 : : {
1201 : 141 : RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
1202 : : Relids required_outer;
1203 : : ParamPathInfo *param_info;
1204 : :
1205 : : /* Check if clause can be moved to this rel */
1206 [ + + ]: 141 : if (!join_clause_is_movable_to(rinfo, baserel))
1207 : 96 : continue;
1208 : :
1209 : : /* See if it is safe to send to remote */
1210 [ + + ]: 45 : if (!is_foreign_expr(root, baserel, fpinfo, rinfo->clause))
1211 : 7 : continue;
1212 : :
1213 : : /* Calculate required outer rels for the resulting path */
1214 : 38 : required_outer = bms_union(rinfo->clause_relids,
1215 : 38 : baserel->lateral_relids);
1216 : : /* We do not want the foreign rel itself listed in required_outer */
1217 : 38 : required_outer = bms_del_member(required_outer, baserel->relid);
1218 : :
1219 : : /*
1220 : : * required_outer probably can't be empty here, but if it were, we
1221 : : * couldn't make a parameterized path.
1222 : : */
1223 [ - + ]: 38 : if (bms_is_empty(required_outer))
1224 : 0 : continue;
1225 : :
1226 : : /* Get the ParamPathInfo */
1227 : 38 : param_info = get_baserel_parampathinfo(root, baserel,
1228 : : required_outer);
1229 : : Assert(param_info != NULL);
1230 : :
1231 : : /*
1232 : : * Add it to list unless we already have it. Testing pointer equality
1233 : : * is OK since get_baserel_parampathinfo won't make duplicates.
1234 : : */
1235 : 38 : ppi_list = list_append_unique_ptr(ppi_list, param_info);
1236 : : }
1237 : :
1238 : : /*
1239 : : * The above scan examined only "generic" join clauses, not those that
1240 : : * were absorbed into EquivalenceClauses. See if we can make anything out
1241 : : * of EquivalenceClauses.
1242 : : */
1243 [ + + ]: 315 : if (baserel->has_eclass_joins)
1244 : : {
1245 : : /*
1246 : : * We repeatedly scan the eclass list looking for column references
1247 : : * (or expressions) belonging to the foreign rel. Each time we find
1248 : : * one, we generate a list of equivalence joinclauses for it, and then
1249 : : * see if any are safe to send to the remote. Repeat till there are
1250 : : * no more candidate EC members.
1251 : : */
1252 : : ec_member_foreign_arg arg;
1253 : :
1254 : 147 : arg.already_used = NIL;
1255 : : for (;;)
1256 : 149 : {
1257 : : List *clauses;
1258 : :
1259 : : /* Make clauses, skipping any that join to lateral_referencers */
1260 : 296 : arg.current = NULL;
1261 : 296 : clauses = generate_implied_equalities_for_column(root,
1262 : : baserel,
1263 : : ec_member_matches_foreign,
1264 : : &arg,
1265 : : baserel->lateral_referencers);
1266 : :
1267 : : /* Done if there are no more expressions in the foreign rel */
1268 [ + + ]: 296 : if (arg.current == NULL)
1269 : : {
1270 : : Assert(clauses == NIL);
1271 : 147 : break;
1272 : : }
1273 : :
1274 : : /* Scan the extracted join clauses */
1275 [ + - + + : 334 : foreach(lc, clauses)
+ + ]
1276 : : {
1277 : 185 : RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
1278 : : Relids required_outer;
1279 : : ParamPathInfo *param_info;
1280 : :
1281 : : /* Check if clause can be moved to this rel */
1282 [ - + ]: 185 : if (!join_clause_is_movable_to(rinfo, baserel))
1283 : 0 : continue;
1284 : :
1285 : : /* See if it is safe to send to remote */
1286 [ + + ]: 185 : if (!is_foreign_expr(root, baserel, fpinfo, rinfo->clause))
1287 : 7 : continue;
1288 : :
1289 : : /* Calculate required outer rels for the resulting path */
1290 : 178 : required_outer = bms_union(rinfo->clause_relids,
1291 : 178 : baserel->lateral_relids);
1292 : 178 : required_outer = bms_del_member(required_outer, baserel->relid);
1293 [ - + ]: 178 : if (bms_is_empty(required_outer))
1294 : 0 : continue;
1295 : :
1296 : : /* Get the ParamPathInfo */
1297 : 178 : param_info = get_baserel_parampathinfo(root, baserel,
1298 : : required_outer);
1299 : : Assert(param_info != NULL);
1300 : :
1301 : : /* Add it to list unless we already have it */
1302 : 178 : ppi_list = list_append_unique_ptr(ppi_list, param_info);
1303 : : }
1304 : :
1305 : : /* Try again, now ignoring the expression we found this time */
1306 : 149 : arg.already_used = lappend(arg.already_used, arg.current);
1307 : : }
1308 : : }
1309 : :
1310 : : /*
1311 : : * Now build a path for each useful outer relation.
1312 : : */
1313 [ + + + + : 521 : foreach(lc, ppi_list)
+ + ]
1314 : : {
1315 : 206 : ParamPathInfo *param_info = (ParamPathInfo *) lfirst(lc);
1316 : : double rows;
1317 : : int width;
1318 : : int disabled_nodes;
1319 : : Cost startup_cost;
1320 : : Cost total_cost;
1321 : :
1322 : : /* Get a cost estimate from the remote */
1323 : 206 : estimate_path_cost_size(root, baserel,
1324 : : param_info->ppi_clauses, NIL, NULL,
1325 : : &rows, &width, &disabled_nodes,
1326 : : &startup_cost, &total_cost);
1327 : :
1328 : : /*
1329 : : * ppi_rows currently won't get looked at by anything, but still we
1330 : : * may as well ensure that it matches our idea of the rowcount.
1331 : : */
1332 : 206 : param_info->ppi_rows = rows;
1333 : :
1334 : : /* Make the path */
1335 : 206 : path = create_foreignscan_path(root, baserel,
1336 : : NULL, /* default pathtarget */
1337 : : rows,
1338 : : disabled_nodes,
1339 : : startup_cost,
1340 : : total_cost,
1341 : : NIL, /* no pathkeys */
1342 : : param_info->ppi_req_outer,
1343 : : NULL,
1344 : : NIL, /* no fdw_restrictinfo list */
1345 : : NIL); /* no fdw_private list */
1346 : 206 : add_path(baserel, (Path *) path);
1347 : : }
1348 : : }
1349 : :
1350 : : /*
1351 : : * postgresGetForeignPlan
1352 : : * Create ForeignScan plan node which implements selected best path
1353 : : */
1354 : : static ForeignScan *
1355 : 1151 : postgresGetForeignPlan(PlannerInfo *root,
1356 : : RelOptInfo *foreignrel,
1357 : : Oid foreigntableid,
1358 : : ForeignPath *best_path,
1359 : : List *tlist,
1360 : : List *scan_clauses,
1361 : : Plan *outer_plan)
1362 : : {
1363 : 1151 : PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) foreignrel->fdw_private;
1364 : : Index scan_relid;
1365 : : List *fdw_private;
1366 : 1151 : List *remote_exprs = NIL;
1367 : 1151 : List *local_exprs = NIL;
1368 : 1151 : List *params_list = NIL;
1369 : 1151 : List *fdw_scan_tlist = NIL;
1370 : 1151 : List *fdw_recheck_quals = NIL;
1371 : : List *retrieved_attrs;
1372 : : StringInfoData sql;
1373 : 1151 : bool has_final_sort = false;
1374 : 1151 : bool has_limit = false;
1375 : : ListCell *lc;
1376 : :
1377 : : /*
1378 : : * Get FDW private data created by postgresGetForeignUpperPaths(), if any.
1379 : : */
1380 [ + + ]: 1151 : if (best_path->fdw_private)
1381 : : {
1382 : 157 : has_final_sort = boolVal(list_nth(best_path->fdw_private,
1383 : : FdwPathPrivateHasFinalSort));
1384 : 157 : has_limit = boolVal(list_nth(best_path->fdw_private,
1385 : : FdwPathPrivateHasLimit));
1386 : : }
1387 : :
1388 [ + + + + ]: 1151 : if (IS_SIMPLE_REL(foreignrel))
1389 : : {
1390 : : /*
1391 : : * For base relations, set scan_relid as the relid of the relation.
1392 : : */
1393 : 826 : scan_relid = foreignrel->relid;
1394 : :
1395 : : /*
1396 : : * In a base-relation scan, we must apply the given scan_clauses.
1397 : : *
1398 : : * Separate the scan_clauses into those that can be executed remotely
1399 : : * and those that can't. baserestrictinfo clauses that were
1400 : : * previously determined to be safe or unsafe by classifyConditions
1401 : : * are found in fpinfo->remote_conds and fpinfo->local_conds. Anything
1402 : : * else in the scan_clauses list will be a join clause, which we have
1403 : : * to check for remote-safety.
1404 : : *
1405 : : * Note: the join clauses we see here should be the exact same ones
1406 : : * previously examined by postgresGetForeignPaths. Possibly it'd be
1407 : : * worth passing forward the classification work done then, rather
1408 : : * than repeating it here.
1409 : : *
1410 : : * This code must match "extract_actual_clauses(scan_clauses, false)"
1411 : : * except for the additional decision about remote versus local
1412 : : * execution.
1413 : : */
1414 [ + + + + : 1246 : foreach(lc, scan_clauses)
+ + ]
1415 : : {
1416 : 420 : RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc);
1417 : :
1418 : : /* Ignore any pseudoconstants, they're dealt with elsewhere */
1419 [ + + ]: 420 : if (rinfo->pseudoconstant)
1420 : 4 : continue;
1421 : :
1422 [ + + ]: 416 : if (list_member_ptr(fpinfo->remote_conds, rinfo))
1423 : 312 : remote_exprs = lappend(remote_exprs, rinfo->clause);
1424 [ + + ]: 104 : else if (list_member_ptr(fpinfo->local_conds, rinfo))
1425 : 89 : local_exprs = lappend(local_exprs, rinfo->clause);
1426 [ + + ]: 15 : else if (is_foreign_expr(root, foreignrel, fpinfo, rinfo->clause))
1427 : 13 : remote_exprs = lappend(remote_exprs, rinfo->clause);
1428 : : else
1429 : 2 : local_exprs = lappend(local_exprs, rinfo->clause);
1430 : : }
1431 : :
1432 : : /*
1433 : : * For a base-relation scan, we have to support EPQ recheck, which
1434 : : * should recheck all the remote quals.
1435 : : */
1436 : 826 : fdw_recheck_quals = remote_exprs;
1437 : : }
1438 : : else
1439 : : {
1440 : : /*
1441 : : * Join relation or upper relation - set scan_relid to 0.
1442 : : */
1443 : 325 : scan_relid = 0;
1444 : :
1445 : : /*
1446 : : * For a join rel, baserestrictinfo is NIL and we are not considering
1447 : : * parameterization right now, so there should be no scan_clauses for
1448 : : * a joinrel or an upper rel either.
1449 : : */
1450 : : Assert(!scan_clauses);
1451 : :
1452 : : /*
1453 : : * Instead we get the conditions to apply from the fdw_private
1454 : : * structure.
1455 : : */
1456 : 325 : remote_exprs = extract_actual_clauses(fpinfo->remote_conds, false);
1457 : 325 : local_exprs = extract_actual_clauses(fpinfo->local_conds, false);
1458 : :
1459 : : /*
1460 : : * We leave fdw_recheck_quals empty in this case, since we never need
1461 : : * to apply EPQ recheck clauses. In the case of a joinrel, EPQ
1462 : : * recheck is handled elsewhere --- see postgresGetForeignJoinPaths().
1463 : : * If we're planning an upperrel (ie, remote grouping or aggregation)
1464 : : * then there's no EPQ to do because SELECT FOR UPDATE wouldn't be
1465 : : * allowed, and indeed we *can't* put the remote clauses into
1466 : : * fdw_recheck_quals because the unaggregated Vars won't be available
1467 : : * locally.
1468 : : */
1469 : :
1470 : : /* Build the list of columns to be fetched from the foreign server. */
1471 : 325 : fdw_scan_tlist = build_tlist_to_deparse(foreignrel);
1472 : :
1473 : : /*
1474 : : * Ensure that the outer plan produces a tuple whose descriptor
1475 : : * matches our scan tuple slot. Also, remove the local conditions
1476 : : * from outer plan's quals, lest they be evaluated twice, once by the
1477 : : * local plan and once by the scan.
1478 : : */
1479 [ + + ]: 325 : if (outer_plan)
1480 : : {
1481 : : /*
1482 : : * Right now, we only consider grouping and aggregation beyond
1483 : : * joins. Queries involving aggregates or grouping do not require
1484 : : * EPQ mechanism, hence should not have an outer plan here.
1485 : : */
1486 : : Assert(!IS_UPPER_REL(foreignrel));
1487 : :
1488 : : /*
1489 : : * First, update the plan's qual list if possible. In some cases
1490 : : * the quals might be enforced below the topmost plan level, in
1491 : : * which case we'll fail to remove them; it's not worth working
1492 : : * harder than this.
1493 : : */
1494 [ + + + + : 32 : foreach(lc, local_exprs)
+ + ]
1495 : : {
1496 : 3 : Node *qual = lfirst(lc);
1497 : :
1498 : 3 : outer_plan->qual = list_delete(outer_plan->qual, qual);
1499 : :
1500 : : /*
1501 : : * For an inner join the local conditions of foreign scan plan
1502 : : * can be part of the joinquals as well. (They might also be
1503 : : * in the mergequals or hashquals, but we can't touch those
1504 : : * without breaking the plan.)
1505 : : */
1506 [ + + ]: 3 : if (IsA(outer_plan, NestLoop) ||
1507 [ + - ]: 1 : IsA(outer_plan, MergeJoin) ||
1508 [ - + ]: 1 : IsA(outer_plan, HashJoin))
1509 : : {
1510 : 2 : Join *join_plan = (Join *) outer_plan;
1511 : :
1512 [ + - ]: 2 : if (join_plan->jointype == JOIN_INNER)
1513 : 2 : join_plan->joinqual = list_delete(join_plan->joinqual,
1514 : : qual);
1515 : : }
1516 : : }
1517 : :
1518 : : /*
1519 : : * Now fix the subplan's tlist --- this might result in inserting
1520 : : * a Result node atop the plan tree.
1521 : : */
1522 : 29 : outer_plan = change_plan_targetlist(outer_plan, fdw_scan_tlist,
1523 : 29 : best_path->path.parallel_safe);
1524 : : }
1525 : : }
1526 : :
1527 : : /*
1528 : : * Build the query string to be sent for execution, and identify
1529 : : * expressions to be sent as parameters.
1530 : : */
1531 : 1151 : initStringInfo(&sql);
1532 : 1151 : deparseSelectStmtForRel(&sql, root, foreignrel, fdw_scan_tlist,
1533 : : remote_exprs, best_path->path.pathkeys,
1534 : : has_final_sort, has_limit, false,
1535 : : &retrieved_attrs, ¶ms_list);
1536 : :
1537 : : /* Remember remote_exprs for possible use by postgresPlanDirectModify */
1538 : 1151 : fpinfo->final_remote_exprs = remote_exprs;
1539 : :
1540 : : /*
1541 : : * Build the fdw_private list that will be available to the executor.
1542 : : * Items in the list must match order in enum FdwScanPrivateIndex.
1543 : : */
1544 : 1151 : fdw_private = list_make3(makeString(sql.data),
1545 : : retrieved_attrs,
1546 : : makeInteger(fpinfo->fetch_size));
1547 : :
1548 : : /*
1549 : : * Position FdwScanPrivateRelations: either the EXPLAIN relation string
1550 : : * (joins/upper rels) or a NULL placeholder, so that subsequent indexes
1551 : : * stay valid for the base-rel scan case.
1552 : : */
1553 [ + + + + : 1151 : if (IS_JOIN_REL(foreignrel) || IS_UPPER_REL(foreignrel))
+ + + + ]
1554 : 325 : fdw_private = lappend(fdw_private,
1555 : 325 : makeString(fpinfo->relation_name));
1556 : : else
1557 : 826 : fdw_private = lappend(fdw_private, NULL);
1558 : :
1559 : : /*
1560 : : * FdwScanPrivateFunctions / FdwScanPrivateMinRTIndex carry the metadata
1561 : : * the executor needs to rebuild TupleDesc entries for whole-row Vars
1562 : : * pointing at RTE_FUNCTION rels absorbed into the foreign scan.
1563 : : */
1564 : 1151 : fdw_private = lappend(fdw_private, get_functions_data(root, foreignrel));
1565 : 1151 : fdw_private = lappend(fdw_private,
1566 : 1151 : makeInteger(get_min_base_rti(root, foreignrel)));
1567 : :
1568 : : /*
1569 : : * Create the ForeignScan node for the given relation.
1570 : : *
1571 : : * Note that the remote parameter expressions are stored in the fdw_exprs
1572 : : * field of the finished plan node; we can't keep them in private state
1573 : : * because then they wouldn't be subject to later planner processing.
1574 : : */
1575 : 1151 : return make_foreignscan(tlist,
1576 : : local_exprs,
1577 : : scan_relid,
1578 : : params_list,
1579 : : fdw_private,
1580 : : fdw_scan_tlist,
1581 : : fdw_recheck_quals,
1582 : : outer_plan);
1583 : : }
1584 : :
1585 : : /*
1586 : : * Construct a tuple descriptor for the scan tuples handled by a foreign join.
1587 : : *
1588 : : * 'rtfuncdata' is the FdwScanPrivateFunctions list saved at plan time, and
1589 : : * 'rtoffset' is the difference between the executor's RT indexes and the
1590 : : * scan-local RT indexes captured in that list. Both may be 0/NIL when the
1591 : : * scan has no RTE_FUNCTION dependents.
1592 : : */
1593 : : static TupleDesc
1594 : 181 : get_tupdesc_for_join_scan_tuples(ForeignScanState *node,
1595 : : List *rtfuncdata, int rtoffset)
1596 : : {
1597 : 181 : ForeignScan *fsplan = (ForeignScan *) node->ss.ps.plan;
1598 : 181 : EState *estate = node->ss.ps.state;
1599 : : TupleDesc tupdesc;
1600 : :
1601 : : /*
1602 : : * The core code has already set up a scan tuple slot based on
1603 : : * fsplan->fdw_scan_tlist, and this slot's tupdesc is mostly good enough,
1604 : : * but there's one case where it isn't. If we have any whole-row row
1605 : : * identifier Vars, they may have vartype RECORD, and we need to replace
1606 : : * that with the associated table's actual composite type. This ensures
1607 : : * that when we read those ROW() expression values from the remote server,
1608 : : * we can convert them to a composite type the local server knows.
1609 : : */
1610 : 181 : tupdesc = CreateTupleDescCopy(node->ss.ss_ScanTupleSlot->tts_tupleDescriptor);
1611 [ + + ]: 760 : for (int i = 0; i < tupdesc->natts; i++)
1612 : : {
1613 : 579 : Form_pg_attribute att = TupleDescAttr(tupdesc, i);
1614 : : Var *var;
1615 : : RangeTblEntry *rte;
1616 : : Oid reltype;
1617 : :
1618 : : /* Nothing to do if it's not a generic RECORD attribute */
1619 [ + + - + ]: 579 : if (att->atttypid != RECORDOID || att->atttypmod >= 0)
1620 : 569 : continue;
1621 : :
1622 : : /*
1623 : : * If we can't identify the referenced table, do nothing. This'll
1624 : : * likely lead to failure later, but perhaps we can muddle through.
1625 : : */
1626 : 10 : var = (Var *) list_nth_node(TargetEntry, fsplan->fdw_scan_tlist,
1627 : : i)->expr;
1628 [ + - - + ]: 10 : if (!IsA(var, Var) || var->varattno != 0)
1629 : 0 : continue;
1630 : 10 : rte = list_nth(estate->es_range_table, var->varno - 1);
1631 : :
1632 [ + + ]: 10 : if (rte->rtekind == RTE_RELATION)
1633 : : {
1634 : 5 : reltype = get_rel_type_id(rte->relid);
1635 [ - + ]: 5 : if (!OidIsValid(reltype))
1636 : 0 : continue;
1637 : 5 : att->atttypid = reltype;
1638 : : /* shouldn't need to change anything else */
1639 : : }
1640 [ + - ]: 5 : else if (rte->rtekind == RTE_FUNCTION)
1641 : : {
1642 : : /*
1643 : : * A whole-row Var points at a FUNCTION RTE absorbed into the
1644 : : * foreign join. Synthesize an anonymous composite TupleDesc from
1645 : : * the per-function return-type metadata we saved at plan time;
1646 : : * the deparser emits these as ROW(f<rti>.c1, f<rti>.c2, ...).
1647 : : *
1648 : : * For an upperrel scan (the only path that reaches here)
1649 : : * postgresGetForeignPlan always builds rtfuncdata via
1650 : : * get_functions_data(), so it is never NIL; the per-RTE slot for
1651 : : * the function RTE referenced by this Var must likewise be
1652 : : * populated.
1653 : : */
1654 : : List *funcdata;
1655 : : TupleDesc rte_tupdesc;
1656 : : int num_funcs;
1657 : : int attnum;
1658 : : ListCell *lc1,
1659 : : *lc2;
1660 : :
1661 : : Assert(rtfuncdata != NIL);
1662 : 5 : funcdata = list_nth(rtfuncdata, var->varno - rtoffset);
1663 : : Assert(funcdata != NIL);
1664 : 5 : num_funcs = list_length(funcdata);
1665 : : Assert(num_funcs == list_length(rte->eref->colnames));
1666 : 5 : rte_tupdesc = CreateTemplateTupleDesc(num_funcs);
1667 : :
1668 : 5 : attnum = 1;
1669 [ + - + + : 14 : forboth(lc1, funcdata, lc2, rte->eref->colnames)
+ - + + +
+ + - +
+ ]
1670 : : {
1671 : 9 : List *fdata = lfirst_node(List, lc1);
1672 : 9 : char *colname = strVal(lfirst(lc2));
1673 : : Oid funcrettype;
1674 : : Oid funccollation;
1675 : :
1676 : 9 : funcrettype = lsecond_node(Integer, fdata)->ival;
1677 : 9 : funccollation = lthird_node(Integer, fdata)->ival;
1678 : :
1679 : : /* get_functions_data() already validated the return type. */
1680 : : Assert(OidIsValid(funcrettype) && funcrettype != RECORDOID);
1681 : :
1682 : 9 : TupleDescInitEntry(rte_tupdesc, (AttrNumber) attnum, colname,
1683 : : funcrettype, -1, 0);
1684 : 9 : TupleDescInitEntryCollation(rte_tupdesc, (AttrNumber) attnum,
1685 : : funccollation);
1686 : 9 : attnum++;
1687 : : }
1688 : :
1689 : 5 : assign_record_type_typmod(rte_tupdesc);
1690 : 5 : att->atttypmod = rte_tupdesc->tdtypmod;
1691 : : }
1692 : : }
1693 : 181 : return tupdesc;
1694 : : }
1695 : :
1696 : : /*
1697 : : * postgresBeginForeignScan
1698 : : * Initiate an executor scan of a foreign PostgreSQL table.
1699 : : */
1700 : : static void
1701 : 1045 : postgresBeginForeignScan(ForeignScanState *node, int eflags)
1702 : : {
1703 : 1045 : ForeignScan *fsplan = (ForeignScan *) node->ss.ps.plan;
1704 : 1045 : EState *estate = node->ss.ps.state;
1705 : : PgFdwScanState *fsstate;
1706 : : RangeTblEntry *rte;
1707 : : Oid userid;
1708 : : ForeignTable *table;
1709 : : UserMapping *user;
1710 : : int rtindex;
1711 : : int numParams;
1712 : :
1713 : : /*
1714 : : * Do nothing in EXPLAIN (no ANALYZE) case. node->fdw_state stays NULL.
1715 : : */
1716 [ + + ]: 1045 : if (eflags & EXEC_FLAG_EXPLAIN_ONLY)
1717 : 457 : return;
1718 : :
1719 : : /*
1720 : : * We'll save private state in node->fdw_state.
1721 : : */
1722 : 588 : fsstate = palloc0_object(PgFdwScanState);
1723 : 588 : node->fdw_state = fsstate;
1724 : :
1725 : : /*
1726 : : * Identify which user to do the remote access as. This should match what
1727 : : * ExecCheckPermissions() does. For a join, scan the base relids until we
1728 : : * find an RTE_RELATION (the foreign-table side); ignore any RTE_FUNCTION
1729 : : * absorbed into the join, which contributes no relation OID to look up.
1730 : : */
1731 [ + + ]: 588 : userid = OidIsValid(fsplan->checkAsUser) ? fsplan->checkAsUser : GetUserId();
1732 : 588 : rte = NULL;
1733 [ + + ]: 588 : if (fsplan->scan.scanrelid > 0)
1734 : : {
1735 : 407 : rtindex = fsplan->scan.scanrelid;
1736 : 407 : rte = exec_rt_fetch(rtindex, estate);
1737 : : }
1738 : : else
1739 : : {
1740 : 181 : rtindex = -1;
1741 [ + - ]: 184 : while ((rtindex = bms_next_member(fsplan->fs_base_relids, rtindex)) >= 0)
1742 : : {
1743 : 184 : rte = exec_rt_fetch(rtindex, estate);
1744 [ + - + + ]: 184 : if (rte != NULL && rte->rtekind == RTE_RELATION)
1745 : 181 : break;
1746 : 3 : rte = NULL;
1747 : : }
1748 [ - + ]: 181 : if (rte == NULL)
1749 [ # # ]: 0 : elog(ERROR, "could not locate a foreign relation RTE in foreign scan");
1750 : : }
1751 : :
1752 : : /* Get info about foreign table. */
1753 : 588 : table = GetForeignTable(rte->relid);
1754 : 588 : user = GetUserMapping(userid, table->serverid);
1755 : :
1756 : : /*
1757 : : * Get connection to the foreign server. Connection manager will
1758 : : * establish new connection if necessary.
1759 : : */
1760 : 588 : fsstate->conn = GetConnection(user, false, &fsstate->conn_state);
1761 : :
1762 : : /* Assign a unique ID for my cursor */
1763 : 577 : fsstate->cursor_number = GetCursorNumber(fsstate->conn);
1764 : 577 : fsstate->cursor_exists = false;
1765 : :
1766 : : /* Get private info created by planner functions. */
1767 : 577 : fsstate->query = strVal(list_nth(fsplan->fdw_private,
1768 : : FdwScanPrivateSelectSql));
1769 : 577 : fsstate->retrieved_attrs = (List *) list_nth(fsplan->fdw_private,
1770 : : FdwScanPrivateRetrievedAttrs);
1771 : 577 : fsstate->fetch_size = intVal(list_nth(fsplan->fdw_private,
1772 : : FdwScanPrivateFetchSize));
1773 : :
1774 : : /* Create contexts for batches of tuples and per-tuple temp workspace. */
1775 : 577 : fsstate->batch_cxt = AllocSetContextCreate(estate->es_query_cxt,
1776 : : "postgres_fdw tuple data",
1777 : : ALLOCSET_DEFAULT_SIZES);
1778 : 577 : fsstate->temp_cxt = AllocSetContextCreate(estate->es_query_cxt,
1779 : : "postgres_fdw temporary data",
1780 : : ALLOCSET_SMALL_SIZES);
1781 : :
1782 : : /*
1783 : : * Get info we'll need for converting data fetched from the foreign server
1784 : : * into local representation and error reporting during that process.
1785 : : */
1786 [ + + ]: 577 : if (fsplan->scan.scanrelid > 0)
1787 : : {
1788 : 398 : fsstate->rel = node->ss.ss_currentRelation;
1789 : 398 : fsstate->tupdesc = RelationGetDescr(fsstate->rel);
1790 : : }
1791 : : else
1792 : : {
1793 : 179 : List *rtfuncdata = (List *) list_nth(fsplan->fdw_private,
1794 : : FdwScanPrivateFunctions);
1795 : 179 : int min_base_rti = intVal(list_nth(fsplan->fdw_private,
1796 : : FdwScanPrivateMinRTIndex));
1797 : 179 : int rtoffset = bms_next_member(fsplan->fs_base_relids, -1) -
1798 : : min_base_rti;
1799 : :
1800 : : Assert(min_base_rti > 0);
1801 : : Assert(rtoffset >= 0);
1802 : :
1803 : 179 : fsstate->rel = NULL;
1804 : 179 : fsstate->tupdesc = get_tupdesc_for_join_scan_tuples(node, rtfuncdata,
1805 : : rtoffset);
1806 : : }
1807 : :
1808 : 577 : fsstate->attinmeta = TupleDescGetAttInMetadata(fsstate->tupdesc);
1809 : :
1810 : : /*
1811 : : * Prepare for processing of parameters used in remote query, if any.
1812 : : */
1813 : 577 : numParams = list_length(fsplan->fdw_exprs);
1814 : 577 : fsstate->numParams = numParams;
1815 [ + + ]: 577 : if (numParams > 0)
1816 : 39 : prepare_query_params((PlanState *) node,
1817 : : fsplan->fdw_exprs,
1818 : : numParams,
1819 : : &fsstate->param_flinfo,
1820 : : &fsstate->param_exprs,
1821 : : &fsstate->param_values);
1822 : :
1823 : : /* Set the async-capable flag */
1824 : 577 : fsstate->async_capable = node->ss.ps.async_capable;
1825 : : }
1826 : :
1827 : : /*
1828 : : * postgresIterateForeignScan
1829 : : * Retrieve next row from the result set, or clear tuple slot to indicate
1830 : : * EOF.
1831 : : */
1832 : : static TupleTableSlot *
1833 : 74346 : postgresIterateForeignScan(ForeignScanState *node)
1834 : : {
1835 : 74346 : PgFdwScanState *fsstate = (PgFdwScanState *) node->fdw_state;
1836 : 74346 : TupleTableSlot *slot = node->ss.ss_ScanTupleSlot;
1837 : :
1838 : : /*
1839 : : * In sync mode, if this is the first call after Begin or ReScan, we need
1840 : : * to create the cursor on the remote side. In async mode, we would have
1841 : : * already created the cursor before we get here, even if this is the
1842 : : * first call after Begin or ReScan.
1843 : : */
1844 [ + + ]: 74346 : if (!fsstate->cursor_exists)
1845 : 833 : create_cursor(node);
1846 : :
1847 : : /*
1848 : : * Get some more tuples, if we've run out.
1849 : : */
1850 [ + + ]: 74343 : if (fsstate->next_tuple >= fsstate->num_tuples)
1851 : : {
1852 : : /* In async mode, just clear tuple slot. */
1853 [ + + ]: 2159 : if (fsstate->async_capable)
1854 : 48 : return ExecClearTuple(slot);
1855 : : /* No point in another fetch if we already detected EOF, though. */
1856 [ + + ]: 2111 : if (!fsstate->eof_reached)
1857 : 1410 : fetch_more_data(node);
1858 : : /* If we didn't get any tuples, must be end of data. */
1859 [ + + ]: 2097 : if (fsstate->next_tuple >= fsstate->num_tuples)
1860 : 792 : return ExecClearTuple(slot);
1861 : : }
1862 : :
1863 : : /*
1864 : : * Return the next tuple.
1865 : : */
1866 : 73489 : ExecStoreHeapTuple(fsstate->tuples[fsstate->next_tuple++],
1867 : : slot,
1868 : : false);
1869 : :
1870 : 73489 : return slot;
1871 : : }
1872 : :
1873 : : /*
1874 : : * postgresReScanForeignScan
1875 : : * Restart the scan.
1876 : : */
1877 : : static void
1878 : 455 : postgresReScanForeignScan(ForeignScanState *node)
1879 : : {
1880 : 455 : PgFdwScanState *fsstate = (PgFdwScanState *) node->fdw_state;
1881 : : char sql[64];
1882 : : PGresult *res;
1883 : :
1884 : : /* If we haven't created the cursor yet, nothing to do. */
1885 [ + + ]: 455 : if (!fsstate->cursor_exists)
1886 : 62 : return;
1887 : :
1888 : : /*
1889 : : * If the node is async-capable, any asynchronous fetch made for it should
1890 : : * have been processed before we get here (see ExecAppendAsyncReset() and
1891 : : * ExecMergeAppendAsyncReset()).
1892 : : */
1893 : : Assert(!fsstate->async_capable || !fsstate->conn_state->pendingAreq ||
1894 : : fsstate->conn_state->pendingAreq->requestee != (PlanState *) node);
1895 : :
1896 : : /*
1897 : : * If any internal parameters affecting this node have changed, we'd
1898 : : * better destroy and recreate the cursor. Otherwise, if the remote
1899 : : * server is v14 or older, rewinding it should be good enough; if not,
1900 : : * rewind is only allowed for scrollable cursors, but we don't have a way
1901 : : * to check the scrollability of it, so destroy and recreate it in any
1902 : : * case. If we've only fetched zero or one batch, we needn't even rewind
1903 : : * the cursor, just rescan what we have.
1904 : : */
1905 [ + + ]: 406 : if (node->ss.ps.chgParam != NULL)
1906 : : {
1907 : 374 : fsstate->cursor_exists = false;
1908 : 374 : snprintf(sql, sizeof(sql), "CLOSE c%u",
1909 : : fsstate->cursor_number);
1910 : : }
1911 [ + + ]: 32 : else if (fsstate->fetch_ct_2 > 1)
1912 : : {
1913 [ - + ]: 19 : if (PQserverVersion(fsstate->conn) < 150000)
1914 : 0 : snprintf(sql, sizeof(sql), "MOVE BACKWARD ALL IN c%u",
1915 : : fsstate->cursor_number);
1916 : : else
1917 : : {
1918 : 19 : fsstate->cursor_exists = false;
1919 : 19 : snprintf(sql, sizeof(sql), "CLOSE c%u",
1920 : : fsstate->cursor_number);
1921 : : }
1922 : : }
1923 : : else
1924 : : {
1925 : : /* Easy: just rescan what we already have in memory, if anything */
1926 : 13 : fsstate->next_tuple = 0;
1927 : 13 : return;
1928 : : }
1929 : :
1930 : 393 : res = pgfdw_exec_query(fsstate->conn, sql, fsstate->conn_state);
1931 [ - + ]: 393 : if (PQresultStatus(res) != PGRES_COMMAND_OK)
1932 : 0 : pgfdw_report_error(res, fsstate->conn, sql);
1933 : 393 : PQclear(res);
1934 : :
1935 : : /* Now force a fresh FETCH. */
1936 : 393 : fsstate->tuples = NULL;
1937 : 393 : fsstate->num_tuples = 0;
1938 : 393 : fsstate->next_tuple = 0;
1939 : 393 : fsstate->fetch_ct_2 = 0;
1940 : 393 : fsstate->eof_reached = false;
1941 : : }
1942 : :
1943 : : /*
1944 : : * postgresEndForeignScan
1945 : : * Finish scanning foreign table and dispose objects used for this scan
1946 : : */
1947 : : static void
1948 : 1001 : postgresEndForeignScan(ForeignScanState *node)
1949 : : {
1950 : 1001 : PgFdwScanState *fsstate = (PgFdwScanState *) node->fdw_state;
1951 : :
1952 : : /* if fsstate is NULL, we are in EXPLAIN; nothing to do */
1953 [ + + ]: 1001 : if (fsstate == NULL)
1954 : 457 : return;
1955 : :
1956 : : /* Close the cursor if open, to prevent accumulation of cursors */
1957 [ + + ]: 544 : if (fsstate->cursor_exists)
1958 : 515 : close_cursor(fsstate->conn, fsstate->cursor_number,
1959 : : fsstate->conn_state);
1960 : :
1961 : : /* Release remote connection */
1962 : 543 : ReleaseConnection(fsstate->conn);
1963 : 543 : fsstate->conn = NULL;
1964 : :
1965 : : /* MemoryContexts will be deleted automatically. */
1966 : : }
1967 : :
1968 : : /*
1969 : : * postgresAddForeignUpdateTargets
1970 : : * Add resjunk column(s) needed for update/delete on a foreign table
1971 : : */
1972 : : static void
1973 : 194 : postgresAddForeignUpdateTargets(PlannerInfo *root,
1974 : : Index rtindex,
1975 : : RangeTblEntry *target_rte,
1976 : : Relation target_relation)
1977 : : {
1978 : : Var *var;
1979 : :
1980 : : /*
1981 : : * In postgres_fdw, what we need is the ctid, same as for a regular table.
1982 : : */
1983 : :
1984 : : /* Make a Var representing the desired value */
1985 : 194 : var = makeVar(rtindex,
1986 : : SelfItemPointerAttributeNumber,
1987 : : TIDOID,
1988 : : -1,
1989 : : InvalidOid,
1990 : : 0);
1991 : :
1992 : : /* Register it as a row-identity column needed by this target rel */
1993 : 194 : add_row_identity_var(root, var, rtindex, "ctid");
1994 : 194 : }
1995 : :
1996 : : /*
1997 : : * postgresPlanForeignModify
1998 : : * Plan an insert/update/delete operation on a foreign table
1999 : : */
2000 : : static List *
2001 : 174 : postgresPlanForeignModify(PlannerInfo *root,
2002 : : ModifyTable *plan,
2003 : : Index resultRelation,
2004 : : int subplan_index)
2005 : : {
2006 : 174 : CmdType operation = plan->operation;
2007 [ + - ]: 174 : RangeTblEntry *rte = planner_rt_fetch(resultRelation, root);
2008 : : Relation targetrel;
2009 : : StringInfoData sql;
2010 : 174 : List *targetAttrs = NIL;
2011 : 174 : List *withCheckOptionList = NIL;
2012 : 174 : List *returningList = NIL;
2013 : 174 : List *retrieved_attrs = NIL;
2014 : 174 : bool doNothing = false;
2015 : 174 : int values_end_len = -1;
2016 : :
2017 : 174 : initStringInfo(&sql);
2018 : :
2019 : : /*
2020 : : * Core code already has some lock on each rel being planned, so we can
2021 : : * use NoLock here.
2022 : : */
2023 : 174 : targetrel = table_open(rte->relid, NoLock);
2024 : :
2025 : : /*
2026 : : * In an INSERT, we transmit all columns that are defined in the foreign
2027 : : * table. In an UPDATE, if there are BEFORE ROW UPDATE triggers on the
2028 : : * foreign table, we transmit all columns like INSERT; else we transmit
2029 : : * only columns that were explicitly targets of the UPDATE, so as to avoid
2030 : : * unnecessary data transmission. (We can't do that for INSERT since we
2031 : : * would miss sending default values for columns not listed in the source
2032 : : * statement, and for UPDATE if there are BEFORE ROW UPDATE triggers since
2033 : : * those triggers might change values for non-target columns, in which
2034 : : * case we would miss sending changed values for those columns.)
2035 : : */
2036 [ + + + + ]: 174 : if (operation == CMD_INSERT ||
2037 : 62 : (operation == CMD_UPDATE &&
2038 [ + + ]: 62 : targetrel->trigdesc &&
2039 [ + + ]: 18 : targetrel->trigdesc->trig_update_before_row))
2040 : 105 : {
2041 : 105 : TupleDesc tupdesc = RelationGetDescr(targetrel);
2042 : : int attnum;
2043 : :
2044 [ + + ]: 439 : for (attnum = 1; attnum <= tupdesc->natts; attnum++)
2045 : : {
2046 : 334 : CompactAttribute *attr = TupleDescCompactAttr(tupdesc, attnum - 1);
2047 : :
2048 [ + + ]: 334 : if (!attr->attisdropped)
2049 : 317 : targetAttrs = lappend_int(targetAttrs, attnum);
2050 : : }
2051 : : }
2052 [ + + ]: 69 : else if (operation == CMD_UPDATE)
2053 : : {
2054 : : int col;
2055 : 47 : RelOptInfo *baserel = find_base_rel(root, resultRelation);
2056 : 47 : Bitmapset *allUpdatedCols = get_rel_all_updated_cols(root, baserel);
2057 : :
2058 : 47 : col = -1;
2059 [ + + ]: 104 : while ((col = bms_next_member(allUpdatedCols, col)) >= 0)
2060 : : {
2061 : : /* bit numbers are offset by FirstLowInvalidHeapAttributeNumber */
2062 : 57 : AttrNumber attno = col + FirstLowInvalidHeapAttributeNumber;
2063 : :
2064 [ - + ]: 57 : if (attno <= InvalidAttrNumber) /* shouldn't happen */
2065 [ # # ]: 0 : elog(ERROR, "system-column update is not supported");
2066 : 57 : targetAttrs = lappend_int(targetAttrs, attno);
2067 : : }
2068 : : }
2069 : :
2070 : : /*
2071 : : * Extract the relevant WITH CHECK OPTION list if any.
2072 : : */
2073 [ + + ]: 174 : if (plan->withCheckOptionLists)
2074 : 16 : withCheckOptionList = (List *) list_nth(plan->withCheckOptionLists,
2075 : : subplan_index);
2076 : :
2077 : : /*
2078 : : * Extract the relevant RETURNING list if any.
2079 : : */
2080 [ + + ]: 174 : if (plan->returningLists)
2081 : 34 : returningList = (List *) list_nth(plan->returningLists, subplan_index);
2082 : :
2083 : : /*
2084 : : * ON CONFLICT DO NOTHING/SELECT/UPDATE with inference specification
2085 : : * should have already been rejected in the optimizer, as presently there
2086 : : * is no way to recognize an arbiter index on a foreign table. Only DO
2087 : : * NOTHING is supported without an inference specification.
2088 : : */
2089 [ + + ]: 174 : if (plan->onConflictAction == ONCONFLICT_NOTHING)
2090 : 1 : doNothing = true;
2091 [ - + ]: 173 : else if (plan->onConflictAction != ONCONFLICT_NONE)
2092 [ # # ]: 0 : elog(ERROR, "unexpected ON CONFLICT specification: %d",
2093 : : (int) plan->onConflictAction);
2094 : :
2095 : : /*
2096 : : * Construct the SQL command string.
2097 : : */
2098 [ + + + - ]: 174 : switch (operation)
2099 : : {
2100 : 90 : case CMD_INSERT:
2101 : 90 : deparseInsertSql(&sql, rte, resultRelation, targetrel,
2102 : : targetAttrs, doNothing,
2103 : : withCheckOptionList, returningList,
2104 : : &retrieved_attrs, &values_end_len);
2105 : 90 : break;
2106 : 62 : case CMD_UPDATE:
2107 : 62 : deparseUpdateSql(&sql, rte, resultRelation, targetrel,
2108 : : targetAttrs,
2109 : : withCheckOptionList, returningList,
2110 : : &retrieved_attrs);
2111 : 62 : break;
2112 : 22 : case CMD_DELETE:
2113 : 22 : deparseDeleteSql(&sql, rte, resultRelation, targetrel,
2114 : : returningList,
2115 : : &retrieved_attrs);
2116 : 22 : break;
2117 : 0 : default:
2118 [ # # ]: 0 : elog(ERROR, "unexpected operation: %d", (int) operation);
2119 : : break;
2120 : : }
2121 : :
2122 : 174 : table_close(targetrel, NoLock);
2123 : :
2124 : : /*
2125 : : * Build the fdw_private list that will be available to the executor.
2126 : : * Items in the list must match enum FdwModifyPrivateIndex, above.
2127 : : */
2128 : 174 : return list_make5(makeString(sql.data),
2129 : : targetAttrs,
2130 : : makeInteger(values_end_len),
2131 : : makeBoolean((retrieved_attrs != NIL)),
2132 : : retrieved_attrs);
2133 : : }
2134 : :
2135 : : /*
2136 : : * postgresBeginForeignModify
2137 : : * Begin an insert/update/delete operation on a foreign table
2138 : : */
2139 : : static void
2140 : 175 : postgresBeginForeignModify(ModifyTableState *mtstate,
2141 : : ResultRelInfo *resultRelInfo,
2142 : : List *fdw_private,
2143 : : int subplan_index,
2144 : : int eflags)
2145 : : {
2146 : : PgFdwModifyState *fmstate;
2147 : : char *query;
2148 : : List *target_attrs;
2149 : : bool has_returning;
2150 : : int values_end_len;
2151 : : List *retrieved_attrs;
2152 : : RangeTblEntry *rte;
2153 : :
2154 : : /*
2155 : : * Do nothing in EXPLAIN (no ANALYZE) case. resultRelInfo->ri_FdwState
2156 : : * stays NULL.
2157 : : */
2158 [ + + ]: 175 : if (eflags & EXEC_FLAG_EXPLAIN_ONLY)
2159 : 47 : return;
2160 : :
2161 : : /* Deconstruct fdw_private data. */
2162 : 128 : query = strVal(list_nth(fdw_private,
2163 : : FdwModifyPrivateUpdateSql));
2164 : 128 : target_attrs = (List *) list_nth(fdw_private,
2165 : : FdwModifyPrivateTargetAttnums);
2166 : 128 : values_end_len = intVal(list_nth(fdw_private,
2167 : : FdwModifyPrivateLen));
2168 : 128 : has_returning = boolVal(list_nth(fdw_private,
2169 : : FdwModifyPrivateHasReturning));
2170 : 128 : retrieved_attrs = (List *) list_nth(fdw_private,
2171 : : FdwModifyPrivateRetrievedAttrs);
2172 : :
2173 : : /* Find RTE. */
2174 : 128 : rte = exec_rt_fetch(resultRelInfo->ri_RangeTableIndex,
2175 : : mtstate->ps.state);
2176 : :
2177 : : /* Construct an execution state. */
2178 : 128 : fmstate = create_foreign_modify(mtstate->ps.state,
2179 : : rte,
2180 : : resultRelInfo,
2181 : : mtstate->operation,
2182 : 128 : outerPlanState(mtstate)->plan,
2183 : : query,
2184 : : target_attrs,
2185 : : values_end_len,
2186 : : has_returning,
2187 : : retrieved_attrs);
2188 : :
2189 : 128 : resultRelInfo->ri_FdwState = fmstate;
2190 : : }
2191 : :
2192 : : /*
2193 : : * postgresExecForeignInsert
2194 : : * Insert one row into a foreign table
2195 : : */
2196 : : static TupleTableSlot *
2197 : 1993 : postgresExecForeignInsert(EState *estate,
2198 : : ResultRelInfo *resultRelInfo,
2199 : : TupleTableSlot *slot,
2200 : : TupleTableSlot *planSlot)
2201 : : {
2202 : 1993 : PgFdwModifyState *fmstate = (PgFdwModifyState *) resultRelInfo->ri_FdwState;
2203 : : TupleTableSlot **rslot;
2204 : 1993 : int numSlots = 1;
2205 : :
2206 : : /*
2207 : : * If the fmstate has aux_fmstate set, use the aux_fmstate (see
2208 : : * postgresBeginForeignInsert())
2209 : : */
2210 [ - + ]: 1993 : if (fmstate->aux_fmstate)
2211 : 0 : resultRelInfo->ri_FdwState = fmstate->aux_fmstate;
2212 : 1993 : rslot = execute_foreign_modify(estate, resultRelInfo, CMD_INSERT,
2213 : : &slot, &planSlot, &numSlots);
2214 : : /* Revert that change */
2215 [ - + ]: 1989 : if (fmstate->aux_fmstate)
2216 : 0 : resultRelInfo->ri_FdwState = fmstate;
2217 : :
2218 [ + + ]: 1989 : return rslot ? *rslot : NULL;
2219 : : }
2220 : :
2221 : : /*
2222 : : * postgresExecForeignBatchInsert
2223 : : * Insert multiple rows into a foreign table
2224 : : */
2225 : : static TupleTableSlot **
2226 : 43 : postgresExecForeignBatchInsert(EState *estate,
2227 : : ResultRelInfo *resultRelInfo,
2228 : : TupleTableSlot **slots,
2229 : : TupleTableSlot **planSlots,
2230 : : int *numSlots)
2231 : : {
2232 : 43 : PgFdwModifyState *fmstate = (PgFdwModifyState *) resultRelInfo->ri_FdwState;
2233 : : TupleTableSlot **rslot;
2234 : :
2235 : : /*
2236 : : * If the fmstate has aux_fmstate set, use the aux_fmstate (see
2237 : : * postgresBeginForeignInsert())
2238 : : */
2239 [ - + ]: 43 : if (fmstate->aux_fmstate)
2240 : 0 : resultRelInfo->ri_FdwState = fmstate->aux_fmstate;
2241 : 43 : rslot = execute_foreign_modify(estate, resultRelInfo, CMD_INSERT,
2242 : : slots, planSlots, numSlots);
2243 : : /* Revert that change */
2244 [ - + ]: 42 : if (fmstate->aux_fmstate)
2245 : 0 : resultRelInfo->ri_FdwState = fmstate;
2246 : :
2247 : 42 : return rslot;
2248 : : }
2249 : :
2250 : : /*
2251 : : * postgresGetForeignModifyBatchSize
2252 : : * Determine the maximum number of tuples that can be inserted in bulk
2253 : : *
2254 : : * Returns the batch size specified for server or table. When batching is not
2255 : : * allowed (e.g. for tables with BEFORE/AFTER ROW triggers or with RETURNING
2256 : : * clause), returns 1.
2257 : : */
2258 : : static int
2259 : 152 : postgresGetForeignModifyBatchSize(ResultRelInfo *resultRelInfo)
2260 : : {
2261 : : int batch_size;
2262 : 152 : PgFdwModifyState *fmstate = (PgFdwModifyState *) resultRelInfo->ri_FdwState;
2263 : :
2264 : : /* should be called only once */
2265 : : Assert(resultRelInfo->ri_BatchSize == 0);
2266 : :
2267 : : /*
2268 : : * Should never get called when the insert is being performed on a table
2269 : : * that is also among the target relations of an UPDATE operation, because
2270 : : * postgresBeginForeignInsert() currently rejects such insert attempts.
2271 : : */
2272 : : Assert(fmstate == NULL || fmstate->aux_fmstate == NULL);
2273 : :
2274 : : /*
2275 : : * In EXPLAIN without ANALYZE, ri_FdwState is NULL, so we have to lookup
2276 : : * the option directly in server/table options. Otherwise just use the
2277 : : * value we determined earlier.
2278 : : */
2279 [ + + ]: 152 : if (fmstate)
2280 : 139 : batch_size = fmstate->batch_size;
2281 : : else
2282 : 13 : batch_size = get_batch_size_option(resultRelInfo->ri_RelationDesc);
2283 : :
2284 : : /*
2285 : : * Disable batching when we have to use RETURNING, there are any
2286 : : * BEFORE/AFTER ROW INSERT triggers on the foreign table, or there are any
2287 : : * WITH CHECK OPTION constraints from parent views.
2288 : : *
2289 : : * When there are any BEFORE ROW INSERT triggers on the table, we can't
2290 : : * support it, because such triggers might query the table we're inserting
2291 : : * into and act differently if the tuples that have already been processed
2292 : : * and prepared for insertion are not there.
2293 : : */
2294 [ + + ]: 152 : if (resultRelInfo->ri_projectReturning != NULL ||
2295 [ + + ]: 131 : resultRelInfo->ri_WithCheckOptions != NIL ||
2296 [ + + ]: 122 : (resultRelInfo->ri_TrigDesc &&
2297 [ + + ]: 14 : (resultRelInfo->ri_TrigDesc->trig_insert_before_row ||
2298 [ + - ]: 1 : resultRelInfo->ri_TrigDesc->trig_insert_after_row)))
2299 : 44 : return 1;
2300 : :
2301 : : /*
2302 : : * If the foreign table has no columns, disable batching as the INSERT
2303 : : * syntax doesn't allow batching multiple empty rows into a zero-column
2304 : : * table in a single statement. This is needed for COPY FROM, in which
2305 : : * case fmstate must be non-NULL.
2306 : : */
2307 [ + + + + ]: 108 : if (fmstate && list_length(fmstate->target_attrs) == 0)
2308 : 1 : return 1;
2309 : :
2310 : : /*
2311 : : * Otherwise use the batch size specified for server/table. The number of
2312 : : * parameters in a batch is limited to 65535 (uint16), so make sure we
2313 : : * don't exceed this limit by using the maximum batch_size possible.
2314 : : */
2315 [ + + + - ]: 107 : if (fmstate && fmstate->p_nums > 0)
2316 : 99 : batch_size = Min(batch_size, PQ_QUERY_PARAM_MAX_LIMIT / fmstate->p_nums);
2317 : :
2318 : 107 : return batch_size;
2319 : : }
2320 : :
2321 : : /*
2322 : : * postgresExecForeignUpdate
2323 : : * Update one row in a foreign table
2324 : : */
2325 : : static TupleTableSlot *
2326 : 97 : postgresExecForeignUpdate(EState *estate,
2327 : : ResultRelInfo *resultRelInfo,
2328 : : TupleTableSlot *slot,
2329 : : TupleTableSlot *planSlot)
2330 : : {
2331 : : TupleTableSlot **rslot;
2332 : 97 : int numSlots = 1;
2333 : :
2334 : 97 : rslot = execute_foreign_modify(estate, resultRelInfo, CMD_UPDATE,
2335 : : &slot, &planSlot, &numSlots);
2336 : :
2337 [ + + ]: 97 : return rslot ? rslot[0] : NULL;
2338 : : }
2339 : :
2340 : : /*
2341 : : * postgresExecForeignDelete
2342 : : * Delete one row from a foreign table
2343 : : */
2344 : : static TupleTableSlot *
2345 : 23 : postgresExecForeignDelete(EState *estate,
2346 : : ResultRelInfo *resultRelInfo,
2347 : : TupleTableSlot *slot,
2348 : : TupleTableSlot *planSlot)
2349 : : {
2350 : : TupleTableSlot **rslot;
2351 : 23 : int numSlots = 1;
2352 : :
2353 : 23 : rslot = execute_foreign_modify(estate, resultRelInfo, CMD_DELETE,
2354 : : &slot, &planSlot, &numSlots);
2355 : :
2356 [ + - ]: 23 : return rslot ? rslot[0] : NULL;
2357 : : }
2358 : :
2359 : : /*
2360 : : * postgresEndForeignModify
2361 : : * Finish an insert/update/delete operation on a foreign table
2362 : : */
2363 : : static void
2364 : 161 : postgresEndForeignModify(EState *estate,
2365 : : ResultRelInfo *resultRelInfo)
2366 : : {
2367 : 161 : PgFdwModifyState *fmstate = (PgFdwModifyState *) resultRelInfo->ri_FdwState;
2368 : :
2369 : : /* If fmstate is NULL, we are in EXPLAIN; nothing to do */
2370 [ + + ]: 161 : if (fmstate == NULL)
2371 : 47 : return;
2372 : :
2373 : : /* Destroy the execution state */
2374 : 114 : finish_foreign_modify(fmstate);
2375 : : }
2376 : :
2377 : : /*
2378 : : * postgresBeginForeignInsert
2379 : : * Begin an insert operation on a foreign table
2380 : : */
2381 : : static void
2382 : 68 : postgresBeginForeignInsert(ModifyTableState *mtstate,
2383 : : ResultRelInfo *resultRelInfo)
2384 : : {
2385 : : PgFdwModifyState *fmstate;
2386 : 68 : ModifyTable *plan = castNode(ModifyTable, mtstate->ps.plan);
2387 : 68 : EState *estate = mtstate->ps.state;
2388 : : Index resultRelation;
2389 : 68 : Relation rel = resultRelInfo->ri_RelationDesc;
2390 : : RangeTblEntry *rte;
2391 : 68 : TupleDesc tupdesc = RelationGetDescr(rel);
2392 : : int attnum;
2393 : : int values_end_len;
2394 : : StringInfoData sql;
2395 : 68 : List *targetAttrs = NIL;
2396 : 68 : List *retrieved_attrs = NIL;
2397 : 68 : bool doNothing = false;
2398 : :
2399 : : /*
2400 : : * If the foreign table we are about to insert routed rows into is also an
2401 : : * UPDATE subplan result rel that will be updated later, proceeding with
2402 : : * the INSERT will result in the later UPDATE incorrectly modifying those
2403 : : * routed rows, so prevent the INSERT --- it would be nice if we could
2404 : : * handle this case; but for now, throw an error for safety.
2405 : : */
2406 [ + + + + ]: 68 : if (plan && plan->operation == CMD_UPDATE &&
2407 [ + + ]: 9 : (resultRelInfo->ri_usesFdwDirectModify ||
2408 [ + + ]: 5 : resultRelInfo->ri_FdwState))
2409 [ + - ]: 6 : ereport(ERROR,
2410 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2411 : : errmsg("cannot route tuples into foreign table to be updated \"%s\"",
2412 : : RelationGetRelationName(rel))));
2413 : :
2414 : 62 : initStringInfo(&sql);
2415 : :
2416 : : /* We transmit all columns that are defined in the foreign table. */
2417 [ + + ]: 189 : for (attnum = 1; attnum <= tupdesc->natts; attnum++)
2418 : : {
2419 : 127 : CompactAttribute *attr = TupleDescCompactAttr(tupdesc, attnum - 1);
2420 : :
2421 [ + + ]: 127 : if (!attr->attisdropped)
2422 : 125 : targetAttrs = lappend_int(targetAttrs, attnum);
2423 : : }
2424 : :
2425 : : /* Check if we add the ON CONFLICT clause to the remote query. */
2426 [ + + ]: 62 : if (plan)
2427 : : {
2428 : 38 : OnConflictAction onConflictAction = plan->onConflictAction;
2429 : :
2430 : : /* We only support DO NOTHING without an inference specification. */
2431 [ + + ]: 38 : if (onConflictAction == ONCONFLICT_NOTHING)
2432 : 2 : doNothing = true;
2433 [ - + ]: 36 : else if (onConflictAction != ONCONFLICT_NONE)
2434 [ # # ]: 0 : elog(ERROR, "unexpected ON CONFLICT specification: %d",
2435 : : (int) onConflictAction);
2436 : : }
2437 : :
2438 : : /*
2439 : : * If the foreign table is a partition that doesn't have a corresponding
2440 : : * RTE entry, we need to create a new RTE describing the foreign table for
2441 : : * use by deparseInsertSql and create_foreign_modify() below, after first
2442 : : * copying the parent's RTE and modifying some fields to describe the
2443 : : * foreign partition to work on. However, if this is invoked by UPDATE,
2444 : : * the existing RTE may already correspond to this partition if it is one
2445 : : * of the UPDATE subplan target rels; in that case, we can just use the
2446 : : * existing RTE as-is.
2447 : : */
2448 [ + + ]: 62 : if (resultRelInfo->ri_RangeTableIndex == 0)
2449 : : {
2450 : 44 : ResultRelInfo *rootResultRelInfo = resultRelInfo->ri_RootResultRelInfo;
2451 : :
2452 : 44 : rte = exec_rt_fetch(rootResultRelInfo->ri_RangeTableIndex, estate);
2453 : 44 : rte = copyObject(rte);
2454 : 44 : rte->relid = RelationGetRelid(rel);
2455 : 44 : rte->relkind = RELKIND_FOREIGN_TABLE;
2456 : :
2457 : : /*
2458 : : * For UPDATE, we must use the RT index of the first subplan target
2459 : : * rel's RTE, because the core code would have built expressions for
2460 : : * the partition, such as RETURNING, using that RT index as varno of
2461 : : * Vars contained in those expressions.
2462 : : */
2463 [ + + + + ]: 44 : if (plan && plan->operation == CMD_UPDATE &&
2464 [ + - ]: 3 : rootResultRelInfo->ri_RangeTableIndex == plan->rootRelation)
2465 : 3 : resultRelation = mtstate->resultRelInfo[0].ri_RangeTableIndex;
2466 : : else
2467 : 41 : resultRelation = rootResultRelInfo->ri_RangeTableIndex;
2468 : : }
2469 : : else
2470 : : {
2471 : 18 : resultRelation = resultRelInfo->ri_RangeTableIndex;
2472 : 18 : rte = exec_rt_fetch(resultRelation, estate);
2473 : : }
2474 : :
2475 : : /* Construct the SQL command string. */
2476 : 62 : deparseInsertSql(&sql, rte, resultRelation, rel, targetAttrs, doNothing,
2477 : : resultRelInfo->ri_WithCheckOptions,
2478 : : resultRelInfo->ri_returningList,
2479 : : &retrieved_attrs, &values_end_len);
2480 : :
2481 : : /* Construct an execution state. */
2482 : 62 : fmstate = create_foreign_modify(mtstate->ps.state,
2483 : : rte,
2484 : : resultRelInfo,
2485 : : CMD_INSERT,
2486 : : NULL,
2487 : : sql.data,
2488 : : targetAttrs,
2489 : : values_end_len,
2490 : : retrieved_attrs != NIL,
2491 : : retrieved_attrs);
2492 : :
2493 : : /*
2494 : : * If the given resultRelInfo already has PgFdwModifyState set, it means
2495 : : * the foreign table is an UPDATE subplan result rel; in which case, store
2496 : : * the resulting state into the aux_fmstate of the PgFdwModifyState.
2497 : : */
2498 [ - + ]: 62 : if (resultRelInfo->ri_FdwState)
2499 : : {
2500 : : Assert(plan && plan->operation == CMD_UPDATE);
2501 : : Assert(resultRelInfo->ri_usesFdwDirectModify == false);
2502 : 0 : ((PgFdwModifyState *) resultRelInfo->ri_FdwState)->aux_fmstate = fmstate;
2503 : : }
2504 : : else
2505 : 62 : resultRelInfo->ri_FdwState = fmstate;
2506 : 62 : }
2507 : :
2508 : : /*
2509 : : * postgresEndForeignInsert
2510 : : * Finish an insert operation on a foreign table
2511 : : */
2512 : : static void
2513 : 54 : postgresEndForeignInsert(EState *estate,
2514 : : ResultRelInfo *resultRelInfo)
2515 : : {
2516 : 54 : PgFdwModifyState *fmstate = (PgFdwModifyState *) resultRelInfo->ri_FdwState;
2517 : :
2518 : : Assert(fmstate != NULL);
2519 : :
2520 : : /*
2521 : : * If the fmstate has aux_fmstate set, get the aux_fmstate (see
2522 : : * postgresBeginForeignInsert())
2523 : : */
2524 [ - + ]: 54 : if (fmstate->aux_fmstate)
2525 : 0 : fmstate = fmstate->aux_fmstate;
2526 : :
2527 : : /* Destroy the execution state */
2528 : 54 : finish_foreign_modify(fmstate);
2529 : 54 : }
2530 : :
2531 : : /*
2532 : : * postgresIsForeignRelUpdatable
2533 : : * Determine whether a foreign table supports INSERT, UPDATE and/or
2534 : : * DELETE.
2535 : : */
2536 : : static int
2537 : 351 : postgresIsForeignRelUpdatable(Relation rel)
2538 : : {
2539 : : bool updatable;
2540 : : ForeignTable *table;
2541 : : ForeignServer *server;
2542 : : ListCell *lc;
2543 : :
2544 : : /*
2545 : : * By default, all postgres_fdw foreign tables are assumed updatable. This
2546 : : * can be overridden by a per-server setting, which in turn can be
2547 : : * overridden by a per-table setting.
2548 : : */
2549 : 351 : updatable = true;
2550 : :
2551 : 351 : table = GetForeignTable(RelationGetRelid(rel));
2552 : 351 : server = GetForeignServer(table->serverid);
2553 : :
2554 [ + - + + : 1580 : foreach(lc, server->options)
+ + ]
2555 : : {
2556 : 1229 : DefElem *def = (DefElem *) lfirst(lc);
2557 : :
2558 [ - + ]: 1229 : if (strcmp(def->defname, "updatable") == 0)
2559 : 0 : updatable = defGetBoolean(def);
2560 : : }
2561 [ + - + + : 841 : foreach(lc, table->options)
+ + ]
2562 : : {
2563 : 490 : DefElem *def = (DefElem *) lfirst(lc);
2564 : :
2565 [ - + ]: 490 : if (strcmp(def->defname, "updatable") == 0)
2566 : 0 : updatable = defGetBoolean(def);
2567 : : }
2568 : :
2569 : : /*
2570 : : * Currently "updatable" means support for INSERT, UPDATE and DELETE.
2571 : : */
2572 : : return updatable ?
2573 [ + - ]: 351 : (1 << CMD_INSERT) | (1 << CMD_UPDATE) | (1 << CMD_DELETE) : 0;
2574 : : }
2575 : :
2576 : : /*
2577 : : * postgresRecheckForeignScan
2578 : : * Execute a local join execution plan for a foreign join
2579 : : */
2580 : : static bool
2581 : 5 : postgresRecheckForeignScan(ForeignScanState *node, TupleTableSlot *slot)
2582 : : {
2583 : 5 : Index scanrelid = ((Scan *) node->ss.ps.plan)->scanrelid;
2584 : 5 : PlanState *outerPlan = outerPlanState(node);
2585 : : TupleTableSlot *result;
2586 : :
2587 : : /* For base foreign relations, it suffices to set fdw_recheck_quals */
2588 [ + + ]: 5 : if (scanrelid > 0)
2589 : 3 : return true;
2590 : :
2591 : : Assert(outerPlan != NULL);
2592 : :
2593 : : /* Execute a local join execution plan */
2594 : 2 : result = ExecProcNode(outerPlan);
2595 [ + + - + ]: 2 : if (TupIsNull(result))
2596 : 1 : return false;
2597 : :
2598 : : /* Store result in the given slot */
2599 : 1 : ExecCopySlot(slot, result);
2600 : :
2601 : 1 : return true;
2602 : : }
2603 : :
2604 : : /*
2605 : : * find_modifytable_subplan
2606 : : * Helper routine for postgresPlanDirectModify to find the
2607 : : * ModifyTable subplan node that scans the specified RTI.
2608 : : *
2609 : : * Returns NULL if the subplan couldn't be identified. That's not a fatal
2610 : : * error condition, we just abandon trying to do the update directly.
2611 : : */
2612 : : static ForeignScan *
2613 : 136 : find_modifytable_subplan(PlannerInfo *root,
2614 : : ModifyTable *plan,
2615 : : Index rtindex,
2616 : : int subplan_index)
2617 : : {
2618 : 136 : Plan *subplan = outerPlan(plan);
2619 : :
2620 : : /*
2621 : : * The cases we support are (1) the desired ForeignScan is the immediate
2622 : : * child of ModifyTable, or (2) it is the subplan_index'th child of an
2623 : : * Append node that is the immediate child of ModifyTable. There is no
2624 : : * point in looking further down, as that would mean that local joins are
2625 : : * involved, so we can't do the update directly.
2626 : : *
2627 : : * There could be a Result atop the Append too, acting to compute the
2628 : : * UPDATE targetlist values. We ignore that here; the tlist will be
2629 : : * checked by our caller.
2630 : : *
2631 : : * In principle we could examine all the children of the Append, but it's
2632 : : * currently unlikely that the core planner would generate such a plan
2633 : : * with the children out-of-order. Moreover, such a search risks costing
2634 : : * O(N^2) time when there are a lot of children.
2635 : : */
2636 [ + + ]: 136 : if (IsA(subplan, Append))
2637 : : {
2638 : 35 : Append *appendplan = (Append *) subplan;
2639 : :
2640 [ + - ]: 35 : if (subplan_index < list_length(appendplan->appendplans))
2641 : 35 : subplan = (Plan *) list_nth(appendplan->appendplans, subplan_index);
2642 : : }
2643 [ + + ]: 101 : else if (IsA(subplan, Result) &&
2644 [ + + ]: 6 : outerPlan(subplan) != NULL &&
2645 [ + - ]: 5 : IsA(outerPlan(subplan), Append))
2646 : : {
2647 : 5 : Append *appendplan = (Append *) outerPlan(subplan);
2648 : :
2649 [ + - ]: 5 : if (subplan_index < list_length(appendplan->appendplans))
2650 : 5 : subplan = (Plan *) list_nth(appendplan->appendplans, subplan_index);
2651 : : }
2652 : :
2653 : : /* Now, have we got a ForeignScan on the desired rel? */
2654 [ + + ]: 136 : if (IsA(subplan, ForeignScan))
2655 : : {
2656 : 119 : ForeignScan *fscan = (ForeignScan *) subplan;
2657 : :
2658 [ + - ]: 119 : if (bms_is_member(rtindex, fscan->fs_base_relids))
2659 : 119 : return fscan;
2660 : : }
2661 : :
2662 : 17 : return NULL;
2663 : : }
2664 : :
2665 : : /*
2666 : : * postgresPlanDirectModify
2667 : : * Consider a direct foreign table modification
2668 : : *
2669 : : * Decide whether it is safe to modify a foreign table directly, and if so,
2670 : : * rewrite subplan accordingly.
2671 : : */
2672 : : static bool
2673 : 202 : postgresPlanDirectModify(PlannerInfo *root,
2674 : : ModifyTable *plan,
2675 : : Index resultRelation,
2676 : : int subplan_index)
2677 : : {
2678 : 202 : CmdType operation = plan->operation;
2679 : : RelOptInfo *foreignrel;
2680 : : RangeTblEntry *rte;
2681 : : PgFdwRelationInfo *fpinfo;
2682 : : Relation rel;
2683 : : StringInfoData sql;
2684 : : ForeignScan *fscan;
2685 : 202 : List *processed_tlist = NIL;
2686 : 202 : List *targetAttrs = NIL;
2687 : : List *remote_exprs;
2688 : 202 : List *params_list = NIL;
2689 : 202 : List *returningList = NIL;
2690 : 202 : List *retrieved_attrs = NIL;
2691 : :
2692 : : /*
2693 : : * Decide whether it is safe to modify a foreign table directly.
2694 : : */
2695 : :
2696 : : /*
2697 : : * The table modification must be an UPDATE or DELETE.
2698 : : */
2699 [ + + + + ]: 202 : if (operation != CMD_UPDATE && operation != CMD_DELETE)
2700 : 66 : return false;
2701 : :
2702 : : /*
2703 : : * Try to locate the ForeignScan subplan that's scanning resultRelation.
2704 : : */
2705 : 136 : fscan = find_modifytable_subplan(root, plan, resultRelation, subplan_index);
2706 [ + + ]: 136 : if (!fscan)
2707 : 17 : return false;
2708 : :
2709 : : /*
2710 : : * It's unsafe to modify a foreign table directly if there are any quals
2711 : : * that should be evaluated locally.
2712 : : */
2713 [ + + ]: 119 : if (fscan->scan.plan.qual != NIL)
2714 : 5 : return false;
2715 : :
2716 : : /* Safe to fetch data about the target foreign rel */
2717 [ + + ]: 114 : if (fscan->scan.scanrelid == 0)
2718 : : {
2719 : 13 : foreignrel = find_join_rel(root, fscan->fs_relids);
2720 : : /* We should have a rel for this foreign join. */
2721 : : Assert(foreignrel);
2722 : : }
2723 : : else
2724 : 101 : foreignrel = root->simple_rel_array[resultRelation];
2725 : 114 : rte = root->simple_rte_array[resultRelation];
2726 : 114 : fpinfo = (PgFdwRelationInfo *) foreignrel->fdw_private;
2727 : :
2728 : : /*
2729 : : * It's unsafe to update a foreign table directly, if any expressions to
2730 : : * assign to the target columns are unsafe to evaluate remotely.
2731 : : */
2732 [ + + ]: 114 : if (operation == CMD_UPDATE)
2733 : : {
2734 : : ListCell *lc,
2735 : : *lc2;
2736 : :
2737 : : /*
2738 : : * The expressions of concern are the first N columns of the processed
2739 : : * targetlist, where N is the length of the rel's update_colnos.
2740 : : */
2741 : 55 : get_translated_update_targetlist(root, resultRelation,
2742 : : &processed_tlist, &targetAttrs);
2743 [ + - + - : 111 : forboth(lc, processed_tlist, lc2, targetAttrs)
+ - + + +
- + + +
+ ]
2744 : : {
2745 : 63 : TargetEntry *tle = lfirst_node(TargetEntry, lc);
2746 : 63 : AttrNumber attno = lfirst_int(lc2);
2747 : :
2748 : : /* update's new-value expressions shouldn't be resjunk */
2749 : : Assert(!tle->resjunk);
2750 : :
2751 [ - + ]: 63 : if (attno <= InvalidAttrNumber) /* shouldn't happen */
2752 [ # # ]: 0 : elog(ERROR, "system-column update is not supported");
2753 : :
2754 [ + + ]: 63 : if (!is_foreign_expr(root, foreignrel, fpinfo, (Expr *) tle->expr))
2755 : 7 : return false;
2756 : : }
2757 : : }
2758 : :
2759 : : /*
2760 : : * Ok, rewrite subplan so as to modify the foreign table directly.
2761 : : */
2762 : 107 : initStringInfo(&sql);
2763 : :
2764 : : /*
2765 : : * Core code already has some lock on each rel being planned, so we can
2766 : : * use NoLock here.
2767 : : */
2768 : 107 : rel = table_open(rte->relid, NoLock);
2769 : :
2770 : : /*
2771 : : * Recall the qual clauses that must be evaluated remotely. (These are
2772 : : * bare clauses not RestrictInfos, but deparse.c's appendConditions()
2773 : : * doesn't care.)
2774 : : */
2775 : 107 : remote_exprs = fpinfo->final_remote_exprs;
2776 : :
2777 : : /*
2778 : : * Extract the relevant RETURNING list if any.
2779 : : */
2780 [ + + ]: 107 : if (plan->returningLists)
2781 : : {
2782 : 37 : returningList = (List *) list_nth(plan->returningLists, subplan_index);
2783 : :
2784 : : /*
2785 : : * When performing an UPDATE/DELETE .. RETURNING on a join directly,
2786 : : * we fetch from the foreign server any Vars specified in RETURNING
2787 : : * that refer not only to the target relation but to non-target
2788 : : * relations. So we'll deparse them into the RETURNING clause of the
2789 : : * remote query; use a targetlist consisting of them instead, which
2790 : : * will be adjusted to be new fdw_scan_tlist of the foreign-scan plan
2791 : : * node below.
2792 : : */
2793 [ + + ]: 37 : if (fscan->scan.scanrelid == 0)
2794 : 5 : returningList = build_remote_returning(resultRelation, rel,
2795 : : returningList);
2796 : : }
2797 : :
2798 : : /*
2799 : : * Construct the SQL command string.
2800 : : */
2801 [ + + - ]: 107 : switch (operation)
2802 : : {
2803 : 48 : case CMD_UPDATE:
2804 : 48 : deparseDirectUpdateSql(&sql, root, resultRelation, rel,
2805 : : foreignrel,
2806 : : processed_tlist,
2807 : : targetAttrs,
2808 : : remote_exprs, ¶ms_list,
2809 : : returningList, &retrieved_attrs);
2810 : 48 : break;
2811 : 59 : case CMD_DELETE:
2812 : 59 : deparseDirectDeleteSql(&sql, root, resultRelation, rel,
2813 : : foreignrel,
2814 : : remote_exprs, ¶ms_list,
2815 : : returningList, &retrieved_attrs);
2816 : 59 : break;
2817 : 0 : default:
2818 [ # # ]: 0 : elog(ERROR, "unexpected operation: %d", (int) operation);
2819 : : break;
2820 : : }
2821 : :
2822 : : /*
2823 : : * Update the operation and target relation info.
2824 : : */
2825 : 107 : fscan->operation = operation;
2826 : 107 : fscan->resultRelation = resultRelation;
2827 : :
2828 : : /*
2829 : : * Update the fdw_exprs list that will be available to the executor.
2830 : : */
2831 : 107 : fscan->fdw_exprs = params_list;
2832 : :
2833 : : /*
2834 : : * Update the fdw_private list that will be available to the executor.
2835 : : * Items in the list must match enum FdwDirectModifyPrivateIndex, above.
2836 : : */
2837 : 107 : fscan->fdw_private = list_make4(makeString(sql.data),
2838 : : makeBoolean((retrieved_attrs != NIL)),
2839 : : retrieved_attrs,
2840 : : makeBoolean(plan->canSetTag));
2841 : 107 : fscan->fdw_private = lappend(fscan->fdw_private,
2842 : 107 : get_functions_data(root, foreignrel));
2843 : 107 : fscan->fdw_private = lappend(fscan->fdw_private,
2844 : 107 : makeInteger(get_min_base_rti(root, foreignrel)));
2845 : :
2846 : : /*
2847 : : * Update the foreign-join-related fields.
2848 : : */
2849 [ + + ]: 107 : if (fscan->scan.scanrelid == 0)
2850 : : {
2851 : : /* No need for the outer subplan. */
2852 : 10 : fscan->scan.plan.lefttree = NULL;
2853 : :
2854 : : /* Build new fdw_scan_tlist if UPDATE/DELETE .. RETURNING. */
2855 [ + + ]: 10 : if (returningList)
2856 : 3 : rebuild_fdw_scan_tlist(fscan, returningList);
2857 : : }
2858 : :
2859 : : /*
2860 : : * Finally, unset the async-capable flag if it is set, as we currently
2861 : : * don't support asynchronous execution of direct modifications.
2862 : : */
2863 [ + + ]: 107 : if (fscan->scan.plan.async_capable)
2864 : 8 : fscan->scan.plan.async_capable = false;
2865 : :
2866 : 107 : table_close(rel, NoLock);
2867 : 107 : return true;
2868 : : }
2869 : :
2870 : : /*
2871 : : * postgresBeginDirectModify
2872 : : * Prepare a direct foreign table modification
2873 : : */
2874 : : static void
2875 : 108 : postgresBeginDirectModify(ForeignScanState *node, int eflags)
2876 : : {
2877 : 108 : ForeignScan *fsplan = (ForeignScan *) node->ss.ps.plan;
2878 : 108 : EState *estate = node->ss.ps.state;
2879 : : PgFdwDirectModifyState *dmstate;
2880 : : Index rtindex;
2881 : : Oid userid;
2882 : : ForeignTable *table;
2883 : : UserMapping *user;
2884 : : int numParams;
2885 : :
2886 : : /*
2887 : : * Do nothing in EXPLAIN (no ANALYZE) case. node->fdw_state stays NULL.
2888 : : */
2889 [ + + ]: 108 : if (eflags & EXEC_FLAG_EXPLAIN_ONLY)
2890 : 33 : return;
2891 : :
2892 : : /*
2893 : : * We'll save private state in node->fdw_state.
2894 : : */
2895 : 75 : dmstate = palloc0_object(PgFdwDirectModifyState);
2896 : 75 : node->fdw_state = dmstate;
2897 : :
2898 : : /*
2899 : : * Identify which user to do the remote access as. This should match what
2900 : : * ExecCheckPermissions() does.
2901 : : */
2902 [ - + ]: 75 : userid = OidIsValid(fsplan->checkAsUser) ? fsplan->checkAsUser : GetUserId();
2903 : :
2904 : : /* Get info about foreign table. */
2905 : 75 : rtindex = node->resultRelInfo->ri_RangeTableIndex;
2906 [ + + ]: 75 : if (fsplan->scan.scanrelid == 0)
2907 : 6 : dmstate->rel = ExecOpenScanRelation(estate, rtindex, eflags);
2908 : : else
2909 : 69 : dmstate->rel = node->ss.ss_currentRelation;
2910 : 75 : table = GetForeignTable(RelationGetRelid(dmstate->rel));
2911 : 75 : user = GetUserMapping(userid, table->serverid);
2912 : :
2913 : : /*
2914 : : * Get connection to the foreign server. Connection manager will
2915 : : * establish new connection if necessary.
2916 : : */
2917 : 75 : dmstate->conn = GetConnection(user, false, &dmstate->conn_state);
2918 : :
2919 : : /* Update the foreign-join-related fields. */
2920 [ + + ]: 75 : if (fsplan->scan.scanrelid == 0)
2921 : : {
2922 : : /* Save info about foreign table. */
2923 : 6 : dmstate->resultRel = dmstate->rel;
2924 : :
2925 : : /*
2926 : : * Set dmstate->rel to NULL to teach get_returning_data() and
2927 : : * make_tuple_from_result_row() that columns fetched from the remote
2928 : : * server are described by fdw_scan_tlist of the foreign-scan plan
2929 : : * node, not the tuple descriptor for the target relation.
2930 : : */
2931 : 6 : dmstate->rel = NULL;
2932 : : }
2933 : :
2934 : : /* Initialize state variable */
2935 : 75 : dmstate->num_tuples = -1; /* -1 means not set yet */
2936 : :
2937 : : /* Get private info created by planner functions. */
2938 : 75 : dmstate->query = strVal(list_nth(fsplan->fdw_private,
2939 : : FdwDirectModifyPrivateUpdateSql));
2940 : 75 : dmstate->has_returning = boolVal(list_nth(fsplan->fdw_private,
2941 : : FdwDirectModifyPrivateHasReturning));
2942 : 75 : dmstate->retrieved_attrs = (List *) list_nth(fsplan->fdw_private,
2943 : : FdwDirectModifyPrivateRetrievedAttrs);
2944 : 75 : dmstate->set_processed = boolVal(list_nth(fsplan->fdw_private,
2945 : : FdwDirectModifyPrivateSetProcessed));
2946 : :
2947 : : /* Create context for per-tuple temp workspace. */
2948 : 75 : dmstate->temp_cxt = AllocSetContextCreate(estate->es_query_cxt,
2949 : : "postgres_fdw temporary data",
2950 : : ALLOCSET_SMALL_SIZES);
2951 : :
2952 : : /* Prepare for input conversion of RETURNING results. */
2953 [ + + ]: 75 : if (dmstate->has_returning)
2954 : : {
2955 : : TupleDesc tupdesc;
2956 : :
2957 [ + + ]: 18 : if (fsplan->scan.scanrelid == 0)
2958 : : {
2959 : : /*
2960 : : * DirectModify on a foreign join: use the per-RTE function
2961 : : * metadata saved at plan time so a whole-row Var pointing at a
2962 : : * function RTE absorbed into the join can be rebuilt into a
2963 : : * usable TupleDesc (e.g. RETURNING t for a join with UNNEST(...,
2964 : : * ...) AS t(bx, i)).
2965 : : */
2966 : 2 : List *rtfuncdata = (List *) list_nth(fsplan->fdw_private,
2967 : : FdwDirectModifyPrivateFunctions);
2968 : 2 : int min_base_rti = intVal(list_nth(fsplan->fdw_private,
2969 : : FdwDirectModifyPrivateMinRTIndex));
2970 : 2 : int rtoffset = bms_next_member(fsplan->fs_base_relids, -1) -
2971 : : min_base_rti;
2972 : :
2973 : : Assert(min_base_rti > 0);
2974 : : Assert(rtoffset >= 0);
2975 : :
2976 : 2 : tupdesc = get_tupdesc_for_join_scan_tuples(node, rtfuncdata, rtoffset);
2977 : : }
2978 : : else
2979 : 16 : tupdesc = RelationGetDescr(dmstate->rel);
2980 : :
2981 : 18 : dmstate->attinmeta = TupleDescGetAttInMetadata(tupdesc);
2982 : :
2983 : : /*
2984 : : * When performing an UPDATE/DELETE .. RETURNING on a join directly,
2985 : : * initialize a filter to extract an updated/deleted tuple from a scan
2986 : : * tuple.
2987 : : */
2988 [ + + ]: 18 : if (fsplan->scan.scanrelid == 0)
2989 : 2 : init_returning_filter(dmstate, fsplan->fdw_scan_tlist, rtindex);
2990 : : }
2991 : :
2992 : : /*
2993 : : * Prepare for processing of parameters used in remote query, if any.
2994 : : */
2995 : 75 : numParams = list_length(fsplan->fdw_exprs);
2996 : 75 : dmstate->numParams = numParams;
2997 [ + + ]: 75 : if (numParams > 0)
2998 : 1 : prepare_query_params((PlanState *) node,
2999 : : fsplan->fdw_exprs,
3000 : : numParams,
3001 : : &dmstate->param_flinfo,
3002 : : &dmstate->param_exprs,
3003 : : &dmstate->param_values);
3004 : : }
3005 : :
3006 : : /*
3007 : : * postgresIterateDirectModify
3008 : : * Execute a direct foreign table modification
3009 : : */
3010 : : static TupleTableSlot *
3011 : 423 : postgresIterateDirectModify(ForeignScanState *node)
3012 : : {
3013 : 423 : PgFdwDirectModifyState *dmstate = (PgFdwDirectModifyState *) node->fdw_state;
3014 : 423 : EState *estate = node->ss.ps.state;
3015 : 423 : ResultRelInfo *resultRelInfo = node->resultRelInfo;
3016 : :
3017 : : /*
3018 : : * If this is the first call after Begin, execute the statement.
3019 : : */
3020 [ + + ]: 423 : if (dmstate->num_tuples == -1)
3021 : 74 : execute_dml_stmt(node);
3022 : :
3023 : : /*
3024 : : * If the local query doesn't specify RETURNING, just clear tuple slot.
3025 : : */
3026 [ + + ]: 419 : if (!resultRelInfo->ri_projectReturning)
3027 : : {
3028 : 51 : TupleTableSlot *slot = node->ss.ss_ScanTupleSlot;
3029 : 51 : NodeInstrumentation *instr = node->ss.ps.instrument;
3030 : :
3031 : : Assert(!dmstate->has_returning);
3032 : :
3033 : : /* Increment the command es_processed count if necessary. */
3034 [ + - ]: 51 : if (dmstate->set_processed)
3035 : 51 : estate->es_processed += dmstate->num_tuples;
3036 : :
3037 : : /* Increment the tuple count for EXPLAIN ANALYZE if necessary. */
3038 [ - + ]: 51 : if (instr)
3039 : 0 : instr->tuplecount += dmstate->num_tuples;
3040 : :
3041 : 51 : return ExecClearTuple(slot);
3042 : : }
3043 : :
3044 : : /*
3045 : : * Get the next RETURNING tuple.
3046 : : */
3047 : 368 : return get_returning_data(node);
3048 : : }
3049 : :
3050 : : /*
3051 : : * postgresEndDirectModify
3052 : : * Finish a direct foreign table modification
3053 : : */
3054 : : static void
3055 : 100 : postgresEndDirectModify(ForeignScanState *node)
3056 : : {
3057 : 100 : PgFdwDirectModifyState *dmstate = (PgFdwDirectModifyState *) node->fdw_state;
3058 : :
3059 : : /* if dmstate is NULL, we are in EXPLAIN; nothing to do */
3060 [ + + ]: 100 : if (dmstate == NULL)
3061 : 33 : return;
3062 : :
3063 : : /* Release PGresult */
3064 : 67 : PQclear(dmstate->result);
3065 : :
3066 : : /* Release remote connection */
3067 : 67 : ReleaseConnection(dmstate->conn);
3068 : 67 : dmstate->conn = NULL;
3069 : :
3070 : : /* MemoryContext will be deleted automatically. */
3071 : : }
3072 : :
3073 : : /*
3074 : : * postgresExplainForeignScan
3075 : : * Produce extra output for EXPLAIN of a ForeignScan on a foreign table
3076 : : */
3077 : : static void
3078 : 467 : postgresExplainForeignScan(ForeignScanState *node, ExplainState *es)
3079 : : {
3080 : 467 : ForeignScan *plan = castNode(ForeignScan, node->ss.ps.plan);
3081 : 467 : List *fdw_private = plan->fdw_private;
3082 : :
3083 : : /*
3084 : : * Identify foreign scans that are really joins or upper relations. The
3085 : : * input looks something like "(1) LEFT JOIN (2)", and we must replace the
3086 : : * digit string(s), which are RT indexes, with the correct relation names.
3087 : : * We do that here, not when the plan is created, because we can't know
3088 : : * what aliases ruleutils.c will assign at plan creation time.
3089 : : */
3090 [ + - + + ]: 934 : if (list_length(fdw_private) > FdwScanPrivateRelations &&
3091 : 467 : list_nth(fdw_private, FdwScanPrivateRelations) != NULL)
3092 : : {
3093 : : StringInfoData relations;
3094 : : char *rawrelations;
3095 : : char *ptr;
3096 : : int minrti,
3097 : : rtoffset;
3098 : :
3099 : 143 : rawrelations = strVal(list_nth(fdw_private, FdwScanPrivateRelations));
3100 : :
3101 : : /*
3102 : : * A difficulty with using a string representation of RT indexes is
3103 : : * that setrefs.c won't update the string when flattening the
3104 : : * rangetable. To find out what rtoffset was applied, identify the
3105 : : * minimum RT index appearing in the string and compare it to the
3106 : : * minimum member of plan->fs_base_relids. (We expect all the relids
3107 : : * in the join will have been offset by the same amount; the Asserts
3108 : : * below should catch it if that ever changes.)
3109 : : */
3110 : 143 : minrti = INT_MAX;
3111 : 143 : ptr = rawrelations;
3112 [ + + ]: 3338 : while (*ptr)
3113 : : {
3114 [ + + ]: 3195 : if (isdigit((unsigned char) *ptr))
3115 : : {
3116 : 284 : int rti = strtol(ptr, &ptr, 10);
3117 : :
3118 [ + + ]: 284 : if (rti < minrti)
3119 : 155 : minrti = rti;
3120 : : }
3121 : : else
3122 : 2911 : ptr++;
3123 : : }
3124 : 143 : rtoffset = bms_next_member(plan->fs_base_relids, -1) - minrti;
3125 : :
3126 : : /* Now we can translate the string */
3127 : 143 : initStringInfo(&relations);
3128 : 143 : ptr = rawrelations;
3129 [ + + ]: 3338 : while (*ptr)
3130 : : {
3131 [ + + ]: 3195 : if (isdigit((unsigned char) *ptr))
3132 : : {
3133 : 284 : int rti = strtol(ptr, &ptr, 10);
3134 : : RangeTblEntry *rte;
3135 : 284 : char *relname = NULL;
3136 : : char *refname;
3137 : :
3138 : 284 : rti += rtoffset;
3139 : : Assert(bms_is_member(rti, plan->fs_base_relids));
3140 : 284 : rte = rt_fetch(rti, es->rtable);
3141 : :
3142 [ + + ]: 284 : if (rte->rtekind == RTE_FUNCTION)
3143 : : {
3144 : 13 : List *rtfuncdata = list_nth(fdw_private, FdwScanPrivateFunctions);
3145 : : List *funcdata;
3146 : : bool multi_func;
3147 : 13 : bool first = true;
3148 : : ListCell *lc;
3149 : :
3150 : 13 : funcdata = list_nth(rtfuncdata, rti - rtoffset);
3151 : :
3152 : 13 : multi_func = list_length(funcdata) > 1;
3153 : :
3154 [ + + ]: 13 : if (multi_func)
3155 : 4 : appendStringInfoString(&relations, "ROWS FROM (");
3156 : :
3157 [ + - + + : 30 : foreach(lc, funcdata)
+ + ]
3158 : : {
3159 : : List *funcinfo;
3160 : : Oid funcid;
3161 : :
3162 : :
3163 [ + + ]: 17 : if (!first)
3164 : 4 : appendStringInfoString(&relations, ", ");
3165 : :
3166 : 17 : funcinfo = (List *) lfirst(lc);
3167 : :
3168 : 17 : funcid = linitial_node(Integer, funcinfo)->ival;
3169 : : /* Checked by function_rte_pushdown_ok() */
3170 : : Assert(OidIsValid(funcid));
3171 : :
3172 : : /* Match RTE_RELATION behavior */
3173 : 17 : relname = get_func_name(funcid);
3174 [ - + ]: 17 : if (relname == NULL)
3175 [ # # ]: 0 : elog(ERROR, "cache lookup failed for function %u", funcid);
3176 [ + - ]: 17 : if (es->verbose)
3177 : : {
3178 : : char *namespace;
3179 : 17 : Oid nsoid = get_func_namespace(funcid);
3180 : :
3181 : 17 : namespace = get_namespace_name(nsoid);
3182 [ - + ]: 17 : if (namespace == NULL)
3183 [ # # ]: 0 : elog(ERROR, "cache lookup failed for namespace %u", nsoid);
3184 : :
3185 : 17 : appendStringInfo(&relations, "%s.%s()",
3186 : : quote_identifier(namespace),
3187 : : quote_identifier(relname));
3188 : : }
3189 : : else
3190 : 0 : appendStringInfo(&relations, "%s()", quote_identifier(relname));
3191 : :
3192 : 17 : first = false;
3193 : : }
3194 : : /* Close ROWS FROM */
3195 [ + + ]: 13 : if (multi_func)
3196 : 4 : appendStringInfoChar(&relations, ')');
3197 : : }
3198 : : else
3199 : : {
3200 : : Assert(rte->rtekind == RTE_RELATION);
3201 : :
3202 : : /*
3203 : : * This logic should agree with explain.c's
3204 : : * ExplainTargetRel
3205 : : */
3206 : 271 : relname = get_rel_name(rte->relid);
3207 [ + + ]: 271 : if (es->verbose)
3208 : : {
3209 : : char *namespace;
3210 : :
3211 : 255 : namespace = get_namespace_name_or_temp(get_rel_namespace(rte->relid));
3212 : 255 : appendStringInfo(&relations, "%s.%s",
3213 : : quote_identifier(namespace),
3214 : : quote_identifier(relname));
3215 : : }
3216 : : else
3217 : 16 : appendStringInfoString(&relations,
3218 : : quote_identifier(relname));
3219 : : }
3220 : :
3221 : 284 : refname = (char *) list_nth(es->rtable_names, rti - 1);
3222 [ - + ]: 284 : if (refname == NULL)
3223 : 0 : refname = rte->eref->aliasname;
3224 [ + - + + ]: 284 : if (relname == NULL || strcmp(refname, relname) != 0)
3225 : 185 : appendStringInfo(&relations, " %s",
3226 : : quote_identifier(refname));
3227 : : }
3228 : : else
3229 : 2911 : appendStringInfoChar(&relations, *ptr++);
3230 : : }
3231 : 143 : ExplainPropertyText("Relations", relations.data, es);
3232 : : }
3233 : :
3234 : : /*
3235 : : * Add remote query, when VERBOSE option is specified.
3236 : : */
3237 [ + + ]: 467 : if (es->verbose)
3238 : : {
3239 : : char *sql;
3240 : :
3241 : 429 : sql = strVal(list_nth(fdw_private, FdwScanPrivateSelectSql));
3242 : 429 : ExplainPropertyText("Remote SQL", sql, es);
3243 : : }
3244 : 467 : }
3245 : :
3246 : : /*
3247 : : * postgresExplainForeignModify
3248 : : * Produce extra output for EXPLAIN of a ModifyTable on a foreign table
3249 : : */
3250 : : static void
3251 : 47 : postgresExplainForeignModify(ModifyTableState *mtstate,
3252 : : ResultRelInfo *rinfo,
3253 : : List *fdw_private,
3254 : : int subplan_index,
3255 : : ExplainState *es)
3256 : : {
3257 [ + - ]: 47 : if (es->verbose)
3258 : : {
3259 : 47 : char *sql = strVal(list_nth(fdw_private,
3260 : : FdwModifyPrivateUpdateSql));
3261 : :
3262 : 47 : ExplainPropertyText("Remote SQL", sql, es);
3263 : :
3264 : : /*
3265 : : * For INSERT we should always have batch size >= 1, but UPDATE and
3266 : : * DELETE don't support batching so don't show the property.
3267 : : */
3268 [ + + ]: 47 : if (rinfo->ri_BatchSize > 0)
3269 : 13 : ExplainPropertyInteger("Batch Size", NULL, rinfo->ri_BatchSize, es);
3270 : : }
3271 : 47 : }
3272 : :
3273 : : /*
3274 : : * postgresExplainDirectModify
3275 : : * Produce extra output for EXPLAIN of a ForeignScan that modifies a
3276 : : * foreign table directly
3277 : : */
3278 : : static void
3279 : 33 : postgresExplainDirectModify(ForeignScanState *node, ExplainState *es)
3280 : : {
3281 : : List *fdw_private;
3282 : : char *sql;
3283 : :
3284 [ + - ]: 33 : if (es->verbose)
3285 : : {
3286 : 33 : fdw_private = ((ForeignScan *) node->ss.ps.plan)->fdw_private;
3287 : 33 : sql = strVal(list_nth(fdw_private, FdwDirectModifyPrivateUpdateSql));
3288 : 33 : ExplainPropertyText("Remote SQL", sql, es);
3289 : : }
3290 : 33 : }
3291 : :
3292 : : /*
3293 : : * postgresExecForeignTruncate
3294 : : * Truncate one or more foreign tables
3295 : : */
3296 : : static void
3297 : 15 : postgresExecForeignTruncate(List *rels,
3298 : : DropBehavior behavior,
3299 : : bool restart_seqs)
3300 : : {
3301 : 15 : Oid serverid = InvalidOid;
3302 : 15 : UserMapping *user = NULL;
3303 : 15 : PGconn *conn = NULL;
3304 : : StringInfoData sql;
3305 : : ListCell *lc;
3306 : 15 : bool server_truncatable = true;
3307 : :
3308 : : /*
3309 : : * By default, all postgres_fdw foreign tables are assumed truncatable.
3310 : : * This can be overridden by a per-server setting, which in turn can be
3311 : : * overridden by a per-table setting.
3312 : : */
3313 [ + - + + : 29 : foreach(lc, rels)
+ + ]
3314 : : {
3315 : 17 : ForeignServer *server = NULL;
3316 : 17 : Relation rel = lfirst(lc);
3317 : 17 : ForeignTable *table = GetForeignTable(RelationGetRelid(rel));
3318 : : ListCell *cell;
3319 : : bool truncatable;
3320 : :
3321 : : /*
3322 : : * First time through, determine whether the foreign server allows
3323 : : * truncates. Since all specified foreign tables are assumed to belong
3324 : : * to the same foreign server, this result can be used for other
3325 : : * foreign tables.
3326 : : */
3327 [ + + ]: 17 : if (!OidIsValid(serverid))
3328 : : {
3329 : 15 : serverid = table->serverid;
3330 : 15 : server = GetForeignServer(serverid);
3331 : :
3332 [ + - + + : 60 : foreach(cell, server->options)
+ + ]
3333 : : {
3334 : 48 : DefElem *defel = (DefElem *) lfirst(cell);
3335 : :
3336 [ + + ]: 48 : if (strcmp(defel->defname, "truncatable") == 0)
3337 : : {
3338 : 3 : server_truncatable = defGetBoolean(defel);
3339 : 3 : break;
3340 : : }
3341 : : }
3342 : : }
3343 : :
3344 : : /*
3345 : : * Confirm that all specified foreign tables belong to the same
3346 : : * foreign server.
3347 : : */
3348 : : Assert(table->serverid == serverid);
3349 : :
3350 : : /* Determine whether this foreign table allows truncations */
3351 : 17 : truncatable = server_truncatable;
3352 [ + - + + : 34 : foreach(cell, table->options)
+ + ]
3353 : : {
3354 : 24 : DefElem *defel = (DefElem *) lfirst(cell);
3355 : :
3356 [ + + ]: 24 : if (strcmp(defel->defname, "truncatable") == 0)
3357 : : {
3358 : 7 : truncatable = defGetBoolean(defel);
3359 : 7 : break;
3360 : : }
3361 : : }
3362 : :
3363 [ + + ]: 17 : if (!truncatable)
3364 [ + - ]: 3 : ereport(ERROR,
3365 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3366 : : errmsg("foreign table \"%s\" does not allow truncates",
3367 : : RelationGetRelationName(rel))));
3368 : : }
3369 : : Assert(OidIsValid(serverid));
3370 : :
3371 : : /*
3372 : : * Get connection to the foreign server. Connection manager will
3373 : : * establish new connection if necessary.
3374 : : */
3375 : 12 : user = GetUserMapping(GetUserId(), serverid);
3376 : 12 : conn = GetConnection(user, false, NULL);
3377 : :
3378 : : /* Construct the TRUNCATE command string */
3379 : 12 : initStringInfo(&sql);
3380 : 12 : deparseTruncateSql(&sql, rels, behavior, restart_seqs);
3381 : :
3382 : : /* Issue the TRUNCATE command to remote server */
3383 : 12 : do_sql_command(conn, sql.data);
3384 : :
3385 : 11 : pfree(sql.data);
3386 : 11 : }
3387 : :
3388 : : /*
3389 : : * estimate_path_cost_size
3390 : : * Get cost and size estimates for a foreign scan on given foreign relation
3391 : : * either a base relation or a join between foreign relations or an upper
3392 : : * relation containing foreign relations.
3393 : : *
3394 : : * param_join_conds are the parameterization clauses with outer relations.
3395 : : * pathkeys specify the expected sort order if any for given path being costed.
3396 : : * fpextra specifies additional post-scan/join-processing steps such as the
3397 : : * final sort and the LIMIT restriction.
3398 : : *
3399 : : * The function returns the cost and size estimates in p_rows, p_width,
3400 : : * p_disabled_nodes, p_startup_cost and p_total_cost variables.
3401 : : */
3402 : : static void
3403 : 3047 : estimate_path_cost_size(PlannerInfo *root,
3404 : : RelOptInfo *foreignrel,
3405 : : List *param_join_conds,
3406 : : List *pathkeys,
3407 : : PgFdwPathExtraData *fpextra,
3408 : : double *p_rows, int *p_width,
3409 : : int *p_disabled_nodes,
3410 : : Cost *p_startup_cost, Cost *p_total_cost)
3411 : : {
3412 : 3047 : PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) foreignrel->fdw_private;
3413 : : double rows;
3414 : : double retrieved_rows;
3415 : : int width;
3416 : 3047 : int disabled_nodes = 0;
3417 : : Cost startup_cost;
3418 : : Cost total_cost;
3419 : :
3420 : : /* Make sure the core code has set up the relation's reltarget */
3421 : : Assert(foreignrel->reltarget);
3422 : :
3423 : : /*
3424 : : * If the table or the server is configured to use remote estimates,
3425 : : * connect to the foreign server and execute EXPLAIN to estimate the
3426 : : * number of rows selected by the restriction+join clauses. Otherwise,
3427 : : * estimate rows using whatever statistics we have locally, in a way
3428 : : * similar to ordinary tables.
3429 : : */
3430 [ + + ]: 3047 : if (fpinfo->use_remote_estimate)
3431 : : {
3432 : : List *remote_param_join_conds;
3433 : : List *local_param_join_conds;
3434 : : StringInfoData sql;
3435 : : PGconn *conn;
3436 : : Selectivity local_sel;
3437 : : QualCost local_cost;
3438 : 1333 : List *fdw_scan_tlist = NIL;
3439 : : List *remote_conds;
3440 : :
3441 : : /* Required only to be passed to deparseSelectStmtForRel */
3442 : : List *retrieved_attrs;
3443 : :
3444 : : /*
3445 : : * param_join_conds might contain both clauses that are safe to send
3446 : : * across, and clauses that aren't.
3447 : : */
3448 : 1333 : classifyConditions(root, foreignrel, fpinfo, param_join_conds,
3449 : : &remote_param_join_conds, &local_param_join_conds);
3450 : :
3451 : : /* Build the list of columns to be fetched from the foreign server. */
3452 [ + + + + : 1333 : if (IS_JOIN_REL(foreignrel) || IS_UPPER_REL(foreignrel))
+ + - + ]
3453 : 535 : fdw_scan_tlist = build_tlist_to_deparse(foreignrel);
3454 : : else
3455 : 798 : fdw_scan_tlist = NIL;
3456 : :
3457 : : /*
3458 : : * The complete list of remote conditions includes everything from
3459 : : * baserestrictinfo plus any extra join_conds relevant to this
3460 : : * particular path.
3461 : : */
3462 : 1333 : remote_conds = list_concat(remote_param_join_conds,
3463 : 1333 : fpinfo->remote_conds);
3464 : :
3465 : : /*
3466 : : * Construct EXPLAIN query including the desired SELECT, FROM, and
3467 : : * WHERE clauses. Params and other-relation Vars are replaced by dummy
3468 : : * values, so don't request params_list.
3469 : : */
3470 : 1333 : initStringInfo(&sql);
3471 : 1333 : appendStringInfoString(&sql, "EXPLAIN ");
3472 [ + + + + ]: 1419 : deparseSelectStmtForRel(&sql, root, foreignrel, fdw_scan_tlist,
3473 : : remote_conds, pathkeys,
3474 : 43 : fpextra ? fpextra->has_final_sort : false,
3475 : 43 : fpextra ? fpextra->has_limit : false,
3476 : : false, &retrieved_attrs, NULL);
3477 : :
3478 : : /* Get the remote estimate */
3479 : 1333 : conn = GetConnection(fpinfo->user, false, NULL);
3480 : 1333 : get_remote_estimate(sql.data, conn, &rows, &width,
3481 : : &startup_cost, &total_cost);
3482 : 1333 : ReleaseConnection(conn);
3483 : :
3484 : 1333 : retrieved_rows = rows;
3485 : :
3486 : : /* Factor in the selectivity of the locally-checked quals */
3487 : 1333 : local_sel = clauselist_selectivity(root,
3488 : : local_param_join_conds,
3489 : 1333 : foreignrel->relid,
3490 : : JOIN_INNER,
3491 : : NULL);
3492 : 1333 : local_sel *= fpinfo->local_conds_sel;
3493 : :
3494 : 1333 : rows = clamp_row_est(rows * local_sel);
3495 : :
3496 : : /* Add in the eval cost of the locally-checked quals */
3497 : 1333 : startup_cost += fpinfo->local_conds_cost.startup;
3498 : 1333 : total_cost += fpinfo->local_conds_cost.per_tuple * retrieved_rows;
3499 : 1333 : cost_qual_eval(&local_cost, local_param_join_conds, root);
3500 : 1333 : startup_cost += local_cost.startup;
3501 : 1333 : total_cost += local_cost.per_tuple * retrieved_rows;
3502 : :
3503 : : /*
3504 : : * Add in tlist eval cost for each output row. In case of an
3505 : : * aggregate, some of the tlist expressions such as grouping
3506 : : * expressions will be evaluated remotely, so adjust the costs.
3507 : : */
3508 : 1333 : startup_cost += foreignrel->reltarget->cost.startup;
3509 : 1333 : total_cost += foreignrel->reltarget->cost.startup;
3510 : 1333 : total_cost += foreignrel->reltarget->cost.per_tuple * rows;
3511 [ + + - + ]: 1333 : if (IS_UPPER_REL(foreignrel))
3512 : : {
3513 : : QualCost tlist_cost;
3514 : :
3515 : 44 : cost_qual_eval(&tlist_cost, fdw_scan_tlist, root);
3516 : 44 : startup_cost -= tlist_cost.startup;
3517 : 44 : total_cost -= tlist_cost.startup;
3518 : 44 : total_cost -= tlist_cost.per_tuple * rows;
3519 : : }
3520 : : }
3521 : : else
3522 : : {
3523 : 1714 : Cost run_cost = 0;
3524 : :
3525 : : /*
3526 : : * We don't support join conditions in this mode (hence, no
3527 : : * parameterized paths can be made).
3528 : : */
3529 : : Assert(param_join_conds == NIL);
3530 : :
3531 : : /*
3532 : : * We will come here again and again with different set of pathkeys or
3533 : : * additional post-scan/join-processing steps that caller wants to
3534 : : * cost. We don't need to calculate the cost/size estimates for the
3535 : : * underlying scan, join, or grouping each time. Instead, use those
3536 : : * estimates if we have cached them already.
3537 : : */
3538 [ + + + - ]: 1714 : if (fpinfo->rel_startup_cost >= 0 && fpinfo->rel_total_cost >= 0)
3539 : : {
3540 : : Assert(fpinfo->retrieved_rows >= 0);
3541 : :
3542 : 425 : rows = fpinfo->rows;
3543 : 425 : retrieved_rows = fpinfo->retrieved_rows;
3544 : 425 : width = fpinfo->width;
3545 : 425 : startup_cost = fpinfo->rel_startup_cost;
3546 : 425 : run_cost = fpinfo->rel_total_cost - fpinfo->rel_startup_cost;
3547 : :
3548 : : /*
3549 : : * If we estimate the costs of a foreign scan or a foreign join
3550 : : * with additional post-scan/join-processing steps, the scan or
3551 : : * join costs obtained from the cache wouldn't yet contain the
3552 : : * eval costs for the final scan/join target, which would've been
3553 : : * updated by apply_scanjoin_target_to_paths(); add the eval costs
3554 : : * now.
3555 : : */
3556 [ + + + + : 425 : if (fpextra && !IS_UPPER_REL(foreignrel))
+ - ]
3557 : : {
3558 : : /* Shouldn't get here unless we have LIMIT */
3559 : : Assert(fpextra->has_limit);
3560 : : Assert(foreignrel->reloptkind == RELOPT_BASEREL ||
3561 : : foreignrel->reloptkind == RELOPT_JOINREL);
3562 : 95 : startup_cost += foreignrel->reltarget->cost.startup;
3563 : 95 : run_cost += foreignrel->reltarget->cost.per_tuple * rows;
3564 : : }
3565 : : }
3566 [ + + + + ]: 1289 : else if (IS_JOIN_REL(foreignrel))
3567 : 154 : {
3568 : : PgFdwRelationInfo *fpinfo_i;
3569 : : PgFdwRelationInfo *fpinfo_o;
3570 : : QualCost join_cost;
3571 : : QualCost remote_conds_cost;
3572 : : double nrows;
3573 : :
3574 : : /* Use rows/width estimates made by the core code. */
3575 : 154 : rows = foreignrel->rows;
3576 : 154 : width = foreignrel->reltarget->width;
3577 : :
3578 : : /* For join we expect inner and outer relations set */
3579 : : Assert(fpinfo->innerrel && fpinfo->outerrel);
3580 : :
3581 : : /*
3582 : : * For a FUNCTION RTE absorbed into the join, use the stub fpinfo
3583 : : * we built in foreign_join_ok(), since the function rel itself
3584 : : * has no fdw_private.
3585 : : */
3586 : 308 : fpinfo_i = fpinfo->inner_func_fpinfo ?
3587 [ + + ]: 154 : fpinfo->inner_func_fpinfo :
3588 : 131 : (PgFdwRelationInfo *) fpinfo->innerrel->fdw_private;
3589 : 308 : fpinfo_o = fpinfo->outer_func_fpinfo ?
3590 [ + + ]: 154 : fpinfo->outer_func_fpinfo :
3591 : 148 : (PgFdwRelationInfo *) fpinfo->outerrel->fdw_private;
3592 : :
3593 : : /* Estimate of number of rows in cross product */
3594 : 154 : nrows = fpinfo_i->rows * fpinfo_o->rows;
3595 : :
3596 : : /*
3597 : : * Back into an estimate of the number of retrieved rows. Just in
3598 : : * case this is nuts, clamp to at most nrows.
3599 : : */
3600 : 154 : retrieved_rows = clamp_row_est(rows / fpinfo->local_conds_sel);
3601 [ + + ]: 154 : retrieved_rows = Min(retrieved_rows, nrows);
3602 : :
3603 : : /*
3604 : : * The cost of foreign join is estimated as cost of generating
3605 : : * rows for the joining relations + cost for applying quals on the
3606 : : * rows.
3607 : : */
3608 : :
3609 : : /*
3610 : : * Calculate the cost of clauses pushed down to the foreign server
3611 : : */
3612 : 154 : cost_qual_eval(&remote_conds_cost, fpinfo->remote_conds, root);
3613 : : /* Calculate the cost of applying join clauses */
3614 : 154 : cost_qual_eval(&join_cost, fpinfo->joinclauses, root);
3615 : :
3616 : : /*
3617 : : * Startup cost includes startup cost of joining relations and the
3618 : : * startup cost for join and other clauses. We do not include the
3619 : : * startup cost specific to join strategy (e.g. setting up hash
3620 : : * tables) since we do not know what strategy the foreign server
3621 : : * is going to use.
3622 : : */
3623 : 154 : startup_cost = fpinfo_i->rel_startup_cost + fpinfo_o->rel_startup_cost;
3624 : 154 : startup_cost += join_cost.startup;
3625 : 154 : startup_cost += remote_conds_cost.startup;
3626 : 154 : startup_cost += fpinfo->local_conds_cost.startup;
3627 : :
3628 : : /*
3629 : : * Run time cost includes:
3630 : : *
3631 : : * 1. Run time cost (total_cost - startup_cost) of relations being
3632 : : * joined
3633 : : *
3634 : : * 2. Run time cost of applying join clauses on the cross product
3635 : : * of the joining relations.
3636 : : *
3637 : : * 3. Run time cost of applying pushed down other clauses on the
3638 : : * result of join
3639 : : *
3640 : : * 4. Run time cost of applying nonpushable other clauses locally
3641 : : * on the result fetched from the foreign server.
3642 : : */
3643 : 154 : run_cost = fpinfo_i->rel_total_cost - fpinfo_i->rel_startup_cost;
3644 : 154 : run_cost += fpinfo_o->rel_total_cost - fpinfo_o->rel_startup_cost;
3645 : 154 : run_cost += nrows * join_cost.per_tuple;
3646 : 154 : nrows = clamp_row_est(nrows * fpinfo->joinclause_sel);
3647 : 154 : run_cost += nrows * remote_conds_cost.per_tuple;
3648 : 154 : run_cost += fpinfo->local_conds_cost.per_tuple * retrieved_rows;
3649 : :
3650 : : /* Add in tlist eval cost for each output row */
3651 : 154 : startup_cost += foreignrel->reltarget->cost.startup;
3652 : 154 : run_cost += foreignrel->reltarget->cost.per_tuple * rows;
3653 : : }
3654 [ + + + + ]: 1135 : else if (IS_UPPER_REL(foreignrel))
3655 : 101 : {
3656 : 101 : RelOptInfo *outerrel = fpinfo->outerrel;
3657 : : PgFdwRelationInfo *ofpinfo;
3658 : 101 : AggClauseCosts aggcosts = {0};
3659 : : double input_rows;
3660 : : int numGroupCols;
3661 : 101 : double numGroups = 1;
3662 : :
3663 : : /* The upper relation should have its outer relation set */
3664 : : Assert(outerrel);
3665 : : /* and that outer relation should have its reltarget set */
3666 : : Assert(outerrel->reltarget);
3667 : :
3668 : : /*
3669 : : * This cost model is mixture of costing done for sorted and
3670 : : * hashed aggregates in cost_agg(). We are not sure which
3671 : : * strategy will be considered at remote side, thus for
3672 : : * simplicity, we put all startup related costs in startup_cost
3673 : : * and all finalization and run cost are added in total_cost.
3674 : : */
3675 : :
3676 : 101 : ofpinfo = (PgFdwRelationInfo *) outerrel->fdw_private;
3677 : :
3678 : : /* Get rows from input rel */
3679 : 101 : input_rows = ofpinfo->rows;
3680 : :
3681 : : /* Collect statistics about aggregates for estimating costs. */
3682 [ + + ]: 101 : if (root->parse->hasAggs)
3683 : : {
3684 : 97 : get_agg_clause_costs(root, AGGSPLIT_SIMPLE, &aggcosts);
3685 : : }
3686 : :
3687 : : /* Get number of grouping columns and possible number of groups */
3688 : 101 : numGroupCols = list_length(root->processed_groupClause);
3689 : 101 : numGroups = estimate_num_groups(root,
3690 : : get_sortgrouplist_exprs(root->processed_groupClause,
3691 : : fpinfo->grouped_tlist),
3692 : : input_rows, NULL, NULL);
3693 : :
3694 : : /*
3695 : : * Get the retrieved_rows and rows estimates. If there are HAVING
3696 : : * quals, account for their selectivity.
3697 : : */
3698 [ + + ]: 101 : if (root->hasHavingQual)
3699 : : {
3700 : : /* Factor in the selectivity of the remotely-checked quals */
3701 : : retrieved_rows =
3702 : 14 : clamp_row_est(numGroups *
3703 : 14 : clauselist_selectivity(root,
3704 : : fpinfo->remote_conds,
3705 : : 0,
3706 : : JOIN_INNER,
3707 : : NULL));
3708 : : /* Factor in the selectivity of the locally-checked quals */
3709 : 14 : rows = clamp_row_est(retrieved_rows * fpinfo->local_conds_sel);
3710 : : }
3711 : : else
3712 : : {
3713 : 87 : rows = retrieved_rows = numGroups;
3714 : : }
3715 : :
3716 : : /* Use width estimate made by the core code. */
3717 : 101 : width = foreignrel->reltarget->width;
3718 : :
3719 : : /*-----
3720 : : * Startup cost includes:
3721 : : * 1. Startup cost for underneath input relation, adjusted for
3722 : : * tlist replacement by apply_scanjoin_target_to_paths()
3723 : : * 2. Cost of performing aggregation, per cost_agg()
3724 : : *-----
3725 : : */
3726 : 101 : startup_cost = ofpinfo->rel_startup_cost;
3727 : 101 : startup_cost += outerrel->reltarget->cost.startup;
3728 : 101 : startup_cost += aggcosts.transCost.startup;
3729 : 101 : startup_cost += aggcosts.transCost.per_tuple * input_rows;
3730 : 101 : startup_cost += aggcosts.finalCost.startup;
3731 : 101 : startup_cost += (cpu_operator_cost * numGroupCols) * input_rows;
3732 : :
3733 : : /*-----
3734 : : * Run time cost includes:
3735 : : * 1. Run time cost of underneath input relation, adjusted for
3736 : : * tlist replacement by apply_scanjoin_target_to_paths()
3737 : : * 2. Run time cost of performing aggregation, per cost_agg()
3738 : : *-----
3739 : : */
3740 : 101 : run_cost = ofpinfo->rel_total_cost - ofpinfo->rel_startup_cost;
3741 : 101 : run_cost += outerrel->reltarget->cost.per_tuple * input_rows;
3742 : 101 : run_cost += aggcosts.finalCost.per_tuple * numGroups;
3743 : 101 : run_cost += cpu_tuple_cost * numGroups;
3744 : :
3745 : : /* Account for the eval cost of HAVING quals, if any */
3746 [ + + ]: 101 : if (root->hasHavingQual)
3747 : : {
3748 : : QualCost remote_cost;
3749 : :
3750 : : /* Add in the eval cost of the remotely-checked quals */
3751 : 14 : cost_qual_eval(&remote_cost, fpinfo->remote_conds, root);
3752 : 14 : startup_cost += remote_cost.startup;
3753 : 14 : run_cost += remote_cost.per_tuple * numGroups;
3754 : : /* Add in the eval cost of the locally-checked quals */
3755 : 14 : startup_cost += fpinfo->local_conds_cost.startup;
3756 : 14 : run_cost += fpinfo->local_conds_cost.per_tuple * retrieved_rows;
3757 : : }
3758 : :
3759 : : /* Add in tlist eval cost for each output row */
3760 : 101 : startup_cost += foreignrel->reltarget->cost.startup;
3761 : 101 : run_cost += foreignrel->reltarget->cost.per_tuple * rows;
3762 : : }
3763 : : else
3764 : : {
3765 : : Cost cpu_per_tuple;
3766 : :
3767 : : /* Use rows/width estimates made by set_baserel_size_estimates. */
3768 : 1034 : rows = foreignrel->rows;
3769 : 1034 : width = foreignrel->reltarget->width;
3770 : :
3771 : : /*
3772 : : * Back into an estimate of the number of retrieved rows. Just in
3773 : : * case this is nuts, clamp to at most foreignrel->tuples.
3774 : : */
3775 : 1034 : retrieved_rows = clamp_row_est(rows / fpinfo->local_conds_sel);
3776 [ + + ]: 1034 : retrieved_rows = Min(retrieved_rows, foreignrel->tuples);
3777 : :
3778 : : /*
3779 : : * Cost as though this were a seqscan, which is pessimistic. We
3780 : : * effectively imagine the local_conds are being evaluated
3781 : : * remotely, too.
3782 : : */
3783 : 1034 : startup_cost = 0;
3784 : 1034 : run_cost = 0;
3785 : 1034 : run_cost += seq_page_cost * foreignrel->pages;
3786 : :
3787 : 1034 : startup_cost += foreignrel->baserestrictcost.startup;
3788 : 1034 : cpu_per_tuple = cpu_tuple_cost + foreignrel->baserestrictcost.per_tuple;
3789 : 1034 : run_cost += cpu_per_tuple * foreignrel->tuples;
3790 : :
3791 : : /* Add in tlist eval cost for each output row */
3792 : 1034 : startup_cost += foreignrel->reltarget->cost.startup;
3793 : 1034 : run_cost += foreignrel->reltarget->cost.per_tuple * rows;
3794 : : }
3795 : :
3796 : : /*
3797 : : * Without remote estimates, we have no real way to estimate the cost
3798 : : * of generating sorted output. It could be free if the query plan
3799 : : * the remote side would have chosen generates properly-sorted output
3800 : : * anyway, but in most cases it will cost something. Estimate a value
3801 : : * high enough that we won't pick the sorted path when the ordering
3802 : : * isn't locally useful, but low enough that we'll err on the side of
3803 : : * pushing down the ORDER BY clause when it's useful to do so.
3804 : : */
3805 [ + + ]: 1714 : if (pathkeys != NIL)
3806 : : {
3807 [ + + - + ]: 366 : if (IS_UPPER_REL(foreignrel))
3808 : : {
3809 : : Assert(foreignrel->reloptkind == RELOPT_UPPER_REL &&
3810 : : fpinfo->stage == UPPERREL_GROUP_AGG);
3811 : :
3812 : : /*
3813 : : * We can only get here when this function is called from
3814 : : * add_foreign_ordered_paths() or add_foreign_final_paths();
3815 : : * in which cases, the passed-in fpextra should not be NULL.
3816 : : */
3817 : : Assert(fpextra);
3818 : 30 : adjust_foreign_grouping_path_cost(root, pathkeys,
3819 : : retrieved_rows, width,
3820 : : fpextra->limit_tuples,
3821 : : &disabled_nodes,
3822 : : &startup_cost, &run_cost);
3823 : : }
3824 : : else
3825 : : {
3826 : 336 : startup_cost *= DEFAULT_FDW_SORT_MULTIPLIER;
3827 : 336 : run_cost *= DEFAULT_FDW_SORT_MULTIPLIER;
3828 : : }
3829 : : }
3830 : :
3831 : 1714 : total_cost = startup_cost + run_cost;
3832 : :
3833 : : /* Adjust the cost estimates if we have LIMIT */
3834 [ + + + + ]: 1714 : if (fpextra && fpextra->has_limit)
3835 : : {
3836 : 97 : adjust_limit_rows_costs(&rows, &startup_cost, &total_cost,
3837 : : fpextra->offset_est, fpextra->count_est);
3838 : 97 : retrieved_rows = rows;
3839 : : }
3840 : : }
3841 : :
3842 : : /*
3843 : : * If this includes the final sort step, the given target, which will be
3844 : : * applied to the resulting path, might have different expressions from
3845 : : * the foreignrel's reltarget (see make_sort_input_target()); adjust tlist
3846 : : * eval costs.
3847 : : */
3848 [ + + + + ]: 3047 : if (fpextra && fpextra->has_final_sort &&
3849 [ + + ]: 115 : fpextra->target != foreignrel->reltarget)
3850 : : {
3851 : 6 : QualCost oldcost = foreignrel->reltarget->cost;
3852 : 6 : QualCost newcost = fpextra->target->cost;
3853 : :
3854 : 6 : startup_cost += newcost.startup - oldcost.startup;
3855 : 6 : total_cost += newcost.startup - oldcost.startup;
3856 : 6 : total_cost += (newcost.per_tuple - oldcost.per_tuple) * rows;
3857 : : }
3858 : :
3859 : : /*
3860 : : * Cache the retrieved rows and cost estimates for scans, joins, or
3861 : : * groupings without any parameterization, pathkeys, or additional
3862 : : * post-scan/join-processing steps, before adding the costs for
3863 : : * transferring data from the foreign server. These estimates are useful
3864 : : * for costing remote joins involving this relation or costing other
3865 : : * remote operations on this relation such as remote sorts and remote
3866 : : * LIMIT restrictions, when the costs can not be obtained from the foreign
3867 : : * server. This function will be called at least once for every foreign
3868 : : * relation without any parameterization, pathkeys, or additional
3869 : : * post-scan/join-processing steps.
3870 : : */
3871 [ + + + + : 3047 : if (pathkeys == NIL && param_join_conds == NIL && fpextra == NULL)
+ + ]
3872 : : {
3873 : 1861 : fpinfo->retrieved_rows = retrieved_rows;
3874 : 1861 : fpinfo->rel_startup_cost = startup_cost;
3875 : 1861 : fpinfo->rel_total_cost = total_cost;
3876 : : }
3877 : :
3878 : : /*
3879 : : * Add some additional cost factors to account for connection overhead
3880 : : * (fdw_startup_cost), transferring data across the network
3881 : : * (fdw_tuple_cost per retrieved row), and local manipulation of the data
3882 : : * (cpu_tuple_cost per retrieved row).
3883 : : */
3884 : 3047 : startup_cost += fpinfo->fdw_startup_cost;
3885 : 3047 : total_cost += fpinfo->fdw_startup_cost;
3886 : 3047 : total_cost += fpinfo->fdw_tuple_cost * retrieved_rows;
3887 : 3047 : total_cost += cpu_tuple_cost * retrieved_rows;
3888 : :
3889 : : /*
3890 : : * If we have LIMIT, we should prefer performing the restriction remotely
3891 : : * rather than locally, as the former avoids extra row fetches from the
3892 : : * remote that the latter might cause. But since the core code doesn't
3893 : : * account for such fetches when estimating the costs of the local
3894 : : * restriction (see create_limit_path()), there would be no difference
3895 : : * between the costs of the local restriction and the costs of the remote
3896 : : * restriction estimated above if we don't use remote estimates (except
3897 : : * for the case where the foreignrel is a grouping relation, the given
3898 : : * pathkeys is not NIL, and the effects of a bounded sort for that rel is
3899 : : * accounted for in costing the remote restriction). Tweak the costs of
3900 : : * the remote restriction to ensure we'll prefer it if LIMIT is a useful
3901 : : * one.
3902 : : */
3903 [ + + + + ]: 3047 : if (!fpinfo->use_remote_estimate &&
3904 [ + + ]: 127 : fpextra && fpextra->has_limit &&
3905 [ + - ]: 97 : fpextra->limit_tuples > 0 &&
3906 [ + + ]: 97 : fpextra->limit_tuples < fpinfo->rows)
3907 : : {
3908 : : Assert(fpinfo->rows > 0);
3909 : 90 : total_cost -= (total_cost - startup_cost) * 0.05 *
3910 : 90 : (fpinfo->rows - fpextra->limit_tuples) / fpinfo->rows;
3911 : : }
3912 : :
3913 : : /* Return results. */
3914 : 3047 : *p_rows = rows;
3915 : 3047 : *p_width = width;
3916 : 3047 : *p_disabled_nodes = disabled_nodes;
3917 : 3047 : *p_startup_cost = startup_cost;
3918 : 3047 : *p_total_cost = total_cost;
3919 : 3047 : }
3920 : :
3921 : : /*
3922 : : * Estimate costs of executing a SQL statement remotely.
3923 : : * The given "sql" must be an EXPLAIN command.
3924 : : */
3925 : : static void
3926 : 1333 : get_remote_estimate(const char *sql, PGconn *conn,
3927 : : double *rows, int *width,
3928 : : Cost *startup_cost, Cost *total_cost)
3929 : : {
3930 : : PGresult *res;
3931 : : char *line;
3932 : : char *p;
3933 : : int n;
3934 : :
3935 : : /*
3936 : : * Execute EXPLAIN remotely.
3937 : : */
3938 : 1333 : res = pgfdw_exec_query(conn, sql, NULL);
3939 [ - + ]: 1333 : if (PQresultStatus(res) != PGRES_TUPLES_OK)
3940 : 0 : pgfdw_report_error(res, conn, sql);
3941 : :
3942 : : /*
3943 : : * Extract cost numbers for topmost plan node. Note we search for a left
3944 : : * paren from the end of the line to avoid being confused by other uses of
3945 : : * parentheses.
3946 : : */
3947 : 1333 : line = PQgetvalue(res, 0, 0);
3948 : 1333 : p = strrchr(line, '(');
3949 [ - + ]: 1333 : if (p == NULL)
3950 [ # # ]: 0 : elog(ERROR, "could not interpret EXPLAIN output: \"%s\"", line);
3951 : 1333 : n = sscanf(p, "(cost=%lf..%lf rows=%lf width=%d)",
3952 : : startup_cost, total_cost, rows, width);
3953 [ - + ]: 1333 : if (n != 4)
3954 [ # # ]: 0 : elog(ERROR, "could not interpret EXPLAIN output: \"%s\"", line);
3955 : 1333 : PQclear(res);
3956 : 1333 : }
3957 : :
3958 : : /*
3959 : : * Adjust the cost estimates of a foreign grouping path to include the cost of
3960 : : * generating properly-sorted output.
3961 : : */
3962 : : static void
3963 : 30 : adjust_foreign_grouping_path_cost(PlannerInfo *root,
3964 : : List *pathkeys,
3965 : : double retrieved_rows,
3966 : : double width,
3967 : : double limit_tuples,
3968 : : int *p_disabled_nodes,
3969 : : Cost *p_startup_cost,
3970 : : Cost *p_run_cost)
3971 : : {
3972 : : /*
3973 : : * If the GROUP BY clause isn't sort-able, the plan chosen by the remote
3974 : : * side is unlikely to generate properly-sorted output, so it would need
3975 : : * an explicit sort; adjust the given costs with cost_sort(). Likewise,
3976 : : * if the GROUP BY clause is sort-able but isn't a superset of the given
3977 : : * pathkeys, adjust the costs with that function. Otherwise, adjust the
3978 : : * costs by applying the same heuristic as for the scan or join case.
3979 : : */
3980 [ + - ]: 30 : if (!grouping_is_sortable(root->processed_groupClause) ||
3981 [ + + ]: 30 : !pathkeys_contained_in(pathkeys, root->group_pathkeys))
3982 : 22 : {
3983 : : Path sort_path; /* dummy for result of cost_sort */
3984 : :
3985 : 22 : cost_sort(&sort_path,
3986 : : root,
3987 : : pathkeys,
3988 : : 0,
3989 : 22 : *p_startup_cost + *p_run_cost,
3990 : : retrieved_rows,
3991 : : width,
3992 : : 0.0,
3993 : : work_mem,
3994 : : limit_tuples);
3995 : :
3996 : 22 : *p_startup_cost = sort_path.startup_cost;
3997 : 22 : *p_run_cost = sort_path.total_cost - sort_path.startup_cost;
3998 : : }
3999 : : else
4000 : : {
4001 : : /*
4002 : : * The default extra cost seems too large for foreign-grouping cases;
4003 : : * add 1/4th of that default.
4004 : : */
4005 : 8 : double sort_multiplier = 1.0 + (DEFAULT_FDW_SORT_MULTIPLIER
4006 : : - 1.0) * 0.25;
4007 : :
4008 : 8 : *p_startup_cost *= sort_multiplier;
4009 : 8 : *p_run_cost *= sort_multiplier;
4010 : : }
4011 : 30 : }
4012 : :
4013 : : /*
4014 : : * Detect whether we want to process an EquivalenceClass member.
4015 : : *
4016 : : * This is a callback for use by generate_implied_equalities_for_column.
4017 : : */
4018 : : static bool
4019 : 314 : ec_member_matches_foreign(PlannerInfo *root, RelOptInfo *rel,
4020 : : EquivalenceClass *ec, EquivalenceMember *em,
4021 : : void *arg)
4022 : : {
4023 : 314 : ec_member_foreign_arg *state = (ec_member_foreign_arg *) arg;
4024 : 314 : Expr *expr = em->em_expr;
4025 : :
4026 : : /*
4027 : : * If we've identified what we're processing in the current scan, we only
4028 : : * want to match that expression.
4029 : : */
4030 [ - + ]: 314 : if (state->current != NULL)
4031 : 0 : return equal(expr, state->current);
4032 : :
4033 : : /*
4034 : : * Otherwise, ignore anything we've already processed.
4035 : : */
4036 [ + + ]: 314 : if (list_member(state->already_used, expr))
4037 : 165 : return false;
4038 : :
4039 : : /* This is the new target to process. */
4040 : 149 : state->current = expr;
4041 : 149 : return true;
4042 : : }
4043 : :
4044 : : /*
4045 : : * Create cursor for node's query with current parameter values.
4046 : : */
4047 : : static void
4048 : 940 : create_cursor(ForeignScanState *node)
4049 : : {
4050 : 940 : PgFdwScanState *fsstate = (PgFdwScanState *) node->fdw_state;
4051 : 940 : ExprContext *econtext = node->ss.ps.ps_ExprContext;
4052 : 940 : int numParams = fsstate->numParams;
4053 : 940 : const char **values = fsstate->param_values;
4054 : 940 : PGconn *conn = fsstate->conn;
4055 : : StringInfoData buf;
4056 : : PGresult *res;
4057 : :
4058 : : /* First, process a pending asynchronous request, if any. */
4059 [ + + ]: 940 : if (fsstate->conn_state->pendingAreq)
4060 : 1 : process_pending_request(fsstate->conn_state->pendingAreq);
4061 : :
4062 : : /*
4063 : : * Construct array of query parameter values in text format. We do the
4064 : : * conversions in the short-lived per-tuple context, so as not to cause a
4065 : : * memory leak over repeated scans.
4066 : : */
4067 [ + + ]: 940 : if (numParams > 0)
4068 : : {
4069 : : MemoryContext oldcontext;
4070 : :
4071 : 402 : oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
4072 : :
4073 : 402 : process_query_params(econtext,
4074 : : fsstate->param_flinfo,
4075 : : fsstate->param_exprs,
4076 : : values);
4077 : :
4078 : 402 : MemoryContextSwitchTo(oldcontext);
4079 : : }
4080 : :
4081 : : /* Construct the DECLARE CURSOR command */
4082 : 940 : initStringInfo(&buf);
4083 : 940 : appendStringInfo(&buf, "DECLARE c%u CURSOR FOR\n%s",
4084 : : fsstate->cursor_number, fsstate->query);
4085 : :
4086 : : /*
4087 : : * Notice that we pass NULL for paramTypes, thus forcing the remote server
4088 : : * to infer types for all parameters. Since we explicitly cast every
4089 : : * parameter (see deparse.c), the "inference" is trivial and will produce
4090 : : * the desired result. This allows us to avoid assuming that the remote
4091 : : * server has the same OIDs we do for the parameters' types.
4092 : : */
4093 [ + + ]: 940 : if (!PQsendQueryParams(conn, buf.data, numParams,
4094 : : NULL, values, NULL, NULL, 0))
4095 : 1 : pgfdw_report_error(NULL, conn, buf.data);
4096 : :
4097 : : /*
4098 : : * Get the result, and check for success.
4099 : : */
4100 : 939 : res = pgfdw_get_result(conn);
4101 [ + + ]: 939 : if (PQresultStatus(res) != PGRES_COMMAND_OK)
4102 : 4 : pgfdw_report_error(res, conn, fsstate->query);
4103 : 935 : PQclear(res);
4104 : :
4105 : : /* Mark the cursor as created, and show no tuples have been retrieved */
4106 : 935 : fsstate->cursor_exists = true;
4107 : 935 : fsstate->tuples = NULL;
4108 : 935 : fsstate->num_tuples = 0;
4109 : 935 : fsstate->next_tuple = 0;
4110 : 935 : fsstate->fetch_ct_2 = 0;
4111 : 935 : fsstate->eof_reached = false;
4112 : :
4113 : : /* Clean up */
4114 : 935 : pfree(buf.data);
4115 : 935 : }
4116 : :
4117 : : /*
4118 : : * Fetch some more rows from the node's cursor.
4119 : : */
4120 : : static void
4121 : 1638 : fetch_more_data(ForeignScanState *node)
4122 : : {
4123 : 1638 : PgFdwScanState *fsstate = (PgFdwScanState *) node->fdw_state;
4124 : 1638 : PGconn *conn = fsstate->conn;
4125 : : PGresult *res;
4126 : : int numrows;
4127 : : int i;
4128 : : MemoryContext oldcontext;
4129 : :
4130 : : /*
4131 : : * We'll store the tuples in the batch_cxt. First, flush the previous
4132 : : * batch.
4133 : : */
4134 : 1638 : fsstate->tuples = NULL;
4135 : 1638 : MemoryContextReset(fsstate->batch_cxt);
4136 : 1638 : oldcontext = MemoryContextSwitchTo(fsstate->batch_cxt);
4137 : :
4138 [ + + ]: 1638 : if (fsstate->async_capable)
4139 : : {
4140 : : Assert(fsstate->conn_state->pendingAreq);
4141 : :
4142 : : /*
4143 : : * The query was already sent by an earlier call to
4144 : : * fetch_more_data_begin. So now we just fetch the result.
4145 : : */
4146 : 228 : res = pgfdw_get_result(conn);
4147 : : /* On error, report the original query, not the FETCH. */
4148 [ - + ]: 228 : if (PQresultStatus(res) != PGRES_TUPLES_OK)
4149 : 0 : pgfdw_report_error(res, conn, fsstate->query);
4150 : :
4151 : : /* Reset per-connection state */
4152 : 228 : fsstate->conn_state->pendingAreq = NULL;
4153 : : }
4154 : : else
4155 : : {
4156 : : char sql[64];
4157 : :
4158 : : /* This is a regular synchronous fetch. */
4159 : 1410 : snprintf(sql, sizeof(sql), "FETCH %d FROM c%u",
4160 : : fsstate->fetch_size, fsstate->cursor_number);
4161 : :
4162 : 1410 : res = pgfdw_exec_query(conn, sql, fsstate->conn_state);
4163 : : /* On error, report the original query, not the FETCH. */
4164 [ + + ]: 1409 : if (PQresultStatus(res) != PGRES_TUPLES_OK)
4165 : 9 : pgfdw_report_error(res, conn, fsstate->query);
4166 : : }
4167 : :
4168 : : /* Convert the data into HeapTuples */
4169 : 1628 : numrows = PQntuples(res);
4170 : 1628 : fsstate->tuples = palloc0_array(HeapTuple, numrows);
4171 : 1628 : fsstate->num_tuples = numrows;
4172 : 1628 : fsstate->next_tuple = 0;
4173 : :
4174 [ + + ]: 76956 : for (i = 0; i < numrows; i++)
4175 : : {
4176 : : Assert(IsA(node->ss.ps.plan, ForeignScan));
4177 : :
4178 : 75328 : fsstate->tuples[i] =
4179 : 75332 : make_tuple_from_result_row(res, i,
4180 : : fsstate->rel,
4181 : : fsstate->attinmeta,
4182 : : fsstate->retrieved_attrs,
4183 : : node,
4184 : : fsstate->temp_cxt);
4185 : : }
4186 : :
4187 : : /* Update fetch_ct_2 */
4188 [ + + ]: 1624 : if (fsstate->fetch_ct_2 < 2)
4189 : 1055 : fsstate->fetch_ct_2++;
4190 : :
4191 : : /* Must be EOF if we didn't get as many tuples as we asked for. */
4192 : 1624 : fsstate->eof_reached = (numrows < fsstate->fetch_size);
4193 : :
4194 : 1624 : PQclear(res);
4195 : :
4196 : 1624 : MemoryContextSwitchTo(oldcontext);
4197 : 1624 : }
4198 : :
4199 : : /*
4200 : : * Force assorted GUC parameters to settings that ensure that we'll output
4201 : : * data values in a form that is unambiguous to the remote server.
4202 : : *
4203 : : * This is rather expensive and annoying to do once per row, but there's
4204 : : * little choice if we want to be sure values are transmitted accurately;
4205 : : * we can't leave the settings in place between rows for fear of affecting
4206 : : * user-visible computations.
4207 : : *
4208 : : * We use the equivalent of a function SET option to allow the settings to
4209 : : * persist only until the caller calls reset_transmission_modes(). If an
4210 : : * error is thrown in between, guc.c will take care of undoing the settings.
4211 : : *
4212 : : * The return value is the nestlevel that must be passed to
4213 : : * reset_transmission_modes() to undo things.
4214 : : */
4215 : : int
4216 : 5586 : set_transmission_modes(void)
4217 : : {
4218 : 5586 : int nestlevel = NewGUCNestLevel();
4219 : :
4220 : : /*
4221 : : * The values set here should match what pg_dump does. See also
4222 : : * configure_remote_session in connection.c.
4223 : : */
4224 [ + + ]: 5586 : if (DateStyle != USE_ISO_DATES)
4225 : 5583 : (void) set_config_option("datestyle", "ISO",
4226 : : PGC_USERSET, PGC_S_SESSION,
4227 : : GUC_ACTION_SAVE, true, 0, false);
4228 [ + + ]: 5586 : if (IntervalStyle != INTSTYLE_POSTGRES)
4229 : 5583 : (void) set_config_option("intervalstyle", "postgres",
4230 : : PGC_USERSET, PGC_S_SESSION,
4231 : : GUC_ACTION_SAVE, true, 0, false);
4232 [ + + ]: 5586 : if (extra_float_digits < 3)
4233 : 5584 : (void) set_config_option("extra_float_digits", "3",
4234 : : PGC_USERSET, PGC_S_SESSION,
4235 : : GUC_ACTION_SAVE, true, 0, false);
4236 : :
4237 : : /*
4238 : : * In addition force restrictive search_path, in case there are any
4239 : : * regproc or similar constants to be printed.
4240 : : */
4241 : 5586 : (void) set_config_option("search_path", "pg_catalog",
4242 : : PGC_USERSET, PGC_S_SESSION,
4243 : : GUC_ACTION_SAVE, true, 0, false);
4244 : :
4245 : 5586 : return nestlevel;
4246 : : }
4247 : :
4248 : : /*
4249 : : * Undo the effects of set_transmission_modes().
4250 : : */
4251 : : void
4252 : 5586 : reset_transmission_modes(int nestlevel)
4253 : : {
4254 : 5586 : AtEOXact_GUC(true, nestlevel);
4255 : 5586 : }
4256 : :
4257 : : /*
4258 : : * Utility routine to close a cursor.
4259 : : */
4260 : : static void
4261 : 573 : close_cursor(PGconn *conn, unsigned int cursor_number,
4262 : : PgFdwConnState *conn_state)
4263 : : {
4264 : : char sql[64];
4265 : : PGresult *res;
4266 : :
4267 : 573 : snprintf(sql, sizeof(sql), "CLOSE c%u", cursor_number);
4268 : 573 : res = pgfdw_exec_query(conn, sql, conn_state);
4269 [ + + ]: 573 : if (PQresultStatus(res) != PGRES_COMMAND_OK)
4270 : 1 : pgfdw_report_error(res, conn, sql);
4271 : 572 : PQclear(res);
4272 : 572 : }
4273 : :
4274 : : /*
4275 : : * create_foreign_modify
4276 : : * Construct an execution state of a foreign insert/update/delete
4277 : : * operation
4278 : : */
4279 : : static PgFdwModifyState *
4280 : 190 : create_foreign_modify(EState *estate,
4281 : : RangeTblEntry *rte,
4282 : : ResultRelInfo *resultRelInfo,
4283 : : CmdType operation,
4284 : : Plan *subplan,
4285 : : char *query,
4286 : : List *target_attrs,
4287 : : int values_end,
4288 : : bool has_returning,
4289 : : List *retrieved_attrs)
4290 : : {
4291 : : PgFdwModifyState *fmstate;
4292 : 190 : Relation rel = resultRelInfo->ri_RelationDesc;
4293 : 190 : TupleDesc tupdesc = RelationGetDescr(rel);
4294 : : Oid userid;
4295 : : ForeignTable *table;
4296 : : UserMapping *user;
4297 : : AttrNumber n_params;
4298 : : Oid typefnoid;
4299 : : bool isvarlena;
4300 : : ListCell *lc;
4301 : :
4302 : : /* Begin constructing PgFdwModifyState. */
4303 : 190 : fmstate = palloc0_object(PgFdwModifyState);
4304 : 190 : fmstate->rel = rel;
4305 : :
4306 : : /* Identify which user to do the remote access as. */
4307 : 190 : userid = ExecGetResultRelCheckAsUser(resultRelInfo, estate);
4308 : :
4309 : : /* Get info about foreign table. */
4310 : 190 : table = GetForeignTable(RelationGetRelid(rel));
4311 : 190 : user = GetUserMapping(userid, table->serverid);
4312 : :
4313 : : /* Open connection; report that we'll create a prepared statement. */
4314 : 190 : fmstate->conn = GetConnection(user, true, &fmstate->conn_state);
4315 : 190 : fmstate->p_name = NULL; /* prepared statement not made yet */
4316 : :
4317 : : /* Set up remote query information. */
4318 : 190 : fmstate->query = query;
4319 [ + + ]: 190 : if (operation == CMD_INSERT)
4320 : : {
4321 : 139 : fmstate->query = pstrdup(fmstate->query);
4322 : 139 : fmstate->orig_query = pstrdup(fmstate->query);
4323 : : }
4324 : 190 : fmstate->target_attrs = target_attrs;
4325 : 190 : fmstate->values_end = values_end;
4326 : 190 : fmstate->has_returning = has_returning;
4327 : 190 : fmstate->retrieved_attrs = retrieved_attrs;
4328 : :
4329 : : /* Create context for per-tuple temp workspace. */
4330 : 190 : fmstate->temp_cxt = AllocSetContextCreate(estate->es_query_cxt,
4331 : : "postgres_fdw temporary data",
4332 : : ALLOCSET_SMALL_SIZES);
4333 : :
4334 : : /* Prepare for input conversion of RETURNING results. */
4335 [ + + ]: 190 : if (fmstate->has_returning)
4336 : 64 : fmstate->attinmeta = TupleDescGetAttInMetadata(tupdesc);
4337 : :
4338 : : /* Prepare for output conversion of parameters used in prepared stmt. */
4339 : 190 : n_params = list_length(fmstate->target_attrs) + 1;
4340 : 190 : fmstate->p_flinfo = palloc0_array(FmgrInfo, n_params);
4341 : 190 : fmstate->p_nums = 0;
4342 : :
4343 [ + + + + ]: 190 : if (operation == CMD_UPDATE || operation == CMD_DELETE)
4344 : : {
4345 : : Assert(subplan != NULL);
4346 : :
4347 : : /* Find the ctid resjunk column in the subplan's result */
4348 : 51 : fmstate->ctidAttno = ExecFindJunkAttributeInTlist(subplan->targetlist,
4349 : : "ctid");
4350 [ - + ]: 51 : if (!AttributeNumberIsValid(fmstate->ctidAttno))
4351 [ # # ]: 0 : elog(ERROR, "could not find junk ctid column");
4352 : :
4353 : : /* First transmittable parameter will be ctid */
4354 : 51 : getTypeOutputInfo(TIDOID, &typefnoid, &isvarlena);
4355 : 51 : fmgr_info(typefnoid, &fmstate->p_flinfo[fmstate->p_nums]);
4356 : 51 : fmstate->p_nums++;
4357 : : }
4358 : :
4359 [ + + + + ]: 190 : if (operation == CMD_INSERT || operation == CMD_UPDATE)
4360 : : {
4361 : : /* Set up for remaining transmittable parameters */
4362 [ + + + + : 593 : foreach(lc, fmstate->target_attrs)
+ + ]
4363 : : {
4364 : 416 : int attnum = lfirst_int(lc);
4365 : 416 : Form_pg_attribute attr = TupleDescAttr(tupdesc, attnum - 1);
4366 : :
4367 : : Assert(!attr->attisdropped);
4368 : :
4369 : : /* Ignore generated columns; they are set to DEFAULT */
4370 [ + + ]: 416 : if (attr->attgenerated)
4371 : 8 : continue;
4372 : 408 : getTypeOutputInfo(attr->atttypid, &typefnoid, &isvarlena);
4373 : 408 : fmgr_info(typefnoid, &fmstate->p_flinfo[fmstate->p_nums]);
4374 : 408 : fmstate->p_nums++;
4375 : : }
4376 : : }
4377 : :
4378 : : Assert(fmstate->p_nums <= n_params);
4379 : :
4380 : : /* Set batch_size from foreign server/table options. */
4381 [ + + ]: 190 : if (operation == CMD_INSERT)
4382 : 139 : fmstate->batch_size = get_batch_size_option(rel);
4383 : :
4384 : 190 : fmstate->num_slots = 1;
4385 : :
4386 : : /* Initialize auxiliary state */
4387 : 190 : fmstate->aux_fmstate = NULL;
4388 : :
4389 : 190 : return fmstate;
4390 : : }
4391 : :
4392 : : /*
4393 : : * execute_foreign_modify
4394 : : * Perform foreign-table modification as required, and fetch RETURNING
4395 : : * result if any. (This is the shared guts of postgresExecForeignInsert,
4396 : : * postgresExecForeignBatchInsert, postgresExecForeignUpdate, and
4397 : : * postgresExecForeignDelete.)
4398 : : */
4399 : : static TupleTableSlot **
4400 : 2156 : execute_foreign_modify(EState *estate,
4401 : : ResultRelInfo *resultRelInfo,
4402 : : CmdType operation,
4403 : : TupleTableSlot **slots,
4404 : : TupleTableSlot **planSlots,
4405 : : int *numSlots)
4406 : : {
4407 : 2156 : PgFdwModifyState *fmstate = (PgFdwModifyState *) resultRelInfo->ri_FdwState;
4408 : 2156 : ItemPointer ctid = NULL;
4409 : : const char **p_values;
4410 : : PGresult *res;
4411 : : int n_rows;
4412 : : StringInfoData sql;
4413 : :
4414 : : /* The operation should be INSERT, UPDATE, or DELETE */
4415 : : Assert(operation == CMD_INSERT ||
4416 : : operation == CMD_UPDATE ||
4417 : : operation == CMD_DELETE);
4418 : :
4419 : : /* First, process a pending asynchronous request, if any. */
4420 [ + + ]: 2156 : if (fmstate->conn_state->pendingAreq)
4421 : 1 : process_pending_request(fmstate->conn_state->pendingAreq);
4422 : :
4423 : : /*
4424 : : * If the existing query was deparsed and prepared for a different number
4425 : : * of rows, rebuild it for the proper number.
4426 : : */
4427 [ + + + + ]: 2156 : if (operation == CMD_INSERT && fmstate->num_slots != *numSlots)
4428 : : {
4429 : : /* Destroy the prepared statement created previously */
4430 [ + + ]: 27 : if (fmstate->p_name)
4431 : 11 : deallocate_query(fmstate);
4432 : :
4433 : : /* Build INSERT string with numSlots records in its VALUES clause. */
4434 : 27 : initStringInfo(&sql);
4435 : 27 : rebuildInsertSql(&sql, fmstate->rel,
4436 : : fmstate->orig_query, fmstate->target_attrs,
4437 : : fmstate->values_end, fmstate->p_nums,
4438 : 27 : *numSlots - 1);
4439 : 27 : pfree(fmstate->query);
4440 : 27 : fmstate->query = sql.data;
4441 : 27 : fmstate->num_slots = *numSlots;
4442 : : }
4443 : :
4444 : : /* Set up the prepared statement on the remote server, if we didn't yet */
4445 [ + + ]: 2156 : if (!fmstate->p_name)
4446 : 195 : prepare_foreign_modify(fmstate);
4447 : :
4448 : : /*
4449 : : * For UPDATE/DELETE, get the ctid that was passed up as a resjunk column
4450 : : */
4451 [ + + + + ]: 2156 : if (operation == CMD_UPDATE || operation == CMD_DELETE)
4452 : : {
4453 : : Datum datum;
4454 : : bool isNull;
4455 : :
4456 : 120 : datum = ExecGetJunkAttribute(planSlots[0],
4457 : 120 : fmstate->ctidAttno,
4458 : : &isNull);
4459 : : /* shouldn't ever get a null result... */
4460 [ - + ]: 120 : if (isNull)
4461 [ # # ]: 0 : elog(ERROR, "ctid is NULL");
4462 : 120 : ctid = (ItemPointer) DatumGetPointer(datum);
4463 : : }
4464 : :
4465 : : /* Convert parameters needed by prepared statement to text form */
4466 : 2156 : p_values = convert_prep_stmt_params(fmstate, ctid, slots, *numSlots);
4467 : :
4468 : : /*
4469 : : * Execute the prepared statement.
4470 : : */
4471 [ - + ]: 2156 : if (!PQsendQueryPrepared(fmstate->conn,
4472 : 2156 : fmstate->p_name,
4473 : 2156 : fmstate->p_nums * (*numSlots),
4474 : : p_values,
4475 : : NULL,
4476 : : NULL,
4477 : : 0))
4478 : 0 : pgfdw_report_error(NULL, fmstate->conn, fmstate->query);
4479 : :
4480 : : /*
4481 : : * Get the result, and check for success.
4482 : : */
4483 : 2156 : res = pgfdw_get_result(fmstate->conn);
4484 [ + + ]: 4312 : if (PQresultStatus(res) !=
4485 [ + + ]: 2156 : (fmstate->has_returning ? PGRES_TUPLES_OK : PGRES_COMMAND_OK))
4486 : 5 : pgfdw_report_error(res, fmstate->conn, fmstate->query);
4487 : :
4488 : : /* Check number of rows affected, and fetch RETURNING tuple if any */
4489 [ + + ]: 2151 : if (fmstate->has_returning)
4490 : : {
4491 : : Assert(*numSlots == 1);
4492 : 110 : n_rows = PQntuples(res);
4493 [ + + ]: 110 : if (n_rows > 0)
4494 : 109 : store_returning_result(fmstate, slots[0], res);
4495 : : }
4496 : : else
4497 : 2041 : n_rows = atoi(PQcmdTuples(res));
4498 : :
4499 : : /* And clean up */
4500 : 2151 : PQclear(res);
4501 : :
4502 : 2151 : MemoryContextReset(fmstate->temp_cxt);
4503 : :
4504 : 2151 : *numSlots = n_rows;
4505 : :
4506 : : /*
4507 : : * Return NULL if nothing was inserted/updated/deleted on the remote end
4508 : : */
4509 [ + + ]: 2151 : return (n_rows > 0) ? slots : NULL;
4510 : : }
4511 : :
4512 : : /*
4513 : : * prepare_foreign_modify
4514 : : * Establish a prepared statement for execution of INSERT/UPDATE/DELETE
4515 : : */
4516 : : static void
4517 : 195 : prepare_foreign_modify(PgFdwModifyState *fmstate)
4518 : : {
4519 : : char prep_name[NAMEDATALEN];
4520 : : char *p_name;
4521 : : PGresult *res;
4522 : :
4523 : : /*
4524 : : * The caller would already have processed a pending asynchronous request
4525 : : * if any, so no need to do it here.
4526 : : */
4527 : :
4528 : : /* Construct name we'll use for the prepared statement. */
4529 : 195 : snprintf(prep_name, sizeof(prep_name), "pgsql_fdw_prep_%u",
4530 : : GetPrepStmtNumber(fmstate->conn));
4531 : 195 : p_name = pstrdup(prep_name);
4532 : :
4533 : : /*
4534 : : * We intentionally do not specify parameter types here, but leave the
4535 : : * remote server to derive them by default. This avoids possible problems
4536 : : * with the remote server using different type OIDs than we do. All of
4537 : : * the prepared statements we use in this module are simple enough that
4538 : : * the remote server will make the right choices.
4539 : : */
4540 [ - + ]: 195 : if (!PQsendPrepare(fmstate->conn,
4541 : : p_name,
4542 : 195 : fmstate->query,
4543 : : 0,
4544 : : NULL))
4545 : 0 : pgfdw_report_error(NULL, fmstate->conn, fmstate->query);
4546 : :
4547 : : /*
4548 : : * Get the result, and check for success.
4549 : : */
4550 : 195 : res = pgfdw_get_result(fmstate->conn);
4551 [ - + ]: 195 : if (PQresultStatus(res) != PGRES_COMMAND_OK)
4552 : 0 : pgfdw_report_error(res, fmstate->conn, fmstate->query);
4553 : 195 : PQclear(res);
4554 : :
4555 : : /* This action shows that the prepare has been done. */
4556 : 195 : fmstate->p_name = p_name;
4557 : 195 : }
4558 : :
4559 : : /*
4560 : : * convert_prep_stmt_params
4561 : : * Create array of text strings representing parameter values
4562 : : *
4563 : : * tupleid is ctid to send, or NULL if none
4564 : : * slot is slot to get remaining parameters from, or NULL if none
4565 : : *
4566 : : * Data is constructed in temp_cxt; caller should reset that after use.
4567 : : */
4568 : : static const char **
4569 : 2156 : convert_prep_stmt_params(PgFdwModifyState *fmstate,
4570 : : ItemPointer tupleid,
4571 : : TupleTableSlot **slots,
4572 : : int numSlots)
4573 : : {
4574 : : const char **p_values;
4575 : : int i;
4576 : : int j;
4577 : 2156 : int pindex = 0;
4578 : : MemoryContext oldcontext;
4579 : :
4580 : 2156 : oldcontext = MemoryContextSwitchTo(fmstate->temp_cxt);
4581 : :
4582 : 2156 : p_values = palloc_array(const char *, fmstate->p_nums * numSlots);
4583 : :
4584 : : /* ctid is provided only for UPDATE/DELETE, which don't allow batching */
4585 : : Assert(!(tupleid != NULL && numSlots > 1));
4586 : :
4587 : : /* 1st parameter should be ctid, if it's in use */
4588 [ + + ]: 2156 : if (tupleid != NULL)
4589 : : {
4590 : : Assert(numSlots == 1);
4591 : : /* don't need set_transmission_modes for TID output */
4592 : 120 : p_values[pindex] = OutputFunctionCall(&fmstate->p_flinfo[pindex],
4593 : : PointerGetDatum(tupleid));
4594 : 120 : pindex++;
4595 : : }
4596 : :
4597 : : /* get following parameters from slots */
4598 [ + - + + ]: 2156 : if (slots != NULL && fmstate->target_attrs != NIL)
4599 : : {
4600 : 2130 : TupleDesc tupdesc = RelationGetDescr(fmstate->rel);
4601 : : int nestlevel;
4602 : : ListCell *lc;
4603 : :
4604 : 2130 : nestlevel = set_transmission_modes();
4605 : :
4606 [ + + ]: 4383 : for (i = 0; i < numSlots; i++)
4607 : : {
4608 : 2253 : j = (tupleid != NULL) ? 1 : 0;
4609 [ + - + + : 9208 : foreach(lc, fmstate->target_attrs)
+ + ]
4610 : : {
4611 : 6955 : int attnum = lfirst_int(lc);
4612 : 6955 : CompactAttribute *attr = TupleDescCompactAttr(tupdesc, attnum - 1);
4613 : : Datum value;
4614 : : bool isnull;
4615 : :
4616 : : /* Ignore generated columns; they are set to DEFAULT */
4617 [ + + ]: 6955 : if (attr->attgenerated)
4618 : 14 : continue;
4619 : 6941 : value = slot_getattr(slots[i], attnum, &isnull);
4620 [ + + ]: 6941 : if (isnull)
4621 : 583 : p_values[pindex] = NULL;
4622 : : else
4623 : 6358 : p_values[pindex] = OutputFunctionCall(&fmstate->p_flinfo[j],
4624 : : value);
4625 : 6941 : pindex++;
4626 : 6941 : j++;
4627 : : }
4628 : : }
4629 : :
4630 : 2130 : reset_transmission_modes(nestlevel);
4631 : : }
4632 : :
4633 : : Assert(pindex == fmstate->p_nums * numSlots);
4634 : :
4635 : 2156 : MemoryContextSwitchTo(oldcontext);
4636 : :
4637 : 2156 : return p_values;
4638 : : }
4639 : :
4640 : : /*
4641 : : * store_returning_result
4642 : : * Store the result of a RETURNING clause
4643 : : */
4644 : : static void
4645 : 109 : store_returning_result(PgFdwModifyState *fmstate,
4646 : : TupleTableSlot *slot, PGresult *res)
4647 : : {
4648 : : HeapTuple newtup;
4649 : :
4650 : 109 : newtup = make_tuple_from_result_row(res, 0,
4651 : : fmstate->rel,
4652 : : fmstate->attinmeta,
4653 : : fmstate->retrieved_attrs,
4654 : : NULL,
4655 : : fmstate->temp_cxt);
4656 : :
4657 : : /*
4658 : : * The returning slot will not necessarily be suitable to store heaptuples
4659 : : * directly, so allow for conversion.
4660 : : */
4661 : 109 : ExecForceStoreHeapTuple(newtup, slot, true);
4662 : 109 : }
4663 : :
4664 : : /*
4665 : : * finish_foreign_modify
4666 : : * Release resources for a foreign insert/update/delete operation
4667 : : */
4668 : : static void
4669 : 168 : finish_foreign_modify(PgFdwModifyState *fmstate)
4670 : : {
4671 : : Assert(fmstate != NULL);
4672 : :
4673 : : /* If we created a prepared statement, destroy it */
4674 : 168 : deallocate_query(fmstate);
4675 : :
4676 : : /* Release remote connection */
4677 : 168 : ReleaseConnection(fmstate->conn);
4678 : 168 : fmstate->conn = NULL;
4679 : 168 : }
4680 : :
4681 : : /*
4682 : : * deallocate_query
4683 : : * Deallocate a prepared statement for a foreign insert/update/delete
4684 : : * operation
4685 : : */
4686 : : static void
4687 : 179 : deallocate_query(PgFdwModifyState *fmstate)
4688 : : {
4689 : : char sql[64];
4690 : : PGresult *res;
4691 : :
4692 : : /* do nothing if the query is not allocated */
4693 [ + + ]: 179 : if (!fmstate->p_name)
4694 : 4 : return;
4695 : :
4696 : 175 : snprintf(sql, sizeof(sql), "DEALLOCATE %s", fmstate->p_name);
4697 : 175 : res = pgfdw_exec_query(fmstate->conn, sql, fmstate->conn_state);
4698 [ - + ]: 175 : if (PQresultStatus(res) != PGRES_COMMAND_OK)
4699 : 0 : pgfdw_report_error(res, fmstate->conn, sql);
4700 : 175 : PQclear(res);
4701 : 175 : pfree(fmstate->p_name);
4702 : 175 : fmstate->p_name = NULL;
4703 : : }
4704 : :
4705 : : /*
4706 : : * build_remote_returning
4707 : : * Build a RETURNING targetlist of a remote query for performing an
4708 : : * UPDATE/DELETE .. RETURNING on a join directly
4709 : : */
4710 : : static List *
4711 : 5 : build_remote_returning(Index rtindex, Relation rel, List *returningList)
4712 : : {
4713 : 5 : bool have_wholerow = false;
4714 : 5 : List *tlist = NIL;
4715 : : List *vars;
4716 : : ListCell *lc;
4717 : :
4718 : : Assert(returningList);
4719 : :
4720 : 5 : vars = pull_var_clause((Node *) returningList, PVC_INCLUDE_PLACEHOLDERS);
4721 : :
4722 : : /*
4723 : : * If there's a whole-row reference to the target relation, then we'll
4724 : : * need all the columns of the relation.
4725 : : */
4726 [ + + + + : 8 : foreach(lc, vars)
+ + ]
4727 : : {
4728 : 5 : Var *var = (Var *) lfirst(lc);
4729 : :
4730 [ + - ]: 5 : if (IsA(var, Var) &&
4731 [ + + ]: 5 : var->varno == rtindex &&
4732 [ + + ]: 4 : var->varattno == InvalidAttrNumber)
4733 : : {
4734 : 2 : have_wholerow = true;
4735 : 2 : break;
4736 : : }
4737 : : }
4738 : :
4739 [ + + ]: 5 : if (have_wholerow)
4740 : : {
4741 : 2 : TupleDesc tupdesc = RelationGetDescr(rel);
4742 : : int i;
4743 : :
4744 [ + + ]: 20 : for (i = 1; i <= tupdesc->natts; i++)
4745 : : {
4746 : 18 : Form_pg_attribute attr = TupleDescAttr(tupdesc, i - 1);
4747 : : Var *var;
4748 : :
4749 : : /* Ignore dropped attributes. */
4750 [ + + ]: 18 : if (attr->attisdropped)
4751 : 2 : continue;
4752 : :
4753 : 16 : var = makeVar(rtindex,
4754 : : i,
4755 : : attr->atttypid,
4756 : : attr->atttypmod,
4757 : : attr->attcollation,
4758 : : 0);
4759 : :
4760 : 16 : tlist = lappend(tlist,
4761 : 16 : makeTargetEntry((Expr *) var,
4762 : 16 : list_length(tlist) + 1,
4763 : : NULL,
4764 : : false));
4765 : : }
4766 : : }
4767 : :
4768 : : /* Now add any remaining columns to tlist. */
4769 [ + + + + : 34 : foreach(lc, vars)
+ + ]
4770 : : {
4771 : 29 : Var *var = (Var *) lfirst(lc);
4772 : :
4773 : : /*
4774 : : * No need for whole-row references to the target relation. We don't
4775 : : * need system columns other than ctid and oid either, since those are
4776 : : * set locally.
4777 : : */
4778 [ + - ]: 29 : if (IsA(var, Var) &&
4779 [ + + ]: 29 : var->varno == rtindex &&
4780 [ + + ]: 20 : var->varattno <= InvalidAttrNumber &&
4781 [ + - ]: 2 : var->varattno != SelfItemPointerAttributeNumber)
4782 : 2 : continue; /* don't need it */
4783 : :
4784 [ + + ]: 27 : if (tlist_member((Expr *) var, tlist))
4785 : 16 : continue; /* already got it */
4786 : :
4787 : 11 : tlist = lappend(tlist,
4788 : 11 : makeTargetEntry((Expr *) var,
4789 : 11 : list_length(tlist) + 1,
4790 : : NULL,
4791 : : false));
4792 : : }
4793 : :
4794 : 5 : list_free(vars);
4795 : :
4796 : 5 : return tlist;
4797 : : }
4798 : :
4799 : : /*
4800 : : * rebuild_fdw_scan_tlist
4801 : : * Build new fdw_scan_tlist of given foreign-scan plan node from given
4802 : : * tlist
4803 : : *
4804 : : * There might be columns that the fdw_scan_tlist of the given foreign-scan
4805 : : * plan node contains that the given tlist doesn't. The fdw_scan_tlist would
4806 : : * have contained resjunk columns such as 'ctid' of the target relation and
4807 : : * 'wholerow' of non-target relations, but the tlist might not contain them,
4808 : : * for example. So, adjust the tlist so it contains all the columns specified
4809 : : * in the fdw_scan_tlist; else setrefs.c will get confused.
4810 : : */
4811 : : static void
4812 : 3 : rebuild_fdw_scan_tlist(ForeignScan *fscan, List *tlist)
4813 : : {
4814 : 3 : List *new_tlist = tlist;
4815 : 3 : List *old_tlist = fscan->fdw_scan_tlist;
4816 : : ListCell *lc;
4817 : :
4818 [ + - + + : 20 : foreach(lc, old_tlist)
+ + ]
4819 : : {
4820 : 17 : TargetEntry *tle = (TargetEntry *) lfirst(lc);
4821 : :
4822 [ + + ]: 17 : if (tlist_member(tle->expr, new_tlist))
4823 : 9 : continue; /* already got it */
4824 : :
4825 : 8 : new_tlist = lappend(new_tlist,
4826 : 8 : makeTargetEntry(tle->expr,
4827 : 8 : list_length(new_tlist) + 1,
4828 : : NULL,
4829 : : false));
4830 : : }
4831 : 3 : fscan->fdw_scan_tlist = new_tlist;
4832 : 3 : }
4833 : :
4834 : : /*
4835 : : * Execute a direct UPDATE/DELETE statement.
4836 : : */
4837 : : static void
4838 : 74 : execute_dml_stmt(ForeignScanState *node)
4839 : : {
4840 : 74 : PgFdwDirectModifyState *dmstate = (PgFdwDirectModifyState *) node->fdw_state;
4841 : 74 : ExprContext *econtext = node->ss.ps.ps_ExprContext;
4842 : 74 : int numParams = dmstate->numParams;
4843 : 74 : const char **values = dmstate->param_values;
4844 : :
4845 : : /* First, process a pending asynchronous request, if any. */
4846 [ + + ]: 74 : if (dmstate->conn_state->pendingAreq)
4847 : 1 : process_pending_request(dmstate->conn_state->pendingAreq);
4848 : :
4849 : : /*
4850 : : * Construct array of query parameter values in text format.
4851 : : */
4852 [ + + ]: 74 : if (numParams > 0)
4853 : 1 : process_query_params(econtext,
4854 : : dmstate->param_flinfo,
4855 : : dmstate->param_exprs,
4856 : : values);
4857 : :
4858 : : /*
4859 : : * Notice that we pass NULL for paramTypes, thus forcing the remote server
4860 : : * to infer types for all parameters. Since we explicitly cast every
4861 : : * parameter (see deparse.c), the "inference" is trivial and will produce
4862 : : * the desired result. This allows us to avoid assuming that the remote
4863 : : * server has the same OIDs we do for the parameters' types.
4864 : : */
4865 [ - + ]: 74 : if (!PQsendQueryParams(dmstate->conn, dmstate->query, numParams,
4866 : : NULL, values, NULL, NULL, 0))
4867 : 0 : pgfdw_report_error(NULL, dmstate->conn, dmstate->query);
4868 : :
4869 : : /*
4870 : : * Get the result, and check for success.
4871 : : */
4872 : 74 : dmstate->result = pgfdw_get_result(dmstate->conn);
4873 [ + + ]: 148 : if (PQresultStatus(dmstate->result) !=
4874 [ + + ]: 74 : (dmstate->has_returning ? PGRES_TUPLES_OK : PGRES_COMMAND_OK))
4875 : 4 : pgfdw_report_error(dmstate->result, dmstate->conn,
4876 : 4 : dmstate->query);
4877 : :
4878 : : /*
4879 : : * The result potentially needs to survive across multiple executor row
4880 : : * cycles, so move it to the context where the dmstate is.
4881 : : */
4882 : 70 : dmstate->result = libpqsrv_PGresultSetParent(dmstate->result,
4883 : : GetMemoryChunkContext(dmstate));
4884 : :
4885 : : /* Get the number of rows affected. */
4886 [ + + ]: 70 : if (dmstate->has_returning)
4887 : 16 : dmstate->num_tuples = PQntuples(dmstate->result);
4888 : : else
4889 : 54 : dmstate->num_tuples = atoi(PQcmdTuples(dmstate->result));
4890 : 70 : }
4891 : :
4892 : : /*
4893 : : * Get the result of a RETURNING clause.
4894 : : */
4895 : : static TupleTableSlot *
4896 : 368 : get_returning_data(ForeignScanState *node)
4897 : : {
4898 : 368 : PgFdwDirectModifyState *dmstate = (PgFdwDirectModifyState *) node->fdw_state;
4899 : 368 : EState *estate = node->ss.ps.state;
4900 : 368 : ResultRelInfo *resultRelInfo = node->resultRelInfo;
4901 : 368 : TupleTableSlot *slot = node->ss.ss_ScanTupleSlot;
4902 : : TupleTableSlot *resultSlot;
4903 : :
4904 : : Assert(resultRelInfo->ri_projectReturning);
4905 : :
4906 : : /* If we didn't get any tuples, must be end of data. */
4907 [ + + ]: 368 : if (dmstate->next_tuple >= dmstate->num_tuples)
4908 : 19 : return ExecClearTuple(slot);
4909 : :
4910 : : /* Increment the command es_processed count if necessary. */
4911 [ + + ]: 349 : if (dmstate->set_processed)
4912 : 348 : estate->es_processed += 1;
4913 : :
4914 : : /*
4915 : : * Store a RETURNING tuple. If has_returning is false, just emit a dummy
4916 : : * tuple. (has_returning is false when the local query is of the form
4917 : : * "UPDATE/DELETE .. RETURNING 1" for example.)
4918 : : */
4919 [ + + ]: 349 : if (!dmstate->has_returning)
4920 : : {
4921 : 12 : ExecStoreAllNullTuple(slot);
4922 : 12 : resultSlot = slot;
4923 : : }
4924 : : else
4925 : : {
4926 : : HeapTuple newtup;
4927 : :
4928 : 337 : newtup = make_tuple_from_result_row(dmstate->result,
4929 : : dmstate->next_tuple,
4930 : : dmstate->rel,
4931 : : dmstate->attinmeta,
4932 : : dmstate->retrieved_attrs,
4933 : : node,
4934 : : dmstate->temp_cxt);
4935 : 337 : ExecStoreHeapTuple(newtup, slot, false);
4936 : : /* Get the updated/deleted tuple. */
4937 [ + + ]: 337 : if (dmstate->rel)
4938 : 320 : resultSlot = slot;
4939 : : else
4940 : 17 : resultSlot = apply_returning_filter(dmstate, resultRelInfo, slot, estate);
4941 : : }
4942 : 349 : dmstate->next_tuple++;
4943 : :
4944 : : /* Make slot available for evaluation of the local query RETURNING list. */
4945 : 349 : resultRelInfo->ri_projectReturning->pi_exprContext->ecxt_scantuple =
4946 : : resultSlot;
4947 : :
4948 : 349 : return slot;
4949 : : }
4950 : :
4951 : : /*
4952 : : * Initialize a filter to extract an updated/deleted tuple from a scan tuple.
4953 : : */
4954 : : static void
4955 : 2 : init_returning_filter(PgFdwDirectModifyState *dmstate,
4956 : : List *fdw_scan_tlist,
4957 : : Index rtindex)
4958 : : {
4959 : 2 : TupleDesc resultTupType = RelationGetDescr(dmstate->resultRel);
4960 : : ListCell *lc;
4961 : : int i;
4962 : :
4963 : : /*
4964 : : * Calculate the mapping between the fdw_scan_tlist's entries and the
4965 : : * result tuple's attributes.
4966 : : *
4967 : : * The "map" is an array of indexes of the result tuple's attributes in
4968 : : * fdw_scan_tlist, i.e., one entry for every attribute of the result
4969 : : * tuple. We store zero for any attributes that don't have the
4970 : : * corresponding entries in that list, marking that a NULL is needed in
4971 : : * the result tuple.
4972 : : *
4973 : : * Also get the indexes of the entries for ctid and oid if any.
4974 : : */
4975 : 2 : dmstate->attnoMap = palloc0_array(AttrNumber, resultTupType->natts);
4976 : :
4977 : 2 : dmstate->ctidAttno = dmstate->oidAttno = 0;
4978 : :
4979 : 2 : i = 1;
4980 : 2 : dmstate->hasSystemCols = false;
4981 [ + - + + : 22 : foreach(lc, fdw_scan_tlist)
+ + ]
4982 : : {
4983 : 20 : TargetEntry *tle = (TargetEntry *) lfirst(lc);
4984 : 20 : Var *var = (Var *) tle->expr;
4985 : :
4986 : : Assert(IsA(var, Var));
4987 : :
4988 : : /*
4989 : : * If the Var is a column of the target relation to be retrieved from
4990 : : * the foreign server, get the index of the entry.
4991 : : */
4992 [ + + + + ]: 34 : if (var->varno == rtindex &&
4993 : 14 : list_member_int(dmstate->retrieved_attrs, i))
4994 : : {
4995 : 10 : int attrno = var->varattno;
4996 : :
4997 [ - + ]: 10 : if (attrno < 0)
4998 : : {
4999 : : /*
5000 : : * We don't retrieve system columns other than ctid and oid.
5001 : : */
5002 [ # # ]: 0 : if (attrno == SelfItemPointerAttributeNumber)
5003 : 0 : dmstate->ctidAttno = i;
5004 : : else
5005 : : Assert(false);
5006 : 0 : dmstate->hasSystemCols = true;
5007 : : }
5008 : : else
5009 : : {
5010 : : /*
5011 : : * We don't retrieve whole-row references to the target
5012 : : * relation either.
5013 : : */
5014 : : Assert(attrno > 0);
5015 : :
5016 : 10 : dmstate->attnoMap[attrno - 1] = i;
5017 : : }
5018 : : }
5019 : 20 : i++;
5020 : : }
5021 : 2 : }
5022 : :
5023 : : /*
5024 : : * Extract and return an updated/deleted tuple from a scan tuple.
5025 : : */
5026 : : static TupleTableSlot *
5027 : 17 : apply_returning_filter(PgFdwDirectModifyState *dmstate,
5028 : : ResultRelInfo *resultRelInfo,
5029 : : TupleTableSlot *slot,
5030 : : EState *estate)
5031 : : {
5032 : 17 : TupleDesc resultTupType = RelationGetDescr(dmstate->resultRel);
5033 : : TupleTableSlot *resultSlot;
5034 : : Datum *values;
5035 : : bool *isnull;
5036 : : Datum *old_values;
5037 : : bool *old_isnull;
5038 : : int i;
5039 : :
5040 : : /*
5041 : : * Use the return tuple slot as a place to store the result tuple.
5042 : : */
5043 : 17 : resultSlot = ExecGetReturningSlot(estate, resultRelInfo);
5044 : :
5045 : : /*
5046 : : * Extract all the values of the scan tuple.
5047 : : */
5048 : 17 : slot_getallattrs(slot);
5049 : 17 : old_values = slot->tts_values;
5050 : 17 : old_isnull = slot->tts_isnull;
5051 : :
5052 : : /*
5053 : : * Prepare to build the result tuple.
5054 : : */
5055 : 17 : ExecClearTuple(resultSlot);
5056 : 17 : values = resultSlot->tts_values;
5057 : 17 : isnull = resultSlot->tts_isnull;
5058 : :
5059 : : /*
5060 : : * Transpose data into proper fields of the result tuple.
5061 : : */
5062 [ + + ]: 163 : for (i = 0; i < resultTupType->natts; i++)
5063 : : {
5064 : 146 : int j = dmstate->attnoMap[i];
5065 : :
5066 [ + + ]: 146 : if (j == 0)
5067 : : {
5068 : 16 : values[i] = (Datum) 0;
5069 : 16 : isnull[i] = true;
5070 : : }
5071 : : else
5072 : : {
5073 : 130 : values[i] = old_values[j - 1];
5074 : 130 : isnull[i] = old_isnull[j - 1];
5075 : : }
5076 : : }
5077 : :
5078 : : /*
5079 : : * Build the virtual tuple.
5080 : : */
5081 : 17 : ExecStoreVirtualTuple(resultSlot);
5082 : :
5083 : : /*
5084 : : * If we have any system columns to return, materialize a heap tuple in
5085 : : * the slot from column values set above and install system columns in
5086 : : * that tuple.
5087 : : */
5088 [ - + ]: 17 : if (dmstate->hasSystemCols)
5089 : : {
5090 : 0 : HeapTuple resultTup = ExecFetchSlotHeapTuple(resultSlot, true, NULL);
5091 : :
5092 : : /* ctid */
5093 [ # # ]: 0 : if (dmstate->ctidAttno)
5094 : : {
5095 : 0 : ItemPointer ctid = NULL;
5096 : :
5097 : 0 : ctid = (ItemPointer) DatumGetPointer(old_values[dmstate->ctidAttno - 1]);
5098 : 0 : resultTup->t_self = *ctid;
5099 : : }
5100 : :
5101 : : /*
5102 : : * And remaining columns
5103 : : *
5104 : : * Note: since we currently don't allow the target relation to appear
5105 : : * on the nullable side of an outer join, any system columns wouldn't
5106 : : * go to NULL.
5107 : : *
5108 : : * Note: no need to care about tableoid here because it will be
5109 : : * initialized in ExecProcessReturning().
5110 : : */
5111 : 0 : HeapTupleHeaderSetXmin(resultTup->t_data, InvalidTransactionId);
5112 : 0 : HeapTupleHeaderSetXmax(resultTup->t_data, InvalidTransactionId);
5113 : 0 : HeapTupleHeaderSetCmin(resultTup->t_data, InvalidTransactionId);
5114 : : }
5115 : :
5116 : : /*
5117 : : * And return the result tuple.
5118 : : */
5119 : 17 : return resultSlot;
5120 : : }
5121 : :
5122 : : /*
5123 : : * Prepare for processing of parameters used in remote query.
5124 : : */
5125 : : static void
5126 : 40 : prepare_query_params(PlanState *node,
5127 : : List *fdw_exprs,
5128 : : int numParams,
5129 : : FmgrInfo **param_flinfo,
5130 : : List **param_exprs,
5131 : : const char ***param_values)
5132 : : {
5133 : : int i;
5134 : : ListCell *lc;
5135 : :
5136 : : Assert(numParams > 0);
5137 : :
5138 : : /* Prepare for output conversion of parameters used in remote query. */
5139 : 40 : *param_flinfo = palloc0_array(FmgrInfo, numParams);
5140 : :
5141 : 40 : i = 0;
5142 [ + - + + : 81 : foreach(lc, fdw_exprs)
+ + ]
5143 : : {
5144 : 41 : Node *param_expr = (Node *) lfirst(lc);
5145 : : Oid typefnoid;
5146 : : bool isvarlena;
5147 : :
5148 : 41 : getTypeOutputInfo(exprType(param_expr), &typefnoid, &isvarlena);
5149 : 41 : fmgr_info(typefnoid, &(*param_flinfo)[i]);
5150 : 41 : i++;
5151 : : }
5152 : :
5153 : : /*
5154 : : * Prepare remote-parameter expressions for evaluation. (Note: in
5155 : : * practice, we expect that all these expressions will be just Params, so
5156 : : * we could possibly do something more efficient than using the full
5157 : : * expression-eval machinery for this. But probably there would be little
5158 : : * benefit, and it'd require postgres_fdw to know more than is desirable
5159 : : * about Param evaluation.)
5160 : : */
5161 : 40 : *param_exprs = ExecInitExprList(fdw_exprs, node);
5162 : :
5163 : : /* Allocate buffer for text form of query parameters. */
5164 : 40 : *param_values = palloc0_array(const char *, numParams);
5165 : 40 : }
5166 : :
5167 : : /*
5168 : : * Construct array of query parameter values in text format.
5169 : : */
5170 : : static void
5171 : 403 : process_query_params(ExprContext *econtext,
5172 : : FmgrInfo *param_flinfo,
5173 : : List *param_exprs,
5174 : : const char **param_values)
5175 : : {
5176 : : int nestlevel;
5177 : : int i;
5178 : : ListCell *lc;
5179 : :
5180 : 403 : nestlevel = set_transmission_modes();
5181 : :
5182 : 403 : i = 0;
5183 [ + - + + : 1006 : foreach(lc, param_exprs)
+ + ]
5184 : : {
5185 : 603 : ExprState *expr_state = (ExprState *) lfirst(lc);
5186 : : Datum expr_value;
5187 : : bool isNull;
5188 : :
5189 : : /* Evaluate the parameter expression */
5190 : 603 : expr_value = ExecEvalExpr(expr_state, econtext, &isNull);
5191 : :
5192 : : /*
5193 : : * Get string representation of each parameter value by invoking
5194 : : * type-specific output function, unless the value is null.
5195 : : */
5196 [ - + ]: 603 : if (isNull)
5197 : 0 : param_values[i] = NULL;
5198 : : else
5199 : 603 : param_values[i] = OutputFunctionCall(¶m_flinfo[i], expr_value);
5200 : :
5201 : 603 : i++;
5202 : : }
5203 : :
5204 : 403 : reset_transmission_modes(nestlevel);
5205 : 403 : }
5206 : :
5207 : : /*
5208 : : * postgresAnalyzeForeignTable
5209 : : * Test whether analyzing this foreign table is supported
5210 : : */
5211 : : static bool
5212 : 59 : postgresAnalyzeForeignTable(Relation relation,
5213 : : AcquireSampleRowsFunc *func,
5214 : : BlockNumber *totalpages)
5215 : : {
5216 : : ForeignTable *table;
5217 : : UserMapping *user;
5218 : : PGconn *conn;
5219 : : StringInfoData sql;
5220 : : PGresult *res;
5221 : :
5222 : : /* Return the row-analysis function pointer */
5223 : 59 : *func = postgresAcquireSampleRowsFunc;
5224 : :
5225 : : /*
5226 : : * Now we have to get the number of pages. It's annoying that the ANALYZE
5227 : : * API requires us to return that now, because it forces some duplication
5228 : : * of effort between this routine and postgresAcquireSampleRowsFunc. But
5229 : : * it's probably not worth redefining that API at this point.
5230 : : */
5231 : :
5232 : : /*
5233 : : * Get the connection to use. We do the remote access as the table's
5234 : : * owner, even if the ANALYZE was started by some other user.
5235 : : */
5236 : 59 : table = GetForeignTable(RelationGetRelid(relation));
5237 : 59 : user = GetUserMapping(relation->rd_rel->relowner, table->serverid);
5238 : 59 : conn = GetConnection(user, false, NULL);
5239 : :
5240 : : /*
5241 : : * Construct command to get page count for relation.
5242 : : */
5243 : 59 : initStringInfo(&sql);
5244 : 59 : deparseAnalyzeSizeSql(&sql, relation);
5245 : :
5246 : 59 : res = pgfdw_exec_query(conn, sql.data, NULL);
5247 [ - + ]: 59 : if (PQresultStatus(res) != PGRES_TUPLES_OK)
5248 : 0 : pgfdw_report_error(res, conn, sql.data);
5249 : :
5250 [ + - - + ]: 59 : if (PQntuples(res) != 1 || PQnfields(res) != 1)
5251 [ # # ]: 0 : elog(ERROR, "unexpected result from deparseAnalyzeSizeSql query");
5252 : 59 : *totalpages = strtoul(PQgetvalue(res, 0, 0), NULL, 10);
5253 : 59 : PQclear(res);
5254 : :
5255 : 59 : ReleaseConnection(conn);
5256 : :
5257 : 59 : return true;
5258 : : }
5259 : :
5260 : : /*
5261 : : * postgresGetAnalyzeInfoForForeignTable
5262 : : * Count tuples in foreign table (just get pg_class.reltuples).
5263 : : *
5264 : : * can_tablesample determines if the remote relation supports acquiring the
5265 : : * sample using TABLESAMPLE.
5266 : : */
5267 : : static double
5268 : 52 : postgresGetAnalyzeInfoForForeignTable(Relation relation, bool *can_tablesample)
5269 : : {
5270 : : ForeignTable *table;
5271 : : UserMapping *user;
5272 : : PGconn *conn;
5273 : : StringInfoData sql;
5274 : : PGresult *res;
5275 : : double reltuples;
5276 : : char relkind;
5277 : :
5278 : : /* assume the remote relation does not support TABLESAMPLE */
5279 : 52 : *can_tablesample = false;
5280 : :
5281 : : /*
5282 : : * Get the connection to use. We do the remote access as the table's
5283 : : * owner, even if the ANALYZE was started by some other user.
5284 : : */
5285 : 52 : table = GetForeignTable(RelationGetRelid(relation));
5286 : 52 : user = GetUserMapping(relation->rd_rel->relowner, table->serverid);
5287 : 52 : conn = GetConnection(user, false, NULL);
5288 : :
5289 : : /*
5290 : : * Construct command to get page count for relation.
5291 : : */
5292 : 52 : initStringInfo(&sql);
5293 : 52 : deparseAnalyzeInfoSql(&sql, relation);
5294 : :
5295 : 52 : res = pgfdw_exec_query(conn, sql.data, NULL);
5296 [ - + ]: 52 : if (PQresultStatus(res) != PGRES_TUPLES_OK)
5297 : 0 : pgfdw_report_error(res, conn, sql.data);
5298 : :
5299 [ + - - + ]: 52 : if (PQntuples(res) != 1 || PQnfields(res) != RELSTATS_NUM_FIELDS)
5300 [ # # ]: 0 : elog(ERROR, "unexpected result from deparseAnalyzeInfoSql query");
5301 : : /* We don't use relpages/relhassubclass here */
5302 : 52 : reltuples = strtod(PQgetvalue(res, 0, RELSTATS_RELTUPLES), NULL);
5303 : 52 : relkind = *(PQgetvalue(res, 0, RELSTATS_RELKIND));
5304 : 52 : PQclear(res);
5305 : :
5306 : 52 : ReleaseConnection(conn);
5307 : :
5308 : : /* TABLESAMPLE is supported only for regular tables and matviews */
5309 [ # # ]: 0 : *can_tablesample = (relkind == RELKIND_RELATION ||
5310 [ - + - - ]: 52 : relkind == RELKIND_MATVIEW ||
5311 : 52 : relkind == RELKIND_PARTITIONED_TABLE);
5312 : :
5313 : 52 : return reltuples;
5314 : : }
5315 : :
5316 : : /*
5317 : : * Acquire a random sample of rows from foreign table managed by postgres_fdw.
5318 : : *
5319 : : * Selected rows are returned in the caller-allocated array rows[],
5320 : : * which must have at least targrows entries.
5321 : : * The actual number of rows selected is returned as the function result.
5322 : : * We also count the total number of rows in the table and return it into
5323 : : * *totalrows. Note that *totaldeadrows is always set to 0.
5324 : : *
5325 : : * Note that the returned list of rows is not always in order by physical
5326 : : * position in the table. Therefore, correlation estimates derived later
5327 : : * may be meaningless, but it's OK because we don't use the estimates
5328 : : * currently (the planner only pays attention to correlation for indexscans).
5329 : : */
5330 : : static int
5331 : 59 : postgresAcquireSampleRowsFunc(Relation relation, int elevel,
5332 : : HeapTuple *rows, int targrows,
5333 : : double *totalrows,
5334 : : double *totaldeadrows)
5335 : : {
5336 : : PgFdwAnalyzeState astate;
5337 : : ForeignTable *table;
5338 : : ForeignServer *server;
5339 : : UserMapping *user;
5340 : : PGconn *conn;
5341 : : int server_version_num;
5342 : 59 : PgFdwSamplingMethod method = ANALYZE_SAMPLE_AUTO; /* auto is default */
5343 : 59 : double sample_frac = -1.0;
5344 : 59 : double reltuples = -1.0;
5345 : : unsigned int cursor_number;
5346 : : StringInfoData sql;
5347 : : PGresult *res;
5348 : : char fetch_sql[64];
5349 : : int fetch_size;
5350 : : ListCell *lc;
5351 : :
5352 : : /* Initialize workspace state */
5353 : 59 : astate.rel = relation;
5354 : 59 : astate.attinmeta = TupleDescGetAttInMetadata(RelationGetDescr(relation));
5355 : :
5356 : 59 : astate.rows = rows;
5357 : 59 : astate.targrows = targrows;
5358 : 59 : astate.numrows = 0;
5359 : 59 : astate.samplerows = 0;
5360 : 59 : astate.rowstoskip = -1; /* -1 means not set yet */
5361 : 59 : reservoir_init_selection_state(&astate.rstate, targrows);
5362 : :
5363 : : /* Remember ANALYZE context, and create a per-tuple temp context */
5364 : 59 : astate.anl_cxt = CurrentMemoryContext;
5365 : 59 : astate.temp_cxt = AllocSetContextCreate(CurrentMemoryContext,
5366 : : "postgres_fdw temporary data",
5367 : : ALLOCSET_SMALL_SIZES);
5368 : :
5369 : : /*
5370 : : * Get the connection to use. We do the remote access as the table's
5371 : : * owner, even if the ANALYZE was started by some other user.
5372 : : */
5373 : 59 : table = GetForeignTable(RelationGetRelid(relation));
5374 : 59 : server = GetForeignServer(table->serverid);
5375 : 59 : user = GetUserMapping(relation->rd_rel->relowner, table->serverid);
5376 : 59 : conn = GetConnection(user, false, NULL);
5377 : :
5378 : : /* We'll need server version, so fetch it now. */
5379 : 59 : server_version_num = PQserverVersion(conn);
5380 : :
5381 : : /*
5382 : : * What sampling method should we use?
5383 : : */
5384 [ + - + + : 285 : foreach(lc, server->options)
+ + ]
5385 : : {
5386 : 237 : DefElem *def = (DefElem *) lfirst(lc);
5387 : :
5388 [ + + ]: 237 : if (strcmp(def->defname, "analyze_sampling") == 0)
5389 : : {
5390 : 11 : char *value = defGetString(def);
5391 : :
5392 [ + + ]: 11 : if (strcmp(value, "off") == 0)
5393 : 7 : method = ANALYZE_SAMPLE_OFF;
5394 [ + + ]: 4 : else if (strcmp(value, "auto") == 0)
5395 : 1 : method = ANALYZE_SAMPLE_AUTO;
5396 [ + + ]: 3 : else if (strcmp(value, "random") == 0)
5397 : 1 : method = ANALYZE_SAMPLE_RANDOM;
5398 [ + + ]: 2 : else if (strcmp(value, "system") == 0)
5399 : 1 : method = ANALYZE_SAMPLE_SYSTEM;
5400 [ + - ]: 1 : else if (strcmp(value, "bernoulli") == 0)
5401 : 1 : method = ANALYZE_SAMPLE_BERNOULLI;
5402 : :
5403 : 11 : break;
5404 : : }
5405 : : }
5406 : :
5407 [ + - + + : 139 : foreach(lc, table->options)
+ + ]
5408 : : {
5409 : 80 : DefElem *def = (DefElem *) lfirst(lc);
5410 : :
5411 [ - + ]: 80 : if (strcmp(def->defname, "analyze_sampling") == 0)
5412 : : {
5413 : 0 : char *value = defGetString(def);
5414 : :
5415 [ # # ]: 0 : if (strcmp(value, "off") == 0)
5416 : 0 : method = ANALYZE_SAMPLE_OFF;
5417 [ # # ]: 0 : else if (strcmp(value, "auto") == 0)
5418 : 0 : method = ANALYZE_SAMPLE_AUTO;
5419 [ # # ]: 0 : else if (strcmp(value, "random") == 0)
5420 : 0 : method = ANALYZE_SAMPLE_RANDOM;
5421 [ # # ]: 0 : else if (strcmp(value, "system") == 0)
5422 : 0 : method = ANALYZE_SAMPLE_SYSTEM;
5423 [ # # ]: 0 : else if (strcmp(value, "bernoulli") == 0)
5424 : 0 : method = ANALYZE_SAMPLE_BERNOULLI;
5425 : :
5426 : 0 : break;
5427 : : }
5428 : : }
5429 : :
5430 : : /*
5431 : : * Error-out if explicitly required one of the TABLESAMPLE methods, but
5432 : : * the server does not support it.
5433 : : */
5434 [ - + - - ]: 59 : if ((server_version_num < 90500) &&
5435 [ # # ]: 0 : (method == ANALYZE_SAMPLE_SYSTEM ||
5436 : : method == ANALYZE_SAMPLE_BERNOULLI))
5437 [ # # ]: 0 : ereport(ERROR,
5438 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5439 : : errmsg("remote server does not support TABLESAMPLE feature")));
5440 : :
5441 : : /*
5442 : : * If we've decided to do remote sampling, calculate the sampling rate. We
5443 : : * need to get the number of tuples from the remote server, but skip that
5444 : : * network round-trip if not needed.
5445 : : */
5446 [ + + ]: 59 : if (method != ANALYZE_SAMPLE_OFF)
5447 : : {
5448 : : bool can_tablesample;
5449 : :
5450 : 52 : reltuples = postgresGetAnalyzeInfoForForeignTable(relation,
5451 : : &can_tablesample);
5452 : :
5453 : : /*
5454 : : * Make sure we're not choosing TABLESAMPLE when the remote relation
5455 : : * does not support that. But only do this for "auto" - if the user
5456 : : * explicitly requested BERNOULLI/SYSTEM, it's better to fail.
5457 : : */
5458 [ - + - - ]: 52 : if (!can_tablesample && (method == ANALYZE_SAMPLE_AUTO))
5459 : 0 : method = ANALYZE_SAMPLE_RANDOM;
5460 : :
5461 : : /*
5462 : : * Remote's reltuples could be 0 or -1 if the table has never been
5463 : : * vacuumed/analyzed. In that case, disable sampling after all.
5464 : : */
5465 [ + + + - ]: 52 : if ((reltuples <= 0) || (targrows >= reltuples))
5466 : 52 : method = ANALYZE_SAMPLE_OFF;
5467 : : else
5468 : : {
5469 : : /*
5470 : : * All supported sampling methods require sampling rate, not
5471 : : * target rows directly, so we calculate that using the remote
5472 : : * reltuples value. That's imperfect, because it might be off a
5473 : : * good deal, but that's not something we can (or should) address
5474 : : * here.
5475 : : *
5476 : : * If reltuples is too low (i.e. when table grew), we'll end up
5477 : : * sampling more rows - but then we'll apply the local sampling,
5478 : : * so we get the expected sample size. This is the same outcome as
5479 : : * without remote sampling.
5480 : : *
5481 : : * If reltuples is too high (e.g. after bulk DELETE), we will end
5482 : : * up sampling too few rows.
5483 : : *
5484 : : * We can't really do much better here - we could try sampling a
5485 : : * bit more rows, but we don't know how off the reltuples value is
5486 : : * so how much is "a bit more"?
5487 : : *
5488 : : * Furthermore, the targrows value for partitions is determined
5489 : : * based on table size (relpages), which can be off in different
5490 : : * ways too. Adjusting the sampling rate here might make the issue
5491 : : * worse.
5492 : : */
5493 : 0 : sample_frac = targrows / reltuples;
5494 : :
5495 : : /*
5496 : : * We should never get sampling rate outside the valid range
5497 : : * (between 0.0 and 1.0), because those cases should be covered by
5498 : : * the previous branch that sets ANALYZE_SAMPLE_OFF.
5499 : : */
5500 : : Assert(sample_frac >= 0.0 && sample_frac <= 1.0);
5501 : : }
5502 : : }
5503 : :
5504 : : /*
5505 : : * For "auto" method, pick the one we believe is best. For servers with
5506 : : * TABLESAMPLE support we pick BERNOULLI, for old servers we fall-back to
5507 : : * random() to at least reduce network transfer.
5508 : : */
5509 [ - + ]: 59 : if (method == ANALYZE_SAMPLE_AUTO)
5510 : : {
5511 [ # # ]: 0 : if (server_version_num < 90500)
5512 : 0 : method = ANALYZE_SAMPLE_RANDOM;
5513 : : else
5514 : 0 : method = ANALYZE_SAMPLE_BERNOULLI;
5515 : : }
5516 : :
5517 : : /*
5518 : : * Construct cursor that retrieves whole rows from remote.
5519 : : */
5520 : 59 : cursor_number = GetCursorNumber(conn);
5521 : 59 : initStringInfo(&sql);
5522 : 59 : appendStringInfo(&sql, "DECLARE c%u CURSOR FOR ", cursor_number);
5523 : :
5524 : 59 : deparseAnalyzeSql(&sql, relation, method, sample_frac, &astate.retrieved_attrs);
5525 : :
5526 : 59 : res = pgfdw_exec_query(conn, sql.data, NULL);
5527 [ - + ]: 59 : if (PQresultStatus(res) != PGRES_COMMAND_OK)
5528 : 0 : pgfdw_report_error(res, conn, sql.data);
5529 : 59 : PQclear(res);
5530 : :
5531 : : /*
5532 : : * Determine the fetch size. The default is arbitrary, but shouldn't be
5533 : : * enormous.
5534 : : */
5535 : 59 : fetch_size = 100;
5536 [ + - + + : 296 : foreach(lc, server->options)
+ + ]
5537 : : {
5538 : 237 : DefElem *def = (DefElem *) lfirst(lc);
5539 : :
5540 [ - + ]: 237 : if (strcmp(def->defname, "fetch_size") == 0)
5541 : : {
5542 : 0 : (void) parse_int(defGetString(def), &fetch_size, 0, NULL);
5543 : 0 : break;
5544 : : }
5545 : : }
5546 [ + - + + : 139 : foreach(lc, table->options)
+ + ]
5547 : : {
5548 : 80 : DefElem *def = (DefElem *) lfirst(lc);
5549 : :
5550 [ - + ]: 80 : if (strcmp(def->defname, "fetch_size") == 0)
5551 : : {
5552 : 0 : (void) parse_int(defGetString(def), &fetch_size, 0, NULL);
5553 : 0 : break;
5554 : : }
5555 : : }
5556 : :
5557 : : /* Construct command to fetch rows from remote. */
5558 : 59 : snprintf(fetch_sql, sizeof(fetch_sql), "FETCH %d FROM c%u",
5559 : : fetch_size, cursor_number);
5560 : :
5561 : : /* Retrieve and process rows a batch at a time. */
5562 : : for (;;)
5563 : 241 : {
5564 : : int numrows;
5565 : : int i;
5566 : :
5567 : : /* Allow users to cancel long query */
5568 [ - + ]: 300 : CHECK_FOR_INTERRUPTS();
5569 : :
5570 : : /*
5571 : : * XXX possible future improvement: if rowstoskip is large, we could
5572 : : * issue a MOVE rather than physically fetching the rows, then just
5573 : : * adjust rowstoskip and samplerows appropriately.
5574 : : */
5575 : :
5576 : : /* Fetch some rows */
5577 : 300 : res = pgfdw_exec_query(conn, fetch_sql, NULL);
5578 : : /* On error, report the original query, not the FETCH. */
5579 [ - + ]: 300 : if (PQresultStatus(res) != PGRES_TUPLES_OK)
5580 : 0 : pgfdw_report_error(res, conn, sql.data);
5581 : :
5582 : : /* Process whatever we got. */
5583 : 300 : numrows = PQntuples(res);
5584 [ + + ]: 25180 : for (i = 0; i < numrows; i++)
5585 : 24881 : analyze_row_processor(res, i, &astate);
5586 : :
5587 : 299 : PQclear(res);
5588 : :
5589 : : /* Must be EOF if we didn't get all the rows requested. */
5590 [ + + ]: 299 : if (numrows < fetch_size)
5591 : 58 : break;
5592 : : }
5593 : :
5594 : : /* Close the cursor, just to be tidy. */
5595 : 58 : close_cursor(conn, cursor_number, NULL);
5596 : :
5597 : 58 : ReleaseConnection(conn);
5598 : :
5599 : : /* We assume that we have no dead tuple. */
5600 : 58 : *totaldeadrows = 0.0;
5601 : :
5602 : : /*
5603 : : * Without sampling, we've retrieved all living tuples from foreign
5604 : : * server, so report that as totalrows. Otherwise use the reltuples
5605 : : * estimate we got from the remote side.
5606 : : */
5607 [ + - ]: 58 : if (method == ANALYZE_SAMPLE_OFF)
5608 : 58 : *totalrows = astate.samplerows;
5609 : : else
5610 : 0 : *totalrows = reltuples;
5611 : :
5612 : : /*
5613 : : * Emit some interesting relation info
5614 : : */
5615 [ - + ]: 58 : ereport(elevel,
5616 : : (errmsg("\"%s\": table contains %.0f rows, %d rows in sample",
5617 : : RelationGetRelationName(relation),
5618 : : *totalrows, astate.numrows)));
5619 : :
5620 : 58 : return astate.numrows;
5621 : : }
5622 : :
5623 : : /*
5624 : : * Collect sample rows from the result of query.
5625 : : * - Use all tuples in sample until target # of samples are collected.
5626 : : * - Subsequently, replace already-sampled tuples randomly.
5627 : : */
5628 : : static void
5629 : 24881 : analyze_row_processor(PGresult *res, int row, PgFdwAnalyzeState *astate)
5630 : : {
5631 : 24881 : int targrows = astate->targrows;
5632 : : int pos; /* array index to store tuple in */
5633 : : MemoryContext oldcontext;
5634 : :
5635 : : /* Always increment sample row counter. */
5636 : 24881 : astate->samplerows += 1;
5637 : :
5638 : : /*
5639 : : * Determine the slot where this sample row should be stored. Set pos to
5640 : : * negative value to indicate the row should be skipped.
5641 : : */
5642 [ + - ]: 24881 : if (astate->numrows < targrows)
5643 : : {
5644 : : /* First targrows rows are always included into the sample */
5645 : 24881 : pos = astate->numrows++;
5646 : : }
5647 : : else
5648 : : {
5649 : : /*
5650 : : * Now we start replacing tuples in the sample until we reach the end
5651 : : * of the relation. Same algorithm as in acquire_sample_rows in
5652 : : * analyze.c; see Jeff Vitter's paper.
5653 : : */
5654 [ # # ]: 0 : if (astate->rowstoskip < 0)
5655 : 0 : astate->rowstoskip = reservoir_get_next_S(&astate->rstate, astate->samplerows, targrows);
5656 : :
5657 [ # # ]: 0 : if (astate->rowstoskip <= 0)
5658 : : {
5659 : : /* Choose a random reservoir element to replace. */
5660 : 0 : pos = (int) (targrows * sampler_random_fract(&astate->rstate.randstate));
5661 : : Assert(pos >= 0 && pos < targrows);
5662 : 0 : heap_freetuple(astate->rows[pos]);
5663 : : }
5664 : : else
5665 : : {
5666 : : /* Skip this tuple. */
5667 : 0 : pos = -1;
5668 : : }
5669 : :
5670 : 0 : astate->rowstoskip -= 1;
5671 : : }
5672 : :
5673 [ + - ]: 24881 : if (pos >= 0)
5674 : : {
5675 : : /*
5676 : : * Create sample tuple from current result row, and store it in the
5677 : : * position determined above. The tuple has to be created in anl_cxt.
5678 : : */
5679 : 24881 : oldcontext = MemoryContextSwitchTo(astate->anl_cxt);
5680 : :
5681 : 24881 : astate->rows[pos] = make_tuple_from_result_row(res, row,
5682 : : astate->rel,
5683 : : astate->attinmeta,
5684 : : astate->retrieved_attrs,
5685 : : NULL,
5686 : : astate->temp_cxt);
5687 : :
5688 : 24880 : MemoryContextSwitchTo(oldcontext);
5689 : : }
5690 : 24880 : }
5691 : :
5692 : : /*
5693 : : * postgresImportForeignStatistics
5694 : : * Attempt to import remote statistics instead of sampling.
5695 : : */
5696 : : static bool
5697 : 52 : postgresImportForeignStatistics(Relation relation, List *va_cols, int elevel)
5698 : : {
5699 : 52 : const char *schemaname = NULL;
5700 : 52 : const char *relname = NULL;
5701 : : ForeignTable *table;
5702 : : ForeignServer *server;
5703 : 52 : RemoteStatsResults remstats = {.rel = NULL, .att = NULL};
5704 : 52 : RemoteAttributeMapping *remattrmap = NULL;
5705 : 52 : int attrcnt = 0;
5706 : 52 : TimestampTz starttime = 0;
5707 : 52 : bool import_stats = false;
5708 : 52 : bool ok = false;
5709 : : ListCell *lc;
5710 : :
5711 : 52 : schemaname = get_namespace_name(RelationGetNamespace(relation));
5712 : 52 : relname = RelationGetRelationName(relation);
5713 : 52 : table = GetForeignTable(RelationGetRelid(relation));
5714 : 52 : server = GetForeignServer(table->serverid);
5715 : :
5716 : : /*
5717 : : * Check whether the import_stats option is enabled on the foreign table.
5718 : : * If not, silently ignore the foreign table.
5719 : : *
5720 : : * Server-level options can be overridden by table-level options, so check
5721 : : * server-level first.
5722 : : */
5723 [ + - + + : 283 : foreach(lc, server->options)
+ + ]
5724 : : {
5725 : 231 : DefElem *def = (DefElem *) lfirst(lc);
5726 : :
5727 [ - + ]: 231 : if (strcmp(def->defname, "import_stats") == 0)
5728 : : {
5729 : 0 : import_stats = defGetBoolean(def);
5730 : 0 : break;
5731 : : }
5732 : : }
5733 [ + - + + : 116 : foreach(lc, table->options)
+ + ]
5734 : : {
5735 : 77 : DefElem *def = (DefElem *) lfirst(lc);
5736 : :
5737 [ + + ]: 77 : if (strcmp(def->defname, "import_stats") == 0)
5738 : : {
5739 : 13 : import_stats = defGetBoolean(def);
5740 : 13 : break;
5741 : : }
5742 : : }
5743 [ + + ]: 52 : if (!import_stats)
5744 : 39 : return false;
5745 : :
5746 : : /*
5747 : : * We don't currently support statistics import for foreign tables with
5748 : : * extended statistics objects.
5749 : : */
5750 [ + + ]: 13 : if (HasRelationExtStatistics(relation))
5751 : : {
5752 [ + - ]: 1 : ereport(WARNING,
5753 : : errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5754 : : errmsg("cannot import statistics for foreign table \"%s.%s\" --- this foreign table has extended statistics objects",
5755 : : schemaname, relname));
5756 : 1 : return false;
5757 : : }
5758 : :
5759 : : /*
5760 : : * OK, let's do it.
5761 : : */
5762 [ + + ]: 12 : ereport(elevel,
5763 : : (errmsg("importing statistics for foreign table \"%s.%s\"",
5764 : : schemaname, relname)));
5765 : :
5766 : 12 : starttime = GetCurrentTimestamp();
5767 : :
5768 : 12 : ok = fetch_remote_statistics(relation, va_cols,
5769 : : schemaname, relname, table, server,
5770 : : &remstats, &remattrmap, &attrcnt);
5771 : :
5772 [ + + ]: 12 : if (ok)
5773 : 8 : ok = import_fetched_statistics(relation, schemaname, relname,
5774 : : &remstats, remattrmap, attrcnt);
5775 : :
5776 [ + + ]: 12 : if (ok)
5777 : : {
5778 : 8 : pgstat_report_analyze(relation, remstats.reltuples, 0,
5779 : : (va_cols == NIL), starttime);
5780 : :
5781 [ + - ]: 8 : ereport(elevel,
5782 : : (errmsg("finished importing statistics for foreign table \"%s.%s\"",
5783 : : schemaname, relname)));
5784 : : }
5785 : :
5786 : 12 : PQclear(remstats.rel);
5787 : 12 : PQclear(remstats.att);
5788 : 12 : free_remattrmap(remattrmap, attrcnt);
5789 : :
5790 : 12 : return ok;
5791 : : }
5792 : :
5793 : : /*
5794 : : * Attempt to fetch statistics from a remote server.
5795 : : */
5796 : : static bool
5797 : 12 : fetch_remote_statistics(Relation relation,
5798 : : List *va_cols,
5799 : : const char *local_schemaname,
5800 : : const char *local_relname,
5801 : : ForeignTable *table,
5802 : : ForeignServer *server,
5803 : : RemoteStatsResults *remstats,
5804 : : RemoteAttributeMapping **p_remattrmap,
5805 : : int *p_attrcnt)
5806 : : {
5807 : 12 : const char *remote_schemaname = NULL;
5808 : 12 : const char *remote_relname = NULL;
5809 : : UserMapping *user;
5810 : : PGconn *conn;
5811 : 12 : PGresult *relstats = NULL;
5812 : 12 : PGresult *attstats = NULL;
5813 : : int server_version_num;
5814 : : char relkind;
5815 : : double reltuples;
5816 : 12 : bool ok = false;
5817 : : ListCell *lc;
5818 : :
5819 : : /*
5820 : : * Assume the remote schema/table names are the same as the local name
5821 : : * unless the foreign table's options tell us otherwise.
5822 : : */
5823 : 12 : remote_schemaname = local_schemaname;
5824 : 12 : remote_relname = local_relname;
5825 [ + - + + : 36 : foreach(lc, table->options)
+ + ]
5826 : : {
5827 : 24 : DefElem *def = (DefElem *) lfirst(lc);
5828 : :
5829 [ - + ]: 24 : if (strcmp(def->defname, "schema_name") == 0)
5830 : 0 : remote_schemaname = defGetString(def);
5831 [ + + ]: 24 : else if (strcmp(def->defname, "table_name") == 0)
5832 : 12 : remote_relname = defGetString(def);
5833 : : }
5834 : :
5835 : : /*
5836 : : * Get the connection to use. We do the remote access as the table's
5837 : : * owner. Note that unlike AnalyzeForeignTable(), the core code would
5838 : : * already have switched us to the table's owner, before we are called
5839 : : * from ImportForeignStatistics().
5840 : : */
5841 : 12 : user = GetUserMapping(GetUserId(), table->serverid);
5842 : 12 : conn = GetConnection(user, false, NULL);
5843 : 12 : remstats->version = server_version_num = PQserverVersion(conn);
5844 : :
5845 : : /* Fetch relation stats. */
5846 : 12 : remstats->rel = relstats = fetch_relstats(conn, relation);
5847 : :
5848 : : /*
5849 : : * Verify that the remote table is the sort that can have meaningful stats
5850 : : * in pg_stats.
5851 : : *
5852 : : * Note that while relations of kinds RELKIND_INDEX and
5853 : : * RELKIND_PARTITIONED_INDEX can have rows in pg_stats, they obviously
5854 : : * can't support a foreign table.
5855 : : */
5856 : 12 : relkind = *PQgetvalue(relstats, 0, RELSTATS_RELKIND);
5857 [ + + ]: 12 : switch (relkind)
5858 : : {
5859 : 11 : case RELKIND_RELATION:
5860 : : case RELKIND_FOREIGN_TABLE:
5861 : : case RELKIND_MATVIEW:
5862 : : case RELKIND_PARTITIONED_TABLE:
5863 : 11 : break;
5864 : 1 : default:
5865 [ + - ]: 1 : ereport(WARNING,
5866 : : errmsg("could not import statistics for foreign table \"%s.%s\" --- remote table \"%s.%s\" is of relkind \"%c\" which cannot have statistics",
5867 : : local_schemaname, local_relname,
5868 : : remote_schemaname, remote_relname, relkind));
5869 : 1 : goto fetch_cleanup;
5870 : : }
5871 : :
5872 : : /*
5873 : : * For now, we don't support the case where the remote table is (or was
5874 : : * once) inherited; fallback to sampling in that case. XXX FIXME: for the
5875 : : * case where it is inherited, we could also support it by fetching and
5876 : : * adding the relation stats for child tables as well.
5877 : : */
5878 [ + + - + ]: 11 : if ((relkind == RELKIND_RELATION || relkind == RELKIND_FOREIGN_TABLE) &&
5879 [ - + ]: 10 : strcmp(PQgetvalue(relstats, 0, RELSTATS_RELHASSUBCLASS), "t") == 0)
5880 : : {
5881 [ # # ]: 0 : ereport(WARNING,
5882 : : errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5883 : : errmsg("could not import statistics for foreign table \"%s.%s\" --- remote table \"%s.%s\" is (or was once) inherited",
5884 : : local_schemaname, local_relname,
5885 : : remote_schemaname, remote_relname));
5886 : 0 : goto fetch_cleanup;
5887 : : }
5888 : :
5889 : : /*
5890 : : * If the reltuples value > 0, then we can expect to find attribute stats
5891 : : * for the remote table.
5892 : : *
5893 : : * In v14 or later, if the value is -1, it means the table had never been
5894 : : * analyzed, so we wouldn't expect to find the stats; fallback to sampling
5895 : : * in that case. If the value is 0, it means it was empty, in which case
5896 : : * we don't need the stats, so import relation stats only.
5897 : : *
5898 : : * In versions prior to v14, a value of 0 was ambiguous; it could mean
5899 : : * that the table had never been analyzed, or that it was empty. Assuming
5900 : : * the former, fallback to sampling.
5901 : : */
5902 : 11 : remstats->reltuples = reltuples =
5903 : 11 : strtod(PQgetvalue(relstats, 0, RELSTATS_RELTUPLES), NULL);
5904 [ + + ]: 11 : if (reltuples > 0)
5905 : : {
5906 : : RemoteAttributeMapping *remattrmap;
5907 : : int attrcnt;
5908 : : StringInfoData column_list;
5909 : :
5910 : : /* For columns to analyze, create mappings of local/remote columns. */
5911 : 9 : *p_remattrmap = remattrmap = build_remattrmap(relation, va_cols,
5912 : : &attrcnt, &column_list);
5913 : 9 : *p_attrcnt = attrcnt;
5914 : :
5915 : : /* Try to get attribute stats if needed. */
5916 [ + - ]: 9 : if (attrcnt > 0)
5917 : : {
5918 : : /*
5919 : : * The fetch_attstats query sends COLLATE "C" to the remote
5920 : : * server; if it hasn't got it, fallback to sampling.
5921 : : */
5922 [ - + ]: 9 : if (server_version_num < 90100)
5923 : : {
5924 [ # # ]: 0 : ereport(WARNING,
5925 : : errmsg("could not import statistics for foreign table \"%s.%s\" --- foreign server \"%s\" is too old to support attribute statistics import",
5926 : : local_schemaname, local_relname,
5927 : : server->servername));
5928 : 2 : goto fetch_cleanup;
5929 : : }
5930 : :
5931 : : /* Fetch attribute stats. */
5932 : 18 : remstats->att = attstats = fetch_attstats(conn,
5933 : : server_version_num,
5934 : : remote_schemaname,
5935 : : remote_relname,
5936 : 9 : column_list.data);
5937 : :
5938 : : /* If any attribute stats are missing, fallback to sampling. */
5939 [ + + ]: 9 : if (!match_attrmap(attstats,
5940 : : local_schemaname, local_relname,
5941 : : remote_schemaname, remote_relname,
5942 : : remattrmap, attrcnt))
5943 : 2 : goto fetch_cleanup;
5944 : : }
5945 : : }
5946 [ - + - - : 2 : else if (((server_version_num < 140000) && (reltuples == 0)) ||
+ - ]
5947 [ + + ]: 2 : ((server_version_num >= 140000) && (reltuples == -1)))
5948 : : {
5949 [ + - ]: 1 : ereport(WARNING,
5950 : : errmsg("could not import statistics for foreign table \"%s.%s\" --- remote table \"%s.%s\" has no relation statistics to import",
5951 : : local_schemaname, local_relname,
5952 : : remote_schemaname, remote_relname));
5953 : 1 : goto fetch_cleanup;
5954 : : }
5955 : :
5956 : : /*
5957 : : * If the remote table is partitioned, import relpages = 0, to match the
5958 : : * sampling path. Otherwise, import the relpages value as-is, regardless
5959 : : * of any difference between the remote and local block sizes. Note that
5960 : : * this is fine because it's only used for costing remote operations on
5961 : : * the foreign table.
5962 : : */
5963 [ + + ]: 8 : if (relkind == RELKIND_PARTITIONED_TABLE)
5964 : 1 : remstats->relpages = 0;
5965 : : else
5966 : 7 : remstats->relpages =
5967 : 7 : strtoul(PQgetvalue(relstats, 0, RELSTATS_RELPAGES), NULL, 10);
5968 : :
5969 : 8 : ok = true;
5970 : :
5971 : 12 : fetch_cleanup:
5972 : 12 : ReleaseConnection(conn);
5973 : 12 : return ok;
5974 : : }
5975 : :
5976 : : /*
5977 : : * Attempt to fetch remote relation stats.
5978 : : */
5979 : : static PGresult *
5980 : 12 : fetch_relstats(PGconn *conn, Relation relation)
5981 : : {
5982 : : StringInfoData sql;
5983 : : PGresult *res;
5984 : :
5985 : 12 : initStringInfo(&sql);
5986 : 12 : deparseAnalyzeInfoSql(&sql, relation);
5987 : :
5988 : 12 : res = pgfdw_exec_query(conn, sql.data, NULL);
5989 [ - + ]: 12 : if (PQresultStatus(res) != PGRES_TUPLES_OK)
5990 : 0 : pgfdw_report_error(res, conn, sql.data);
5991 : :
5992 [ + - - + ]: 12 : if (PQntuples(res) != 1 || PQnfields(res) != RELSTATS_NUM_FIELDS)
5993 [ # # ]: 0 : elog(ERROR, "unexpected result from deparseAnalyzeInfoSql query");
5994 : :
5995 : 12 : return res;
5996 : : }
5997 : :
5998 : : /*
5999 : : * Attempt to fetch remote attribute stats.
6000 : : */
6001 : : static PGresult *
6002 : 9 : fetch_attstats(PGconn *conn, int server_version_num,
6003 : : const char *remote_schemaname, const char *remote_relname,
6004 : : const char *column_list)
6005 : : {
6006 : : StringInfoData sql;
6007 : : PGresult *res;
6008 : :
6009 : : /*
6010 : : * The caller guarantees the remote server is v9.1, which supported
6011 : : * COLLATE "C", or later
6012 : : */
6013 : : Assert(server_version_num >= 90100);
6014 : :
6015 : 9 : initStringInfo(&sql);
6016 : :
6017 : : /* Type name is collatable since Postgres 12 */
6018 [ + - ]: 9 : if (server_version_num >= 120000)
6019 : 9 : appendStringInfoString(&sql,
6020 : : "SELECT DISTINCT ON (attname COLLATE \"C\") attname,");
6021 : : else
6022 : 0 : appendStringInfoString(&sql,
6023 : : "SELECT DISTINCT ON (attname::text COLLATE \"C\") attname,");
6024 : :
6025 : 9 : appendStringInfoString(&sql,
6026 : : " null_frac,"
6027 : : " avg_width,"
6028 : : " n_distinct,"
6029 : : " most_common_vals,"
6030 : : " most_common_freqs,"
6031 : : " histogram_bounds,"
6032 : : " correlation,");
6033 : :
6034 : : /* Elements stats are supported since Postgres 9.2 */
6035 [ + - ]: 9 : if (server_version_num >= 90200)
6036 : 9 : appendStringInfoString(&sql,
6037 : : " most_common_elems,"
6038 : : " most_common_elem_freqs,"
6039 : : " elem_count_histogram,");
6040 : : else
6041 : 0 : appendStringInfoString(&sql,
6042 : : " NULL, NULL, NULL,");
6043 : :
6044 : : /* Range stats are supported since Postgres 17 */
6045 [ + - ]: 9 : if (server_version_num >= 170000)
6046 : 9 : appendStringInfoString(&sql,
6047 : : " range_length_histogram,"
6048 : : " range_empty_frac,"
6049 : : " range_bounds_histogram");
6050 : : else
6051 : 0 : appendStringInfoString(&sql,
6052 : : " NULL, NULL, NULL");
6053 : :
6054 : 9 : appendStringInfoString(&sql,
6055 : : " FROM pg_catalog.pg_stats"
6056 : : " WHERE schemaname = ");
6057 : 9 : deparseStringLiteral(&sql, remote_schemaname);
6058 : 9 : appendStringInfoString(&sql,
6059 : : " AND tablename = ");
6060 : 9 : deparseStringLiteral(&sql, remote_relname);
6061 : 9 : appendStringInfo(&sql,
6062 : : " AND attname = ANY(%s)",
6063 : : column_list);
6064 : :
6065 : : /*
6066 : : * Type name is collatable since Postgres 12 (inherited is supported
6067 : : * since Postgres 9.0)
6068 : : */
6069 [ + - ]: 9 : if (server_version_num >= 120000)
6070 : 9 : appendStringInfoString(&sql,
6071 : : " ORDER BY attname COLLATE \"C\", inherited DESC");
6072 : : else
6073 : 0 : appendStringInfoString(&sql,
6074 : : " ORDER BY attname::text COLLATE \"C\", inherited DESC");
6075 : :
6076 : 9 : res = pgfdw_exec_query(conn, sql.data, NULL);
6077 [ - + ]: 9 : if (PQresultStatus(res) != PGRES_TUPLES_OK)
6078 : 0 : pgfdw_report_error(res, conn, sql.data);
6079 : :
6080 [ - + ]: 9 : if (PQnfields(res) != ATTSTATS_NUM_FIELDS)
6081 [ # # ]: 0 : elog(ERROR, "unexpected result from fetch_attstats query");
6082 : :
6083 : 9 : return res;
6084 : : }
6085 : :
6086 : : /*
6087 : : * For columns to analyze, build the mappings of local columns to remote
6088 : : * columns, and create a column list used for constructing the fetch_attstats
6089 : : * query.
6090 : : */
6091 : : static RemoteAttributeMapping *
6092 : 9 : build_remattrmap(Relation relation, List *va_cols,
6093 : : int *p_attrcnt, StringInfo column_list)
6094 : : {
6095 : 9 : TupleDesc tupdesc = RelationGetDescr(relation);
6096 : 9 : RemoteAttributeMapping *remattrmap = NULL;
6097 : 9 : int attrcnt = 0;
6098 : :
6099 : 9 : remattrmap = palloc_array(RemoteAttributeMapping, tupdesc->natts);
6100 : 9 : initStringInfo(column_list);
6101 : 9 : appendStringInfoString(column_list, "ARRAY[");
6102 [ + + ]: 34 : for (int i = 0; i < tupdesc->natts; i++)
6103 : : {
6104 : 25 : Form_pg_attribute attr = TupleDescAttr(tupdesc, i);
6105 : 25 : char *attname = NameStr(attr->attname);
6106 : 25 : AttrNumber attnum = attr->attnum;
6107 : : char *colname;
6108 : : List *fc_options;
6109 : : ListCell *lc;
6110 : :
6111 : : /* If a list is specified, exclude any attnames not in it. */
6112 [ + + ]: 25 : if (!attname_in_list(attname, va_cols))
6113 : 6 : continue;
6114 : :
6115 [ - + ]: 19 : if (!attribute_is_analyzable(relation, attnum, attr, NULL))
6116 : 0 : continue;
6117 : :
6118 : : /*
6119 : : * Assume the remote column names are the same as the local name
6120 : : * unless the foreign column's options tell us otherwise.
6121 : : */
6122 : 19 : colname = attname;
6123 : 19 : fc_options = GetForeignColumnOptions(RelationGetRelid(relation), attnum);
6124 [ + + + - : 19 : foreach(lc, fc_options)
+ + ]
6125 : : {
6126 : 5 : DefElem *def = (DefElem *) lfirst(lc);
6127 : :
6128 [ + - ]: 5 : if (strcmp(def->defname, "column_name") == 0)
6129 : : {
6130 : 5 : colname = defGetString(def);
6131 : 5 : break;
6132 : : }
6133 : : }
6134 : :
6135 [ + + ]: 19 : if (attrcnt > 0)
6136 : 10 : appendStringInfoString(column_list, ", ");
6137 : 19 : deparseStringLiteral(column_list, colname);
6138 : :
6139 : 19 : remattrmap[attrcnt].local_attnum = attnum;
6140 : 19 : remattrmap[attrcnt].local_attname = pstrdup(attname);
6141 : 19 : remattrmap[attrcnt].remote_attname = pstrdup(colname);
6142 : 19 : remattrmap[attrcnt].res_index = -1;
6143 : 19 : attrcnt++;
6144 : : }
6145 : 9 : appendStringInfoChar(column_list, ']');
6146 : :
6147 : : /* Sort the mappings by remote_attname if needed. */
6148 [ + + ]: 9 : if (attrcnt > 1)
6149 : 7 : qsort(remattrmap, attrcnt, sizeof(RemoteAttributeMapping), remattrmap_cmp);
6150 : :
6151 : 9 : *p_attrcnt = attrcnt;
6152 : 9 : return remattrmap;
6153 : : }
6154 : :
6155 : : /*
6156 : : * Free the structure created by build_remattrmap().
6157 : : */
6158 : : static void
6159 : 12 : free_remattrmap(RemoteAttributeMapping *map, int len)
6160 : : {
6161 [ + + ]: 12 : if (!map)
6162 : 3 : return;
6163 : :
6164 [ + + ]: 28 : for (int i = 0; i < len; i++)
6165 : : {
6166 : : Assert(map[i].local_attname);
6167 : 19 : pfree(map[i].local_attname);
6168 : : Assert(map[i].remote_attname);
6169 : 19 : pfree(map[i].remote_attname);
6170 : : }
6171 : :
6172 : 9 : pfree(map);
6173 : : }
6174 : :
6175 : : /*
6176 : : * Test if an attribute name is in the list.
6177 : : *
6178 : : * An empty list means that all attribute names are in the list.
6179 : : */
6180 : : static bool
6181 : 25 : attname_in_list(const char *attname, List *va_cols)
6182 : : {
6183 : : ListCell *lc;
6184 : :
6185 [ + + ]: 25 : if (va_cols == NIL)
6186 : 13 : return true;
6187 : :
6188 [ + - + + : 22 : foreach(lc, va_cols)
+ + ]
6189 : : {
6190 : 16 : char *col = strVal(lfirst(lc));
6191 : :
6192 [ + + ]: 16 : if (strcmp(attname, col) == 0)
6193 : 6 : return true;
6194 : : }
6195 : 6 : return false;
6196 : : }
6197 : :
6198 : : /*
6199 : : * Compare two RemoteAttributeMappings for sorting.
6200 : : */
6201 : : static int
6202 : 13 : remattrmap_cmp(const void *v1, const void *v2)
6203 : : {
6204 : 13 : const RemoteAttributeMapping *r1 = v1;
6205 : 13 : const RemoteAttributeMapping *r2 = v2;
6206 : :
6207 : 13 : return strcmp(r1->remote_attname, r2->remote_attname);
6208 : : }
6209 : :
6210 : : /*
6211 : : * Match local columns to result set rows.
6212 : : *
6213 : : * As the result set consists of the attribute stats for distinct mapped
6214 : : * remote columns, every entry in the RemoteAttributeMapping should have at
6215 : : * most one match in the result set; which is also ordered by remote_attname,
6216 : : * so we find such pairs by doing a merge join.
6217 : : *
6218 : : * Returns true if every entry in it has a match, and false if not.
6219 : : */
6220 : : static bool
6221 : 9 : match_attrmap(PGresult *res,
6222 : : const char *local_schemaname,
6223 : : const char *local_relname,
6224 : : const char *remote_schemaname,
6225 : : const char *remote_relname,
6226 : : RemoteAttributeMapping *remattrmap,
6227 : : int attrcnt)
6228 : : {
6229 : 9 : int numrows = PQntuples(res);
6230 : 9 : int row = -1;
6231 : :
6232 : : /* No work if there are no stats rows. */
6233 [ + + ]: 9 : if (numrows == 0)
6234 : : {
6235 [ + - ]: 1 : ereport(WARNING,
6236 : : errmsg("could not import statistics for foreign table \"%s.%s\" --- remote table \"%s.%s\" has no attribute statistics to import",
6237 : : local_schemaname, local_relname,
6238 : : remote_schemaname, remote_relname));
6239 : 1 : return false;
6240 : : }
6241 : :
6242 : : /* Scan all entries in the RemoteAttributeMapping. */
6243 [ + + ]: 23 : for (int mapidx = 0; mapidx < attrcnt; mapidx++)
6244 : : {
6245 : : /*
6246 : : * First, check whether the entry matches the current stats row, if it
6247 : : * is set.
6248 : : */
6249 [ + + ]: 16 : if (row >= 0 &&
6250 [ + + ]: 8 : strcmp(remattrmap[mapidx].remote_attname,
6251 : 8 : PQgetvalue(res, row, ATTSTATS_ATTNAME)) == 0)
6252 : : {
6253 : 3 : remattrmap[mapidx].res_index = row;
6254 : 3 : continue;
6255 : : }
6256 : :
6257 : : /*
6258 : : * If we've exhausted all stats rows, it means the stats for the entry
6259 : : * are missing.
6260 : : */
6261 [ + + ]: 13 : if (row >= numrows - 1)
6262 : : {
6263 [ + - ]: 1 : ereport(WARNING,
6264 : : errmsg("could not import statistics for foreign table \"%s.%s\" --- no attribute statistics found for column \"%s\" of remote table \"%s.%s\"",
6265 : : local_schemaname, local_relname,
6266 : : remattrmap[mapidx].remote_attname,
6267 : : remote_schemaname, remote_relname));
6268 : 1 : return false;
6269 : : }
6270 : :
6271 : : /* Advance to the next stats row. */
6272 : 12 : row += 1;
6273 : :
6274 : : /*
6275 : : * If the remote_attname in the entry is less than that in the next
6276 : : * stats row, it means the stats for the entry are missing.
6277 : : */
6278 [ - + ]: 12 : if (strcmp(remattrmap[mapidx].remote_attname,
6279 : 12 : PQgetvalue(res, row, ATTSTATS_ATTNAME)) < 0)
6280 : : {
6281 [ # # ]: 0 : ereport(WARNING,
6282 : : errmsg("could not import statistics for foreign table \"%s.%s\" --- no attribute statistics found for column \"%s\" of remote table \"%s.%s\"",
6283 : : local_schemaname, local_relname,
6284 : : remattrmap[mapidx].remote_attname,
6285 : : remote_schemaname, remote_relname));
6286 : 0 : return false;
6287 : : }
6288 : :
6289 : : /* We should not have got a stats row we didn't expect. */
6290 [ - + ]: 12 : if (strcmp(remattrmap[mapidx].remote_attname,
6291 : 12 : PQgetvalue(res, row, ATTSTATS_ATTNAME)) > 0)
6292 [ # # ]: 0 : elog(ERROR, "unexpected result from fetch_attstats query");
6293 : :
6294 : : /* We found a match. */
6295 : : Assert(strcmp(remattrmap[mapidx].remote_attname,
6296 : : PQgetvalue(res, row, ATTSTATS_ATTNAME)) == 0);
6297 : 12 : remattrmap[mapidx].res_index = row;
6298 : : }
6299 : :
6300 : : /* We should have exhausted all stats rows. */
6301 [ - + ]: 7 : if (row < numrows - 1)
6302 [ # # ]: 0 : elog(ERROR, "unexpected result from fetch_attstats query");
6303 : :
6304 : 7 : return true;
6305 : : }
6306 : :
6307 : : /*
6308 : : * Attempt to import fetched statistics into the local statistics tables.
6309 : : */
6310 : : static bool
6311 : 8 : import_fetched_statistics(Relation relation,
6312 : : const char *schemaname,
6313 : : const char *relname,
6314 : : RemoteStatsResults *remstats,
6315 : : const RemoteAttributeMapping *remattrmap,
6316 : : int attrcnt)
6317 : : {
6318 : : /*
6319 : : * ATTSTATS_NUM_FIELDS corresponds to the number of NullableDatum
6320 : : * arguments for import_attribute_statistics(), which is larger than that
6321 : : * for import_relation_statistics(). Therefore, a NullableDatum array of
6322 : : * that length is used to store data for each argument in both functions.
6323 : : */
6324 : : NullableDatum args[ATTSTATS_NUM_FIELDS];
6325 : :
6326 : : /* Set the 'version' parameter, which is common to both statistics. */
6327 : 8 : args[0].value = Int32GetDatum(remstats->version);
6328 : 8 : args[0].isnull = false;
6329 : :
6330 : : /*
6331 : : * We import attribute statistics first, if any, because those are more
6332 : : * prone to errors. This avoids making a modification of pg_class that
6333 : : * will just get rolled back by a failed attribute import.
6334 : : */
6335 [ + + ]: 8 : if (remstats->att != NULL)
6336 : : {
6337 : 7 : PGresult *res = remstats->att;
6338 : :
6339 : : Assert(PQnfields(res) == ATTSTATS_NUM_FIELDS);
6340 : : Assert(PQntuples(res) >= 1);
6341 : :
6342 [ + + ]: 20 : for (int mapidx = 0; mapidx < attrcnt; mapidx++)
6343 : : {
6344 : 13 : int row = remattrmap[mapidx].res_index;
6345 : 13 : AttrNumber attnum = remattrmap[mapidx].local_attnum;
6346 : :
6347 : : /* All mappings should have been assigned a result set row. */
6348 : : Assert(row >= 0);
6349 : :
6350 : : /* Check for user-requested abort. */
6351 [ - + ]: 13 : CHECK_FOR_INTERRUPTS();
6352 : :
6353 : : /* Clear existing attribute statistics. */
6354 : 13 : delete_attribute_statistics(relation, attnum, false);
6355 : :
6356 : : /* Set the remaining parameters. */
6357 : 13 : set_float_arg(&args[1],
6358 : 13 : get_opt_value(res, row, ATTSTATS_NULL_FRAC));
6359 : 13 : set_int32_arg(&args[2],
6360 : 13 : get_opt_value(res, row, ATTSTATS_AVG_WIDTH));
6361 : 13 : set_float_arg(&args[3],
6362 : 13 : get_opt_value(res, row, ATTSTATS_N_DISTINCT));
6363 : 13 : set_text_arg(&args[4],
6364 : 13 : get_opt_value(res, row, ATTSTATS_MOST_COMMON_VALS));
6365 : 13 : set_floatarr_arg(&args[5],
6366 : 13 : get_opt_value(res, row, ATTSTATS_MOST_COMMON_FREQS));
6367 : 13 : set_text_arg(&args[6],
6368 : 13 : get_opt_value(res, row, ATTSTATS_HISTOGRAM_BOUNDS));
6369 : 13 : set_float_arg(&args[7],
6370 : 13 : get_opt_value(res, row, ATTSTATS_CORRELATION));
6371 : 13 : set_text_arg(&args[8],
6372 : 13 : get_opt_value(res, row, ATTSTATS_MOST_COMMON_ELEMS));
6373 : 13 : set_floatarr_arg(&args[9],
6374 : 13 : get_opt_value(res, row, ATTSTATS_MOST_COMMON_ELEM_FREQS));
6375 : 13 : set_floatarr_arg(&args[10],
6376 : 13 : get_opt_value(res, row, ATTSTATS_ELEM_COUNT_HISTOGRAM));
6377 : 13 : set_text_arg(&args[11],
6378 : 13 : get_opt_value(res, row, ATTSTATS_RANGE_LENGTH_HISTOGRAM));
6379 : 13 : set_float_arg(&args[12],
6380 : 13 : get_opt_value(res, row, ATTSTATS_RANGE_EMPTY_FRAC));
6381 : 13 : set_text_arg(&args[13],
6382 : 13 : get_opt_value(res, row, ATTSTATS_RANGE_BOUNDS_HISTOGRAM));
6383 : :
6384 : : /* Try to import the statistics. */
6385 [ - + ]: 13 : if (!import_attribute_statistics(relation, attnum, false,
6386 : : &args[0], &args[1], &args[2],
6387 : : &args[3], &args[4], &args[5],
6388 : : &args[6], &args[7], &args[8],
6389 : : &args[9], &args[10], &args[11],
6390 : : &args[12], &args[13]))
6391 : : {
6392 [ # # ]: 0 : ereport(WARNING,
6393 : : errmsg("could not import statistics for foreign table \"%s.%s\" --- attribute statistics import failed for column \"%s\" of this foreign table",
6394 : : schemaname, relname,
6395 : : remattrmap[mapidx].local_attname));
6396 : 0 : return false;
6397 : : }
6398 : : }
6399 : : }
6400 : :
6401 : : /*
6402 : : * Import relation statistics.
6403 : : */
6404 : :
6405 : : /* Set the remaining parameters. */
6406 : 8 : args[1].value = Int32GetDatum(remstats->relpages);
6407 : 8 : args[1].isnull = false;
6408 : 8 : args[2].value = Float4GetDatum(remstats->reltuples);
6409 : 8 : args[2].isnull = false;
6410 : : /* We don't import relallvisible/relallfrozen. */
6411 : 8 : args[3].value = (Datum) 0;
6412 : 8 : args[3].isnull = true;
6413 : 8 : args[4].value = (Datum) 0;
6414 : 8 : args[4].isnull = true;
6415 : :
6416 : : /* Try to import the statistics. */
6417 [ - + ]: 8 : if (!import_relation_statistics(relation, &args[0], &args[1],
6418 : : &args[2], &args[3], &args[4]))
6419 : : {
6420 [ # # ]: 0 : ereport(WARNING,
6421 : : errmsg("could not import statistics for foreign table \"%s.%s\" --- relation statistics import failed for this foreign table",
6422 : : schemaname, relname));
6423 : 0 : return false;
6424 : : }
6425 : :
6426 : 8 : return true;
6427 : : }
6428 : :
6429 : : /*
6430 : : * Convenience routine to fetch the value for the row/column of the PGresult
6431 : : */
6432 : : static char *
6433 : 169 : get_opt_value(PGresult *res, int row, int col)
6434 : : {
6435 [ + + ]: 169 : if (PQgetisnull(res, row, col))
6436 : 93 : return NULL;
6437 : 76 : return PQgetvalue(res, row, col);
6438 : : }
6439 : :
6440 : : /*
6441 : : * Convenience routine for setting optional text arguments
6442 : : */
6443 : : static void
6444 : 65 : set_text_arg(NullableDatum *arg, const char *s)
6445 : : {
6446 [ + + ]: 65 : if (s)
6447 : : {
6448 : 13 : arg->value = CStringGetTextDatum(s);
6449 : 13 : arg->isnull = false;
6450 : : }
6451 : : else
6452 : : {
6453 : 52 : arg->value = (Datum) 0;
6454 : 52 : arg->isnull = true;
6455 : : }
6456 : 65 : }
6457 : :
6458 : : /*
6459 : : * Convenience routine for setting optional int32 arguments
6460 : : */
6461 : : static void
6462 : 13 : set_int32_arg(NullableDatum *arg, const char *s)
6463 : : {
6464 [ + - ]: 13 : if (s)
6465 : : {
6466 : 13 : int32 val = pg_strtoint32(s);
6467 : :
6468 : 13 : arg->value = Int32GetDatum(val);
6469 : 13 : arg->isnull = false;
6470 : : }
6471 : : else
6472 : : {
6473 : 0 : arg->value = (Datum) 0;
6474 : 0 : arg->isnull = true;
6475 : : }
6476 : 13 : }
6477 : :
6478 : : /*
6479 : : * Convenience routine for setting optional float arguments
6480 : : */
6481 : : static void
6482 : 52 : set_float_arg(NullableDatum *arg, const char *s)
6483 : : {
6484 [ + + ]: 52 : if (s)
6485 : : {
6486 : 39 : float4 val = float4in_internal(s, NULL, "float", s, NULL);
6487 : :
6488 : 39 : arg->value = Float4GetDatum(val);
6489 : 39 : arg->isnull = false;
6490 : : }
6491 : : else
6492 : : {
6493 : 13 : arg->value = (Datum) 0;
6494 : 13 : arg->isnull = true;
6495 : : }
6496 : 52 : }
6497 : :
6498 : : /*
6499 : : * Convenience routine for setting optional float[] arguments
6500 : : */
6501 : : static void
6502 : 39 : set_floatarr_arg(NullableDatum *arg, const char *s)
6503 : : {
6504 [ + + ]: 39 : if (s)
6505 : : {
6506 : : FmgrInfo flinfo;
6507 : : Datum val;
6508 : :
6509 : 11 : fmgr_info(F_ARRAY_IN, &flinfo);
6510 : 11 : val = InputFunctionCall(&flinfo, s, FLOAT4OID, -1);
6511 : :
6512 : 11 : arg->value = val;
6513 : 11 : arg->isnull = false;
6514 : : }
6515 : : else
6516 : : {
6517 : 28 : arg->value = (Datum) 0;
6518 : 28 : arg->isnull = true;
6519 : : }
6520 : 39 : }
6521 : :
6522 : : /*
6523 : : * Import a foreign schema
6524 : : */
6525 : : static List *
6526 : 10 : postgresImportForeignSchema(ImportForeignSchemaStmt *stmt, Oid serverOid)
6527 : : {
6528 : 10 : List *commands = NIL;
6529 : 10 : bool import_collate = true;
6530 : 10 : bool import_default = false;
6531 : 10 : bool import_generated = true;
6532 : 10 : bool import_not_null = true;
6533 : : ForeignServer *server;
6534 : : UserMapping *mapping;
6535 : : PGconn *conn;
6536 : : StringInfoData buf;
6537 : : PGresult *res;
6538 : : int numrows,
6539 : : i;
6540 : : ListCell *lc;
6541 : :
6542 : : /* Parse statement options */
6543 [ + + + + : 14 : foreach(lc, stmt->options)
+ + ]
6544 : : {
6545 : 4 : DefElem *def = (DefElem *) lfirst(lc);
6546 : :
6547 [ + + ]: 4 : if (strcmp(def->defname, "import_collate") == 0)
6548 : 1 : import_collate = defGetBoolean(def);
6549 [ + + ]: 3 : else if (strcmp(def->defname, "import_default") == 0)
6550 : 1 : import_default = defGetBoolean(def);
6551 [ + + ]: 2 : else if (strcmp(def->defname, "import_generated") == 0)
6552 : 1 : import_generated = defGetBoolean(def);
6553 [ + - ]: 1 : else if (strcmp(def->defname, "import_not_null") == 0)
6554 : 1 : import_not_null = defGetBoolean(def);
6555 : : else
6556 [ # # ]: 0 : ereport(ERROR,
6557 : : (errcode(ERRCODE_FDW_INVALID_OPTION_NAME),
6558 : : errmsg("invalid option \"%s\"", def->defname)));
6559 : : }
6560 : :
6561 : : /*
6562 : : * Get connection to the foreign server. Connection manager will
6563 : : * establish new connection if necessary.
6564 : : */
6565 : 10 : server = GetForeignServer(serverOid);
6566 : 10 : mapping = GetUserMapping(GetUserId(), server->serverid);
6567 : 10 : conn = GetConnection(mapping, false, NULL);
6568 : :
6569 : : /* Don't attempt to import collation if remote server hasn't got it */
6570 [ - + ]: 10 : if (PQserverVersion(conn) < 90100)
6571 : 0 : import_collate = false;
6572 : :
6573 : : /* Create workspace for strings */
6574 : 10 : initStringInfo(&buf);
6575 : :
6576 : : /* Check that the schema really exists */
6577 : 10 : appendStringInfoString(&buf, "SELECT 1 FROM pg_catalog.pg_namespace WHERE nspname = ");
6578 : 10 : deparseStringLiteral(&buf, stmt->remote_schema);
6579 : :
6580 : 10 : res = pgfdw_exec_query(conn, buf.data, NULL);
6581 [ - + ]: 10 : if (PQresultStatus(res) != PGRES_TUPLES_OK)
6582 : 0 : pgfdw_report_error(res, conn, buf.data);
6583 : :
6584 [ + + ]: 10 : if (PQntuples(res) != 1)
6585 [ + - ]: 1 : ereport(ERROR,
6586 : : (errcode(ERRCODE_FDW_SCHEMA_NOT_FOUND),
6587 : : errmsg("schema \"%s\" is not present on foreign server \"%s\"",
6588 : : stmt->remote_schema, server->servername)));
6589 : :
6590 : 9 : PQclear(res);
6591 : 9 : resetStringInfo(&buf);
6592 : :
6593 : : /*
6594 : : * Fetch all table data from this schema, possibly restricted by EXCEPT or
6595 : : * LIMIT TO. (We don't actually need to pay any attention to EXCEPT/LIMIT
6596 : : * TO here, because the core code will filter the statements we return
6597 : : * according to those lists anyway. But it should save a few cycles to
6598 : : * not process excluded tables in the first place.)
6599 : : *
6600 : : * Import table data for partitions only when they are explicitly
6601 : : * specified in LIMIT TO clause. Otherwise ignore them and only include
6602 : : * the definitions of the root partitioned tables to allow access to the
6603 : : * complete remote data set locally in the schema imported.
6604 : : *
6605 : : * Note: because we run the connection with search_path restricted to
6606 : : * pg_catalog, the format_type() and pg_get_expr() outputs will always
6607 : : * include a schema name for types/functions in other schemas, which is
6608 : : * what we want.
6609 : : */
6610 : 9 : appendStringInfoString(&buf,
6611 : : "SELECT relname, "
6612 : : " attname, "
6613 : : " format_type(atttypid, atttypmod), "
6614 : : " attnotnull, "
6615 : : " pg_get_expr(adbin, adrelid), ");
6616 : :
6617 : : /* Generated columns are supported since Postgres 12 */
6618 [ + - ]: 9 : if (PQserverVersion(conn) >= 120000)
6619 : 9 : appendStringInfoString(&buf,
6620 : : " attgenerated, ");
6621 : : else
6622 : 0 : appendStringInfoString(&buf,
6623 : : " NULL, ");
6624 : :
6625 [ + + ]: 9 : if (import_collate)
6626 : 8 : appendStringInfoString(&buf,
6627 : : " collname, "
6628 : : " collnsp.nspname ");
6629 : : else
6630 : 1 : appendStringInfoString(&buf,
6631 : : " NULL, NULL ");
6632 : :
6633 : 9 : appendStringInfoString(&buf,
6634 : : "FROM pg_class c "
6635 : : " JOIN pg_namespace n ON "
6636 : : " relnamespace = n.oid "
6637 : : " LEFT JOIN pg_attribute a ON "
6638 : : " attrelid = c.oid AND attnum > 0 "
6639 : : " AND NOT attisdropped "
6640 : : " LEFT JOIN pg_attrdef ad ON "
6641 : : " adrelid = c.oid AND adnum = attnum ");
6642 : :
6643 [ + + ]: 9 : if (import_collate)
6644 : 8 : appendStringInfoString(&buf,
6645 : : " LEFT JOIN pg_collation coll ON "
6646 : : " coll.oid = attcollation "
6647 : : " LEFT JOIN pg_namespace collnsp ON "
6648 : : " collnsp.oid = collnamespace ");
6649 : :
6650 : 9 : appendStringInfoString(&buf,
6651 : : "WHERE c.relkind IN ("
6652 : : CppAsString2(RELKIND_RELATION) ","
6653 : : CppAsString2(RELKIND_VIEW) ","
6654 : : CppAsString2(RELKIND_FOREIGN_TABLE) ","
6655 : : CppAsString2(RELKIND_MATVIEW) ","
6656 : : CppAsString2(RELKIND_PARTITIONED_TABLE) ") "
6657 : : " AND n.nspname = ");
6658 : 9 : deparseStringLiteral(&buf, stmt->remote_schema);
6659 : :
6660 : : /* Partitions are supported since Postgres 10 */
6661 [ + - ]: 9 : if (PQserverVersion(conn) >= 100000 &&
6662 [ + + ]: 9 : stmt->list_type != FDW_IMPORT_SCHEMA_LIMIT_TO)
6663 : 5 : appendStringInfoString(&buf, " AND NOT c.relispartition ");
6664 : :
6665 : : /* Apply restrictions for LIMIT TO and EXCEPT */
6666 [ + + ]: 9 : if (stmt->list_type == FDW_IMPORT_SCHEMA_LIMIT_TO ||
6667 [ + + ]: 5 : stmt->list_type == FDW_IMPORT_SCHEMA_EXCEPT)
6668 : : {
6669 : 5 : bool first_item = true;
6670 : :
6671 : 5 : appendStringInfoString(&buf, " AND c.relname ");
6672 [ + + ]: 5 : if (stmt->list_type == FDW_IMPORT_SCHEMA_EXCEPT)
6673 : 1 : appendStringInfoString(&buf, "NOT ");
6674 : 5 : appendStringInfoString(&buf, "IN (");
6675 : :
6676 : : /* Append list of table names within IN clause */
6677 [ + - + + : 15 : foreach(lc, stmt->table_list)
+ + ]
6678 : : {
6679 : 10 : RangeVar *rv = (RangeVar *) lfirst(lc);
6680 : :
6681 [ + + ]: 10 : if (first_item)
6682 : 5 : first_item = false;
6683 : : else
6684 : 5 : appendStringInfoString(&buf, ", ");
6685 : 10 : deparseStringLiteral(&buf, rv->relname);
6686 : : }
6687 : 5 : appendStringInfoChar(&buf, ')');
6688 : : }
6689 : :
6690 : : /* Append ORDER BY at the end of query to ensure output ordering */
6691 : 9 : appendStringInfoString(&buf, " ORDER BY c.relname, a.attnum");
6692 : :
6693 : : /* Fetch the data */
6694 : 9 : res = pgfdw_exec_query(conn, buf.data, NULL);
6695 [ - + ]: 9 : if (PQresultStatus(res) != PGRES_TUPLES_OK)
6696 : 0 : pgfdw_report_error(res, conn, buf.data);
6697 : :
6698 : : /* Process results */
6699 : 9 : numrows = PQntuples(res);
6700 : : /* note: incrementation of i happens in inner loop's while() test */
6701 [ + + ]: 47 : for (i = 0; i < numrows;)
6702 : : {
6703 : 38 : char *tablename = PQgetvalue(res, i, 0);
6704 : 38 : bool first_item = true;
6705 : :
6706 : 38 : resetStringInfo(&buf);
6707 : 38 : appendStringInfo(&buf, "CREATE FOREIGN TABLE %s (\n",
6708 : : quote_identifier(tablename));
6709 : :
6710 : : /* Scan all rows for this table */
6711 : : do
6712 : : {
6713 : : char *attname;
6714 : : char *typename;
6715 : : char *attnotnull;
6716 : : char *attgenerated;
6717 : : char *attdefault;
6718 : : char *collname;
6719 : : char *collnamespace;
6720 : :
6721 : : /* If table has no columns, we'll see nulls here */
6722 [ + + ]: 75 : if (PQgetisnull(res, i, 1))
6723 : 5 : continue;
6724 : :
6725 : 70 : attname = PQgetvalue(res, i, 1);
6726 : 70 : typename = PQgetvalue(res, i, 2);
6727 : 70 : attnotnull = PQgetvalue(res, i, 3);
6728 [ + + ]: 70 : attdefault = PQgetisnull(res, i, 4) ? NULL :
6729 : 15 : PQgetvalue(res, i, 4);
6730 [ + - ]: 70 : attgenerated = PQgetisnull(res, i, 5) ? NULL :
6731 : 70 : PQgetvalue(res, i, 5);
6732 [ + + ]: 70 : collname = PQgetisnull(res, i, 6) ? NULL :
6733 : 19 : PQgetvalue(res, i, 6);
6734 [ + + ]: 70 : collnamespace = PQgetisnull(res, i, 7) ? NULL :
6735 : 19 : PQgetvalue(res, i, 7);
6736 : :
6737 [ + + ]: 70 : if (first_item)
6738 : 33 : first_item = false;
6739 : : else
6740 : 37 : appendStringInfoString(&buf, ",\n");
6741 : :
6742 : : /* Print column name and type */
6743 : 70 : appendStringInfo(&buf, " %s %s",
6744 : : quote_identifier(attname),
6745 : : typename);
6746 : :
6747 : : /*
6748 : : * Add column_name option so that renaming the foreign table's
6749 : : * column doesn't break the association to the underlying column.
6750 : : */
6751 : 70 : appendStringInfoString(&buf, " OPTIONS (column_name ");
6752 : 70 : deparseStringLiteral(&buf, attname);
6753 : 70 : appendStringInfoChar(&buf, ')');
6754 : :
6755 : : /* Add COLLATE if needed */
6756 [ + + + + : 70 : if (import_collate && collname != NULL && collnamespace != NULL)
+ - ]
6757 : 19 : appendStringInfo(&buf, " COLLATE %s.%s",
6758 : : quote_identifier(collnamespace),
6759 : : quote_identifier(collname));
6760 : :
6761 : : /* Add DEFAULT if needed */
6762 [ + + + + : 70 : if (import_default && attdefault != NULL &&
+ - ]
6763 [ + + ]: 3 : (!attgenerated || !attgenerated[0]))
6764 : 2 : appendStringInfo(&buf, " DEFAULT %s", attdefault);
6765 : :
6766 : : /* Add GENERATED if needed */
6767 [ + + + - ]: 70 : if (import_generated && attgenerated != NULL &&
6768 [ + + ]: 57 : attgenerated[0] == ATTRIBUTE_GENERATED_STORED)
6769 : : {
6770 : : Assert(attdefault != NULL);
6771 : 4 : appendStringInfo(&buf,
6772 : : " GENERATED ALWAYS AS (%s) STORED",
6773 : : attdefault);
6774 : : }
6775 : :
6776 : : /* Add NOT NULL if needed */
6777 [ + + + + ]: 70 : if (import_not_null && attnotnull[0] == 't')
6778 : 4 : appendStringInfoString(&buf, " NOT NULL");
6779 : : }
6780 [ + + ]: 75 : while (++i < numrows &&
6781 [ + + ]: 66 : strcmp(PQgetvalue(res, i, 0), tablename) == 0);
6782 : :
6783 : : /*
6784 : : * Add server name and table-level options. We specify remote schema
6785 : : * and table name as options (the latter to ensure that renaming the
6786 : : * foreign table doesn't break the association).
6787 : : */
6788 : 38 : appendStringInfo(&buf, "\n) SERVER %s\nOPTIONS (",
6789 : 38 : quote_identifier(server->servername));
6790 : :
6791 : 38 : appendStringInfoString(&buf, "schema_name ");
6792 : 38 : deparseStringLiteral(&buf, stmt->remote_schema);
6793 : 38 : appendStringInfoString(&buf, ", table_name ");
6794 : 38 : deparseStringLiteral(&buf, tablename);
6795 : :
6796 : 38 : appendStringInfoString(&buf, ");");
6797 : :
6798 : 38 : commands = lappend(commands, pstrdup(buf.data));
6799 : : }
6800 : 9 : PQclear(res);
6801 : :
6802 : 9 : ReleaseConnection(conn);
6803 : :
6804 : 9 : return commands;
6805 : : }
6806 : :
6807 : : /*
6808 : : * Check if reltarget is safe enough to push down semi-join. Reltarget is not
6809 : : * safe, if it contains references to inner rel relids, which do not belong to
6810 : : * outer rel.
6811 : : */
6812 : : static bool
6813 : 65 : semijoin_target_ok(PlannerInfo *root, RelOptInfo *joinrel, RelOptInfo *outerrel, RelOptInfo *innerrel)
6814 : : {
6815 : : List *vars;
6816 : : ListCell *lc;
6817 : 65 : bool ok = true;
6818 : :
6819 : : Assert(joinrel->reltarget);
6820 : :
6821 : 65 : vars = pull_var_clause((Node *) joinrel->reltarget->exprs, PVC_INCLUDE_PLACEHOLDERS);
6822 : :
6823 [ + - + + : 445 : foreach(lc, vars)
+ + ]
6824 : : {
6825 : 395 : Var *var = (Var *) lfirst(lc);
6826 : :
6827 [ - + ]: 395 : if (!IsA(var, Var))
6828 : 0 : continue;
6829 : :
6830 [ + + ]: 395 : if (bms_is_member(var->varno, innerrel->relids))
6831 : : {
6832 : : /*
6833 : : * The planner can create semi-join, which refers to inner rel
6834 : : * vars in its target list. However, we deparse semi-join as an
6835 : : * exists() subquery, so can't handle references to inner rel in
6836 : : * the target list.
6837 : : */
6838 : : Assert(!bms_is_member(var->varno, outerrel->relids));
6839 : 15 : ok = false;
6840 : 15 : break;
6841 : : }
6842 : : }
6843 : 65 : return ok;
6844 : : }
6845 : :
6846 : : /*
6847 : : * get_base_relids
6848 : : * Return the set of base relids referenced by a foreign scan rel.
6849 : : *
6850 : : * For an upper rel we use the all-query relids minus the outer joins;
6851 : : * otherwise the rel's own relids minus the outer joins. The result matches
6852 : : * the relids that create_foreignscan_plan() ultimately uses for
6853 : : * ForeignScan.fs_base_relids, so it is suitable for any tagging we want to
6854 : : * store via plan-private state.
6855 : : */
6856 : : static Relids
6857 : 2516 : get_base_relids(PlannerInfo *root, RelOptInfo *rel)
6858 : : {
6859 : : Relids relids;
6860 : :
6861 [ + + ]: 2516 : if (rel->reloptkind == RELOPT_UPPER_REL)
6862 : 250 : relids = root->all_query_rels;
6863 : : else
6864 : 2266 : relids = rel->relids;
6865 : :
6866 : 2516 : return bms_difference(relids, root->outer_join_rels);
6867 : : }
6868 : :
6869 : : /*
6870 : : * get_min_base_rti
6871 : : * Lowest base RT index in the foreign scan rel.
6872 : : *
6873 : : * After setrefs.c flattens the rtable, the scan-local indexes saved in
6874 : : * plan-private data can be translated to estate indexes by adding
6875 : : * (ForeignScan.fs_base_relids min - this value). Captured at plan time
6876 : : * because create_foreignscan_plan() computes the same value internally.
6877 : : */
6878 : : static int
6879 : 1258 : get_min_base_rti(PlannerInfo *root, RelOptInfo *rel)
6880 : : {
6881 : 1258 : Relids relids = get_base_relids(root, rel);
6882 : :
6883 : 1258 : return bms_next_member(relids, -1);
6884 : : }
6885 : :
6886 : : /*
6887 : : * get_functions_data
6888 : : * Build the per-RTE function metadata list saved as
6889 : : * FdwScanPrivateFunctions.
6890 : : *
6891 : : * The result list is indexed by base RT index relative to the lowest base
6892 : : * RT index of the scan. Each element is either NULL (for non-RTE_FUNCTION
6893 : : * base rels in this scan) or a List of List of two Integer nodes:
6894 : : * (funcrettype, funccollation) -- one inner list per RangeTblFunction.
6895 : : *
6896 : : * Only RTE_FUNCTION relids actually appearing in the foreign scan's
6897 : : * fs_base_relids contribute; others are placeholders so that the consumer
6898 : : * can index into the result by RTI offset.
6899 : : */
6900 : : static List *
6901 : 1258 : get_functions_data(PlannerInfo *root, RelOptInfo *rel)
6902 : : {
6903 : 1258 : List *rtfuncdata = NIL;
6904 : 1258 : Relids fscan_relids = get_base_relids(root, rel);
6905 : : int i;
6906 : :
6907 [ + + ]: 6289 : for (i = 0; i < root->simple_rel_array_size; i++)
6908 : : {
6909 : 5031 : RangeTblEntry *rte = root->simple_rte_array[i];
6910 : 5031 : List *funcdata = NIL;
6911 : : ListCell *lc;
6912 : :
6913 [ + + + - ]: 5031 : if (rte == NULL || i == 0 ||
6914 [ + + ]: 3773 : !bms_is_member(i, fscan_relids) ||
6915 [ + + ]: 1562 : rte->rtekind != RTE_FUNCTION)
6916 : : {
6917 : 5003 : rtfuncdata = lappend(rtfuncdata, NULL);
6918 : 5003 : continue;
6919 : : }
6920 : :
6921 [ + - + + : 66 : foreach(lc, rte->functions)
+ + ]
6922 : : {
6923 : 38 : RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
6924 : : Oid funcrettype;
6925 : : Oid funccollation;
6926 : : TupleDesc tupdesc;
6927 : : Oid funcid;
6928 : :
6929 : 38 : get_expr_result_type(rtfunc->funcexpr, &funcrettype, &tupdesc);
6930 : :
6931 : : /*
6932 : : * function_rte_pushdown_ok() already rejected any function that
6933 : : * doesn't return a well-defined scalar type, so this is a mere
6934 : : * cross-check.
6935 : : */
6936 : : Assert(OidIsValid(funcrettype) && funcrettype != RECORDOID);
6937 : :
6938 : 38 : funccollation = exprCollation(rtfunc->funcexpr);
6939 : :
6940 : 38 : funcid = ((FuncExpr *) rtfunc->funcexpr)->funcid;
6941 : :
6942 : 38 : funcdata = lappend(funcdata,
6943 : 38 : list_make3(makeInteger(funcid),
6944 : : makeInteger(funcrettype),
6945 : : makeInteger(funccollation)));
6946 : : }
6947 : :
6948 : 28 : rtfuncdata = lappend(rtfuncdata, funcdata);
6949 : : }
6950 : :
6951 : 1258 : return rtfuncdata;
6952 : : }
6953 : :
6954 : : /*
6955 : : * init_func_stub_fpinfo
6956 : : * Build a stub PgFdwRelationInfo for a FUNCTION RTE that is being
6957 : : * absorbed into a foreign join.
6958 : : *
6959 : : * A function RTE has no fdw_private of its own, but the joinrel-level cost
6960 : : * estimator, deparser and merge_fdw_options() all read server-level options
6961 : : * from the "outer" fpinfo unconditionally. So the stub must carry the same
6962 : : * server, shippable_extensions, and cost-related options as the real foreign
6963 : : * side of the join; otherwise the pushdown path is judged against zeroed
6964 : : * fdw_startup_cost/fdw_tuple_cost/etc. and looks artificially cheap.
6965 : : *
6966 : : * The stub is meaningful only for the specific (foreign, function) pairing
6967 : : * that produced it; it must live on the joinrel's PgFdwRelationInfo, never
6968 : : * on the function rel's fdw_private, since the same function RTE may pair
6969 : : * with different foreign servers in sibling joinrels.
6970 : : */
6971 : : static PgFdwRelationInfo *
6972 : 31 : init_func_stub_fpinfo(const PgFdwRelationInfo *fpinfo_foreign,
6973 : : RelOptInfo *funcrel)
6974 : : {
6975 : 31 : PgFdwRelationInfo *stub = palloc0_object(PgFdwRelationInfo);
6976 : :
6977 : 31 : stub->pushdown_safe = true;
6978 : :
6979 : : /* Connection information and options, inherited from the foreign side */
6980 : 31 : stub->server = fpinfo_foreign->server;
6981 : 31 : stub->user = fpinfo_foreign->user;
6982 : 31 : stub->shippable_extensions = fpinfo_foreign->shippable_extensions;
6983 : 31 : stub->fdw_startup_cost = fpinfo_foreign->fdw_startup_cost;
6984 : 31 : stub->fdw_tuple_cost = fpinfo_foreign->fdw_tuple_cost;
6985 : 31 : stub->use_remote_estimate = fpinfo_foreign->use_remote_estimate;
6986 : 31 : stub->fetch_size = fpinfo_foreign->fetch_size;
6987 : 31 : stub->async_capable = fpinfo_foreign->async_capable;
6988 : :
6989 : : /* Function-side identity and estimates from the local planner. */
6990 : 31 : stub->relation_name = psprintf("%u", funcrel->relid);
6991 : 31 : stub->rows = funcrel->rows;
6992 : 31 : stub->width = funcrel->reltarget->width;
6993 : 31 : stub->retrieved_rows = funcrel->rows;
6994 : :
6995 : : /*
6996 : : * The function is executed on the remote server, so these must carry its
6997 : : * cost the same way a foreign rel's do: what producing the rows costs the
6998 : : * far side, before connection setup and data transfer are added. The
6999 : : * local path for the same function is our best estimate of that.
7000 : : */
7001 : 31 : stub->rel_startup_cost = funcrel->cheapest_total_path->startup_cost;
7002 : 31 : stub->rel_total_cost = funcrel->cheapest_total_path->total_cost;
7003 : :
7004 : 31 : return stub;
7005 : : }
7006 : :
7007 : : /*
7008 : : * Check if a relation is a FUNCTION RTE that can be absorbed into a remote
7009 : : * join. Every function in the RTE must
7010 : : *
7011 : : * - return a well-defined scalar type -- we don't ship records/composite
7012 : : * since the remote server cannot reconstruct a column definition list
7013 : : * and our deparser does not emit one;
7014 : : * - have a shippable expression with no mutable subnodes -- is_foreign_expr()
7015 : : * rejects volatile/stable functions through contain_mutable_functions(),
7016 : : * so the IMMUTABLE-only restriction is implicit;
7017 : : * - not contain SubPlans -- we'd otherwise need to ship sub-results to
7018 : : * the remote, which we do not implement.
7019 : : *
7020 : : * WITH ORDINALITY is not supported yet.
7021 : : */
7022 : : static bool
7023 : 37 : function_rte_pushdown_ok(PlannerInfo *root, RelOptInfo *rel,
7024 : : RelOptInfo *fdwrel)
7025 : : {
7026 : : RangeTblEntry *rte;
7027 : : ListCell *lc;
7028 : :
7029 [ - + ]: 37 : if (rel->rtekind != RTE_FUNCTION)
7030 : 0 : return false;
7031 [ + - ]: 37 : rte = planner_rt_fetch(rel->relid, root);
7032 : :
7033 : : /*
7034 : : * build_simple_rel() copies rtekind straight from the RTE, so for a base
7035 : : * rel rel->rtekind always matches the RTE's; the check above is therefore
7036 : : * sufficient.
7037 : : */
7038 : : Assert(rte->rtekind == RTE_FUNCTION);
7039 : :
7040 [ + + ]: 37 : if (rte->funcordinality)
7041 : 1 : return false;
7042 : :
7043 : : /*
7044 : : * Reject up-front any function RTE that lateral-references another
7045 : : * relation: foreign-join push-down would need to parameterise the remote
7046 : : * query per outer row, which we don't support, and even considering the
7047 : : * path is expensive on the planner side. The surrounding lateral_relids
7048 : : * check in postgresGetForeignJoinPaths() would normally bail out for the
7049 : : * joinrel, but doing the check here avoids walking the function
7050 : : * expression entirely.
7051 : : *
7052 : : * Note this rejects only lateral references to another relation at the
7053 : : * same query level. A function argument referencing an outer query level
7054 : : * (e.g. f(outer.col) inside a subquery) is a different case: it becomes a
7055 : : * PARAM_EXEC Param, the function rel's lateral_relids is empty, and
7056 : : * foreign_expr_walker() intentionally treats PARAM_EXEC as shippable. The
7057 : : * remote query then carries a parameter placeholder, and postgres_fdw's
7058 : : * ordinary parameter machinery re-sends it on each rescan -- i.e. it
7059 : : * works as a normal parameterized foreign scan, which is fine.
7060 : : */
7061 [ + + ]: 36 : if (!bms_is_empty(rel->lateral_relids))
7062 : 1 : return false;
7063 : :
7064 : : Assert(list_length(rte->functions) >= 1);
7065 : :
7066 [ + - + + : 76 : foreach(lc, rte->functions)
+ + ]
7067 : : {
7068 : 45 : RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
7069 : : TypeFuncClass functypclass;
7070 : : Oid funcrettype;
7071 : : TupleDesc tupdesc;
7072 : :
7073 : : /* Refuse to deal with strange funcexprs */
7074 [ - + ]: 45 : if (!IsA(rtfunc->funcexpr, FuncExpr))
7075 : 4 : return false;
7076 : :
7077 [ - + ]: 45 : if (!OidIsValid(((FuncExpr *) rtfunc->funcexpr)->funcid))
7078 : 0 : return false;
7079 : :
7080 : 45 : functypclass = get_expr_result_type(rtfunc->funcexpr,
7081 : : &funcrettype, &tupdesc);
7082 [ + + ]: 45 : if (functypclass != TYPEFUNC_SCALAR)
7083 : 1 : return false;
7084 [ + - ]: 44 : if (!OidIsValid(funcrettype) ||
7085 [ + - ]: 44 : funcrettype == RECORDOID ||
7086 [ - + ]: 44 : funcrettype == VOIDOID)
7087 : 0 : return false;
7088 : :
7089 [ - + ]: 44 : if (contain_subplans(rtfunc->funcexpr))
7090 : 0 : return false;
7091 [ + + ]: 44 : if (!is_foreign_expr(root, fdwrel, fdwrel->fdw_private, (Expr *) rtfunc->funcexpr))
7092 : 3 : return false;
7093 : : }
7094 : :
7095 : 31 : return true;
7096 : : }
7097 : :
7098 : : /*
7099 : : * Assess whether the join between inner and outer relations can be pushed down
7100 : : * to the foreign server. As a side effect, save information we obtain in this
7101 : : * function to PgFdwRelationInfo passed in.
7102 : : */
7103 : : static bool
7104 : 450 : foreign_join_ok(PlannerInfo *root, RelOptInfo *joinrel, JoinType jointype,
7105 : : RelOptInfo *outerrel, RelOptInfo *innerrel,
7106 : : JoinPathExtraData *extra)
7107 : : {
7108 : : PgFdwRelationInfo *fpinfo;
7109 : : PgFdwRelationInfo *fpinfo_o;
7110 : : PgFdwRelationInfo *fpinfo_i;
7111 : : ListCell *lc;
7112 : : List *joinclauses;
7113 : :
7114 : : /*
7115 : : * We support pushing down INNER, LEFT, RIGHT, FULL OUTER and SEMI joins.
7116 : : * Constructing queries representing ANTI joins is hard, hence not
7117 : : * considered right now.
7118 : : */
7119 [ + + + + : 450 : if (jointype != JOIN_INNER && jointype != JOIN_LEFT &&
+ - ]
7120 [ + + + + ]: 130 : jointype != JOIN_RIGHT && jointype != JOIN_FULL &&
7121 : : jointype != JOIN_SEMI)
7122 : 19 : return false;
7123 : :
7124 : : /*
7125 : : * We can't push down semi-join if its reltarget is not safe
7126 : : */
7127 [ + + + + ]: 431 : if ((jointype == JOIN_SEMI) && !semijoin_target_ok(root, joinrel, outerrel, innerrel))
7128 : 15 : return false;
7129 : :
7130 : : /*
7131 : : * Detect mixed (foreign x function-RTE) cases. Only INNER joins are
7132 : : * supported initially. We dispatch on rtekind here so that the same
7133 : : * function RTE can be absorbed into joins on multiple foreign servers
7134 : : * (each call gets its own stub fpinfo and rechecks shippability for the
7135 : : * specific server).
7136 : : *
7137 : : * A function rel has no fdw_private of its own, so when one side is a
7138 : : * function RTE we replace its NULL fpinfo with a stub, and the rest of
7139 : : * this function and the cost estimator can then treat both sides
7140 : : * uniformly. We hand the stub to the joinrel's deparser via the same
7141 : : * path the foreign side uses, but we never permanently attach it to the
7142 : : * function rel's fdw_private (different joinrels may pair the same
7143 : : * function RTE with different foreign servers).
7144 : : */
7145 : 416 : fpinfo = (PgFdwRelationInfo *) joinrel->fdw_private;
7146 : 416 : fpinfo_o = (PgFdwRelationInfo *) outerrel->fdw_private;
7147 : 416 : fpinfo_i = (PgFdwRelationInfo *) innerrel->fdw_private;
7148 : :
7149 [ + + + + : 416 : if (jointype == JOIN_INNER && innerrel->rtekind == RTE_FUNCTION &&
+ - ]
7150 [ + - + + ]: 58 : fpinfo_o && fpinfo_o->pushdown_safe &&
7151 : 29 : function_rte_pushdown_ok(root, innerrel, outerrel))
7152 : : {
7153 : 23 : fpinfo_i = init_func_stub_fpinfo(fpinfo_o, innerrel);
7154 : :
7155 : : /*
7156 : : * Classify the function rel's own baserestrictinfo now, so that the
7157 : : * local_conds check below can bail out if any of it is unshippable.
7158 : : * We classify against the stub, not the joinrel's fpinfo, because the
7159 : : * latter's server/shippable_extensions aren't populated until
7160 : : * merge_fdw_options() runs further down.
7161 : : */
7162 : 23 : classifyConditions(root, innerrel, fpinfo_i, innerrel->baserestrictinfo,
7163 : : &fpinfo_i->remote_conds, &fpinfo_i->local_conds);
7164 : 23 : fpinfo->inner_func_fpinfo = fpinfo_i;
7165 : : }
7166 [ + + + + : 393 : else if (jointype == JOIN_INNER && outerrel->rtekind == RTE_FUNCTION &&
+ - ]
7167 [ + - + - ]: 16 : fpinfo_i && fpinfo_i->pushdown_safe &&
7168 : 8 : function_rte_pushdown_ok(root, outerrel, innerrel))
7169 : : {
7170 : 8 : fpinfo_o = init_func_stub_fpinfo(fpinfo_i, outerrel);
7171 : :
7172 : : /* See the comment in the branch above. */
7173 : 8 : classifyConditions(root, outerrel, fpinfo_o, outerrel->baserestrictinfo,
7174 : : &fpinfo_o->remote_conds, &fpinfo_o->local_conds);
7175 : 8 : fpinfo->outer_func_fpinfo = fpinfo_o;
7176 : : }
7177 [ + - + + : 385 : else if (!fpinfo_o || !fpinfo_o->pushdown_safe ||
+ + ]
7178 [ - + ]: 372 : !fpinfo_i || !fpinfo_i->pushdown_safe)
7179 : 13 : return false;
7180 : :
7181 : : /*
7182 : : * If joining relations have local conditions, those conditions are
7183 : : * required to be applied before joining the relations. Hence the join can
7184 : : * not be pushed down.
7185 : : */
7186 [ + + + + ]: 403 : if (fpinfo_o->local_conds || fpinfo_i->local_conds)
7187 : 11 : return false;
7188 : :
7189 : : /*
7190 : : * Merge FDW options. We might be tempted to do this after we have deemed
7191 : : * the foreign join to be OK. But we must do this beforehand so that we
7192 : : * know which quals can be evaluated on the foreign server, which might
7193 : : * depend on shippable_extensions.
7194 : : */
7195 : 392 : fpinfo->server = fpinfo_o->server;
7196 : 392 : merge_fdw_options(fpinfo, fpinfo_o, fpinfo_i);
7197 : :
7198 : : /*
7199 : : * Separate restrict list into join quals and pushed-down (other) quals.
7200 : : *
7201 : : * Join quals belonging to an outer join must all be shippable, else we
7202 : : * cannot execute the join remotely. Add such quals to 'joinclauses'.
7203 : : *
7204 : : * Add other quals to fpinfo->remote_conds if they are shippable, else to
7205 : : * fpinfo->local_conds. In an inner join it's okay to execute conditions
7206 : : * either locally or remotely; the same is true for pushed-down conditions
7207 : : * at an outer join.
7208 : : *
7209 : : * Note we might return failure after having already scribbled on
7210 : : * fpinfo->remote_conds and fpinfo->local_conds. That's okay because we
7211 : : * won't consult those lists again if we deem the join unshippable.
7212 : : */
7213 : 392 : joinclauses = NIL;
7214 [ + + + + : 779 : foreach(lc, extra->restrictlist)
+ + ]
7215 : : {
7216 : 390 : RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc);
7217 : 390 : bool is_remote_clause = is_foreign_expr(root, joinrel, fpinfo,
7218 : : rinfo->clause);
7219 : :
7220 [ + + ]: 390 : if (IS_OUTER_JOIN(jointype) &&
7221 [ + + + - ]: 137 : !RINFO_IS_PUSHED_DOWN(rinfo, joinrel->relids))
7222 : : {
7223 [ + + ]: 121 : if (!is_remote_clause)
7224 : 3 : return false;
7225 : 118 : joinclauses = lappend(joinclauses, rinfo);
7226 : : }
7227 : : else
7228 : : {
7229 [ + + ]: 269 : if (is_remote_clause)
7230 : 257 : fpinfo->remote_conds = lappend(fpinfo->remote_conds, rinfo);
7231 : : else
7232 : 12 : fpinfo->local_conds = lappend(fpinfo->local_conds, rinfo);
7233 : : }
7234 : : }
7235 : :
7236 : : /*
7237 : : * deparseExplicitTargetList() isn't smart enough to handle anything other
7238 : : * than a Var. In particular, if there's some PlaceHolderVar that would
7239 : : * need to be evaluated within this join tree (because there's an upper
7240 : : * reference to a quantity that may go to NULL as a result of an outer
7241 : : * join), then we can't try to push the join down because we'll fail when
7242 : : * we get to deparseExplicitTargetList(). However, a PlaceHolderVar that
7243 : : * needs to be evaluated *at the top* of this join tree is OK, because we
7244 : : * can do that locally after fetching the results from the remote side.
7245 : : */
7246 [ + + + + : 392 : foreach(lc, root->placeholder_list)
+ + ]
7247 : : {
7248 : 11 : PlaceHolderInfo *phinfo = lfirst(lc);
7249 : : Relids relids;
7250 : :
7251 : : /* PlaceHolderInfo refers to parent relids, not child relids. */
7252 [ + + - + ]: 11 : relids = IS_OTHER_REL(joinrel) ?
7253 [ + - ]: 22 : joinrel->top_parent_relids : joinrel->relids;
7254 : :
7255 [ + - + + ]: 22 : if (bms_is_subset(phinfo->ph_eval_at, relids) &&
7256 : 11 : bms_nonempty_difference(relids, phinfo->ph_eval_at))
7257 : 8 : return false;
7258 : : }
7259 : :
7260 : : /* Save the join clauses, for later use. */
7261 : 381 : fpinfo->joinclauses = joinclauses;
7262 : :
7263 : 381 : fpinfo->outerrel = outerrel;
7264 : 381 : fpinfo->innerrel = innerrel;
7265 : 381 : fpinfo->jointype = jointype;
7266 : :
7267 : : /*
7268 : : * By default, both the input relations are not required to be deparsed as
7269 : : * subqueries, but there might be some relations covered by the input
7270 : : * relations that are required to be deparsed as subqueries, so save the
7271 : : * relids of those relations for later use by the deparser.
7272 : : */
7273 : 381 : fpinfo->make_outerrel_subquery = false;
7274 : 381 : fpinfo->make_innerrel_subquery = false;
7275 : : Assert(bms_is_subset(fpinfo_o->lower_subquery_rels, outerrel->relids));
7276 : : Assert(bms_is_subset(fpinfo_i->lower_subquery_rels, innerrel->relids));
7277 : 762 : fpinfo->lower_subquery_rels = bms_union(fpinfo_o->lower_subquery_rels,
7278 : 381 : fpinfo_i->lower_subquery_rels);
7279 : 762 : fpinfo->hidden_subquery_rels = bms_union(fpinfo_o->hidden_subquery_rels,
7280 : 381 : fpinfo_i->hidden_subquery_rels);
7281 : :
7282 : : /*
7283 : : * Pull the other remote conditions from the joining relations into join
7284 : : * clauses or other remote clauses (remote_conds) of this relation
7285 : : * wherever possible. This avoids building subqueries at every join step.
7286 : : *
7287 : : * For an inner join, clauses from both the relations are added to the
7288 : : * other remote clauses. For LEFT and RIGHT OUTER join, the clauses from
7289 : : * the outer side are added to remote_conds since those can be evaluated
7290 : : * after the join is evaluated. The clauses from inner side are added to
7291 : : * the joinclauses, since they need to be evaluated while constructing the
7292 : : * join.
7293 : : *
7294 : : * For SEMI-JOIN clauses from inner relation can not be added to
7295 : : * remote_conds, but should be treated as join clauses (as they are
7296 : : * deparsed to EXISTS subquery, where inner relation can be referred). A
7297 : : * list of relation ids, which can't be referred to from higher levels, is
7298 : : * preserved as a hidden_subquery_rels list.
7299 : : *
7300 : : * For a FULL OUTER JOIN, the other clauses from either relation can not
7301 : : * be added to the joinclauses or remote_conds, since each relation acts
7302 : : * as an outer relation for the other.
7303 : : *
7304 : : * The joining sides can not have local conditions, thus no need to test
7305 : : * shippability of the clauses being pulled up.
7306 : : */
7307 [ + + - + : 381 : switch (jointype)
+ - ]
7308 : : {
7309 : 227 : case JOIN_INNER:
7310 : 454 : fpinfo->remote_conds = list_concat(fpinfo->remote_conds,
7311 : 227 : fpinfo_i->remote_conds);
7312 : 454 : fpinfo->remote_conds = list_concat(fpinfo->remote_conds,
7313 : 227 : fpinfo_o->remote_conds);
7314 : 227 : break;
7315 : :
7316 : 68 : case JOIN_LEFT:
7317 : :
7318 : : /*
7319 : : * When semi-join is involved in the inner or outer part of the
7320 : : * left join, it's deparsed as a subquery, and we can't refer to
7321 : : * its vars on the upper level.
7322 : : */
7323 [ + + ]: 68 : if (bms_is_empty(fpinfo_i->hidden_subquery_rels))
7324 : 64 : fpinfo->joinclauses = list_concat(fpinfo->joinclauses,
7325 : 64 : fpinfo_i->remote_conds);
7326 [ + - ]: 68 : if (bms_is_empty(fpinfo_o->hidden_subquery_rels))
7327 : 68 : fpinfo->remote_conds = list_concat(fpinfo->remote_conds,
7328 : 68 : fpinfo_o->remote_conds);
7329 : 68 : break;
7330 : :
7331 : 0 : case JOIN_RIGHT:
7332 : :
7333 : : /*
7334 : : * When semi-join is involved in the inner or outer part of the
7335 : : * right join, it's deparsed as a subquery, and we can't refer to
7336 : : * its vars on the upper level.
7337 : : */
7338 [ # # ]: 0 : if (bms_is_empty(fpinfo_o->hidden_subquery_rels))
7339 : 0 : fpinfo->joinclauses = list_concat(fpinfo->joinclauses,
7340 : 0 : fpinfo_o->remote_conds);
7341 [ # # ]: 0 : if (bms_is_empty(fpinfo_i->hidden_subquery_rels))
7342 : 0 : fpinfo->remote_conds = list_concat(fpinfo->remote_conds,
7343 : 0 : fpinfo_i->remote_conds);
7344 : 0 : break;
7345 : :
7346 : 44 : case JOIN_SEMI:
7347 : 88 : fpinfo->joinclauses = list_concat(fpinfo->joinclauses,
7348 : 44 : fpinfo_i->remote_conds);
7349 : 88 : fpinfo->joinclauses = list_concat(fpinfo->joinclauses,
7350 : 44 : fpinfo->remote_conds);
7351 : 44 : fpinfo->remote_conds = list_copy(fpinfo_o->remote_conds);
7352 : 88 : fpinfo->hidden_subquery_rels = bms_union(fpinfo->hidden_subquery_rels,
7353 : 44 : innerrel->relids);
7354 : 44 : break;
7355 : :
7356 : 42 : case JOIN_FULL:
7357 : :
7358 : : /*
7359 : : * In this case, if any of the input relations has conditions, we
7360 : : * need to deparse that relation as a subquery so that the
7361 : : * conditions can be evaluated before the join. Remember it in
7362 : : * the fpinfo of this relation so that the deparser can take
7363 : : * appropriate action. Also, save the relids of base relations
7364 : : * covered by that relation for later use by the deparser.
7365 : : */
7366 [ + + ]: 42 : if (fpinfo_o->remote_conds)
7367 : : {
7368 : 14 : fpinfo->make_outerrel_subquery = true;
7369 : 14 : fpinfo->lower_subquery_rels =
7370 : 14 : bms_add_members(fpinfo->lower_subquery_rels,
7371 : 14 : outerrel->relids);
7372 : : }
7373 [ + + ]: 42 : if (fpinfo_i->remote_conds)
7374 : : {
7375 : 14 : fpinfo->make_innerrel_subquery = true;
7376 : 14 : fpinfo->lower_subquery_rels =
7377 : 14 : bms_add_members(fpinfo->lower_subquery_rels,
7378 : 14 : innerrel->relids);
7379 : : }
7380 : 42 : break;
7381 : :
7382 : 0 : default:
7383 : : /* Should not happen, we have just checked this above */
7384 [ # # ]: 0 : elog(ERROR, "unsupported join type %d", jointype);
7385 : : }
7386 : :
7387 : : /*
7388 : : * For an inner join, all restrictions can be treated alike. Treating the
7389 : : * pushed down conditions as join conditions allows a top level full outer
7390 : : * join to be deparsed without requiring subqueries.
7391 : : */
7392 [ + + ]: 381 : if (jointype == JOIN_INNER)
7393 : : {
7394 : : Assert(!fpinfo->joinclauses);
7395 : 227 : fpinfo->joinclauses = fpinfo->remote_conds;
7396 : 227 : fpinfo->remote_conds = NIL;
7397 : : }
7398 [ + + + - : 154 : else if (jointype == JOIN_LEFT || jointype == JOIN_RIGHT || jointype == JOIN_FULL)
+ + ]
7399 : : {
7400 : : /*
7401 : : * Conditions, generated from semi-joins, should be evaluated before
7402 : : * LEFT/RIGHT/FULL join.
7403 : : */
7404 [ - + ]: 110 : if (!bms_is_empty(fpinfo_o->hidden_subquery_rels))
7405 : : {
7406 : 0 : fpinfo->make_outerrel_subquery = true;
7407 : 0 : fpinfo->lower_subquery_rels = bms_add_members(fpinfo->lower_subquery_rels, outerrel->relids);
7408 : : }
7409 : :
7410 [ + + ]: 110 : if (!bms_is_empty(fpinfo_i->hidden_subquery_rels))
7411 : : {
7412 : 4 : fpinfo->make_innerrel_subquery = true;
7413 : 4 : fpinfo->lower_subquery_rels = bms_add_members(fpinfo->lower_subquery_rels, innerrel->relids);
7414 : : }
7415 : : }
7416 : :
7417 : : /* Mark that this join can be pushed down safely */
7418 : 381 : fpinfo->pushdown_safe = true;
7419 : :
7420 : : /* Get user mapping */
7421 [ + + ]: 381 : if (fpinfo->use_remote_estimate)
7422 : : {
7423 [ + + ]: 227 : if (fpinfo_o->use_remote_estimate)
7424 : 159 : fpinfo->user = fpinfo_o->user;
7425 : : else
7426 : 68 : fpinfo->user = fpinfo_i->user;
7427 : : }
7428 : : else
7429 : 154 : fpinfo->user = NULL;
7430 : :
7431 : : /*
7432 : : * Set # of retrieved rows and cached relation costs to some negative
7433 : : * value, so that we can detect when they are set to some sensible values,
7434 : : * during one (usually the first) of the calls to estimate_path_cost_size.
7435 : : */
7436 : 381 : fpinfo->retrieved_rows = -1;
7437 : 381 : fpinfo->rel_startup_cost = -1;
7438 : 381 : fpinfo->rel_total_cost = -1;
7439 : :
7440 : : /*
7441 : : * Set the string describing this join relation to be used in EXPLAIN
7442 : : * output of corresponding ForeignScan. Note that the decoration we add
7443 : : * to the base relation names mustn't include any digits, or it'll confuse
7444 : : * postgresExplainForeignScan.
7445 : : */
7446 : 381 : fpinfo->relation_name = psprintf("(%s) %s JOIN (%s)",
7447 : : fpinfo_o->relation_name,
7448 : : get_jointype_name(fpinfo->jointype),
7449 : : fpinfo_i->relation_name);
7450 : :
7451 : : /*
7452 : : * Set the relation index. This is defined as the position of this
7453 : : * joinrel in the join_rel_list list plus the length of the rtable list.
7454 : : * Note that since this joinrel is at the end of the join_rel_list list
7455 : : * when we are called, we can get the position by list_length.
7456 : : */
7457 : : Assert(fpinfo->relation_index == 0); /* shouldn't be set yet */
7458 : 381 : fpinfo->relation_index =
7459 : 381 : list_length(root->parse->rtable) + list_length(root->join_rel_list);
7460 : :
7461 : 381 : return true;
7462 : : }
7463 : :
7464 : : static void
7465 : 1730 : add_paths_with_pathkeys_for_rel(PlannerInfo *root, RelOptInfo *rel,
7466 : : Path *epq_path, List *restrictlist)
7467 : : {
7468 : 1730 : List *useful_pathkeys_list = NIL; /* List of all pathkeys */
7469 : : ListCell *lc;
7470 : :
7471 : 1730 : useful_pathkeys_list = get_useful_pathkeys_for_relation(root, rel);
7472 : :
7473 : : /*
7474 : : * Before creating sorted paths, arrange for the passed-in EPQ path, if
7475 : : * any, to return columns needed by the parent ForeignScan node so that
7476 : : * they will propagate up through Sort nodes injected below, if necessary.
7477 : : */
7478 [ + + + + ]: 1730 : if (epq_path != NULL && useful_pathkeys_list != NIL)
7479 : : {
7480 : 34 : PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) rel->fdw_private;
7481 : 34 : PathTarget *target = copy_pathtarget(epq_path->pathtarget);
7482 : :
7483 : : /* Include columns required for evaluating PHVs in the tlist. */
7484 : 34 : add_new_columns_to_pathtarget(target,
7485 : 34 : pull_var_clause((Node *) target->exprs,
7486 : : PVC_RECURSE_PLACEHOLDERS));
7487 : :
7488 : : /* Include columns required for evaluating the local conditions. */
7489 [ + + + + : 37 : foreach(lc, fpinfo->local_conds)
+ + ]
7490 : : {
7491 : 3 : RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc);
7492 : :
7493 : 3 : add_new_columns_to_pathtarget(target,
7494 : 3 : pull_var_clause((Node *) rinfo->clause,
7495 : : PVC_RECURSE_PLACEHOLDERS));
7496 : : }
7497 : :
7498 : : /*
7499 : : * If we have added any new columns, adjust the tlist of the EPQ path.
7500 : : *
7501 : : * Note: the plan created using this path will only be used to execute
7502 : : * EPQ checks, where accuracy of the plan cost and width estimates
7503 : : * would not be important, so we do not do set_pathtarget_cost_width()
7504 : : * for the new pathtarget here. See also postgresGetForeignPlan().
7505 : : */
7506 [ + + ]: 34 : if (list_length(target->exprs) > list_length(epq_path->pathtarget->exprs))
7507 : : {
7508 : : /* The EPQ path is a join path, so it is projection-capable. */
7509 : : Assert(is_projection_capable_path(epq_path));
7510 : :
7511 : : /*
7512 : : * Use create_projection_path() here, so as to avoid modifying it
7513 : : * in place.
7514 : : */
7515 : 4 : epq_path = (Path *) create_projection_path(root,
7516 : : rel,
7517 : : epq_path,
7518 : : target);
7519 : : }
7520 : : }
7521 : :
7522 : : /* Create one path for each set of pathkeys we found above. */
7523 [ + + + + : 2540 : foreach(lc, useful_pathkeys_list)
+ + ]
7524 : : {
7525 : : double rows;
7526 : : int width;
7527 : : int disabled_nodes;
7528 : : Cost startup_cost;
7529 : : Cost total_cost;
7530 : 810 : List *useful_pathkeys = lfirst(lc);
7531 : : Path *sorted_epq_path;
7532 : :
7533 : 810 : estimate_path_cost_size(root, rel, NIL, useful_pathkeys, NULL,
7534 : : &rows, &width, &disabled_nodes,
7535 : : &startup_cost, &total_cost);
7536 : :
7537 : : /*
7538 : : * The EPQ path must be at least as well sorted as the path itself, in
7539 : : * case it gets used as input to a mergejoin.
7540 : : */
7541 : 810 : sorted_epq_path = epq_path;
7542 [ + + ]: 810 : if (sorted_epq_path != NULL &&
7543 [ + + ]: 34 : !pathkeys_contained_in(useful_pathkeys,
7544 : : sorted_epq_path->pathkeys))
7545 : : sorted_epq_path = (Path *)
7546 : 26 : create_sort_path(root,
7547 : : rel,
7548 : : sorted_epq_path,
7549 : : useful_pathkeys,
7550 : : -1.0);
7551 : :
7552 [ + + + + ]: 810 : if (IS_SIMPLE_REL(rel))
7553 : 514 : add_path(rel, (Path *)
7554 : 514 : create_foreignscan_path(root, rel,
7555 : : NULL,
7556 : : rows,
7557 : : disabled_nodes,
7558 : : startup_cost,
7559 : : total_cost,
7560 : : useful_pathkeys,
7561 : : rel->lateral_relids,
7562 : : sorted_epq_path,
7563 : : NIL, /* no fdw_restrictinfo
7564 : : * list */
7565 : : NIL));
7566 : : else
7567 : 296 : add_path(rel, (Path *)
7568 : 296 : create_foreign_join_path(root, rel,
7569 : : NULL,
7570 : : rows,
7571 : : disabled_nodes,
7572 : : startup_cost,
7573 : : total_cost,
7574 : : useful_pathkeys,
7575 : : rel->lateral_relids,
7576 : : sorted_epq_path,
7577 : : restrictlist,
7578 : : NIL));
7579 : : }
7580 : 1730 : }
7581 : :
7582 : : /*
7583 : : * Parse options from foreign server and apply them to fpinfo.
7584 : : *
7585 : : * New options might also require tweaking merge_fdw_options().
7586 : : */
7587 : : static void
7588 : 1351 : apply_server_options(PgFdwRelationInfo *fpinfo)
7589 : : {
7590 : : ListCell *lc;
7591 : :
7592 [ + - + + : 5827 : foreach(lc, fpinfo->server->options)
+ + ]
7593 : : {
7594 : 4476 : DefElem *def = (DefElem *) lfirst(lc);
7595 : :
7596 [ + + ]: 4476 : if (strcmp(def->defname, "use_remote_estimate") == 0)
7597 : 176 : fpinfo->use_remote_estimate = defGetBoolean(def);
7598 [ + + ]: 4300 : else if (strcmp(def->defname, "fdw_startup_cost") == 0)
7599 : 6 : (void) parse_real(defGetString(def), &fpinfo->fdw_startup_cost, 0,
7600 : : NULL);
7601 [ + + ]: 4294 : else if (strcmp(def->defname, "fdw_tuple_cost") == 0)
7602 : 2 : (void) parse_real(defGetString(def), &fpinfo->fdw_tuple_cost, 0,
7603 : : NULL);
7604 [ + + ]: 4292 : else if (strcmp(def->defname, "extensions") == 0)
7605 : 987 : fpinfo->shippable_extensions =
7606 : 987 : ExtractExtensionList(defGetString(def), false);
7607 [ - + ]: 3305 : else if (strcmp(def->defname, "fetch_size") == 0)
7608 : 0 : (void) parse_int(defGetString(def), &fpinfo->fetch_size, 0, NULL);
7609 [ + + ]: 3305 : else if (strcmp(def->defname, "async_capable") == 0)
7610 : 191 : fpinfo->async_capable = defGetBoolean(def);
7611 : : }
7612 : 1351 : }
7613 : :
7614 : : /*
7615 : : * Parse options from foreign table and apply them to fpinfo.
7616 : : *
7617 : : * New options might also require tweaking merge_fdw_options().
7618 : : */
7619 : : static void
7620 : 1351 : apply_table_options(PgFdwRelationInfo *fpinfo)
7621 : : {
7622 : : ListCell *lc;
7623 : :
7624 [ + - + + : 3819 : foreach(lc, fpinfo->table->options)
+ + ]
7625 : : {
7626 : 2468 : DefElem *def = (DefElem *) lfirst(lc);
7627 : :
7628 [ + + ]: 2468 : if (strcmp(def->defname, "use_remote_estimate") == 0)
7629 : 351 : fpinfo->use_remote_estimate = defGetBoolean(def);
7630 [ - + ]: 2117 : else if (strcmp(def->defname, "fetch_size") == 0)
7631 : 0 : (void) parse_int(defGetString(def), &fpinfo->fetch_size, 0, NULL);
7632 [ - + ]: 2117 : else if (strcmp(def->defname, "async_capable") == 0)
7633 : 0 : fpinfo->async_capable = defGetBoolean(def);
7634 : : }
7635 : 1351 : }
7636 : :
7637 : : /*
7638 : : * Merge FDW options from input relations into a new set of options for a join
7639 : : * or an upper rel.
7640 : : *
7641 : : * For a join relation, FDW-specific information about the inner and outer
7642 : : * relations is provided using fpinfo_i and fpinfo_o. For an upper relation,
7643 : : * fpinfo_o provides the information for the input relation; fpinfo_i is
7644 : : * expected to NULL.
7645 : : */
7646 : : static void
7647 : 873 : merge_fdw_options(PgFdwRelationInfo *fpinfo,
7648 : : const PgFdwRelationInfo *fpinfo_o,
7649 : : const PgFdwRelationInfo *fpinfo_i)
7650 : : {
7651 : : /* We must always have fpinfo_o. */
7652 : : Assert(fpinfo_o);
7653 : :
7654 : : /* fpinfo_i may be NULL, but if present the servers must both match. */
7655 : : Assert(!fpinfo_i ||
7656 : : fpinfo_i->server->serverid == fpinfo_o->server->serverid);
7657 : :
7658 : : /*
7659 : : * Copy the server specific FDW options. (For a join, both relations come
7660 : : * from the same server, so the server options should have the same value
7661 : : * for both relations.)
7662 : : */
7663 : 873 : fpinfo->fdw_startup_cost = fpinfo_o->fdw_startup_cost;
7664 : 873 : fpinfo->fdw_tuple_cost = fpinfo_o->fdw_tuple_cost;
7665 : 873 : fpinfo->shippable_extensions = fpinfo_o->shippable_extensions;
7666 : 873 : fpinfo->use_remote_estimate = fpinfo_o->use_remote_estimate;
7667 : 873 : fpinfo->fetch_size = fpinfo_o->fetch_size;
7668 : 873 : fpinfo->async_capable = fpinfo_o->async_capable;
7669 : :
7670 : : /* Merge the table level options from either side of the join. */
7671 [ + + ]: 873 : if (fpinfo_i)
7672 : : {
7673 : : /*
7674 : : * We'll prefer to use remote estimates for this join if any table
7675 : : * from either side of the join is using remote estimates. This is
7676 : : * most likely going to be preferred since they're already willing to
7677 : : * pay the price of a round trip to get the remote EXPLAIN. In any
7678 : : * case it's not entirely clear how we might otherwise handle this
7679 : : * best.
7680 : : */
7681 [ + + ]: 620 : fpinfo->use_remote_estimate = fpinfo_o->use_remote_estimate ||
7682 [ + + ]: 228 : fpinfo_i->use_remote_estimate;
7683 : :
7684 : : /*
7685 : : * Set fetch size to maximum of the joining sides, since we are
7686 : : * expecting the rows returned by the join to be proportional to the
7687 : : * relation sizes.
7688 : : */
7689 : 392 : fpinfo->fetch_size = Max(fpinfo_o->fetch_size, fpinfo_i->fetch_size);
7690 : :
7691 : : /*
7692 : : * We'll prefer to consider this join async-capable if any table from
7693 : : * either side of the join is considered async-capable. This would be
7694 : : * reasonable because in that case the foreign server would have its
7695 : : * own resources to scan that table asynchronously, and the join could
7696 : : * also be computed asynchronously using the resources.
7697 : : */
7698 [ + + ]: 768 : fpinfo->async_capable = fpinfo_o->async_capable ||
7699 [ - + ]: 768 : fpinfo_i->async_capable;
7700 : : }
7701 : 873 : }
7702 : :
7703 : : /*
7704 : : * postgresGetForeignJoinPaths
7705 : : * Add possible ForeignPath to joinrel, if join is safe to push down.
7706 : : */
7707 : : static void
7708 : 1470 : postgresGetForeignJoinPaths(PlannerInfo *root,
7709 : : RelOptInfo *joinrel,
7710 : : RelOptInfo *outerrel,
7711 : : RelOptInfo *innerrel,
7712 : : JoinType jointype,
7713 : : JoinPathExtraData *extra)
7714 : : {
7715 : : PgFdwRelationInfo *fpinfo;
7716 : : ForeignPath *joinpath;
7717 : : double rows;
7718 : : int width;
7719 : : int disabled_nodes;
7720 : : Cost startup_cost;
7721 : : Cost total_cost;
7722 : : Path *epq_path; /* Path to create plan to be executed when
7723 : : * EvalPlanQual gets triggered. */
7724 : :
7725 : : /*
7726 : : * Skip if this join combination has been considered already.
7727 : : */
7728 [ + + ]: 1470 : if (joinrel->fdw_private)
7729 : 1089 : return;
7730 : :
7731 : : /*
7732 : : * This code does not work for joins with lateral references, since those
7733 : : * must have parameterized paths, which we don't generate yet.
7734 : : */
7735 [ + + ]: 454 : if (!bms_is_empty(joinrel->lateral_relids))
7736 : 4 : return;
7737 : :
7738 : : /*
7739 : : * Create unfinished PgFdwRelationInfo entry which is used to indicate
7740 : : * that the join relation is already considered, so that we won't waste
7741 : : * time in judging safety of join pushdown and adding the same paths again
7742 : : * if found safe. Once we know that this join can be pushed down, we fill
7743 : : * the entry.
7744 : : */
7745 : 450 : fpinfo = palloc0_object(PgFdwRelationInfo);
7746 : 450 : fpinfo->pushdown_safe = false;
7747 : 450 : joinrel->fdw_private = fpinfo;
7748 : : /* attrs_used is only for base relations. */
7749 : 450 : fpinfo->attrs_used = NULL;
7750 : :
7751 : : /*
7752 : : * If there is a possibility that EvalPlanQual will be executed, we need
7753 : : * to be able to reconstruct the row using scans of the base relations.
7754 : : * GetExistingLocalJoinPath will find a suitable path for this purpose in
7755 : : * the path list of the joinrel, if one exists. We must be careful to
7756 : : * call it before adding any ForeignPath, since the ForeignPath might
7757 : : * dominate the only suitable local path available. We also do it before
7758 : : * calling foreign_join_ok(), since that function updates fpinfo and marks
7759 : : * it as pushable if the join is found to be pushable.
7760 : : */
7761 [ + + ]: 450 : if (root->parse->commandType == CMD_DELETE ||
7762 [ + + ]: 436 : root->parse->commandType == CMD_UPDATE ||
7763 [ + + ]: 407 : root->rowMarks)
7764 : : {
7765 : 81 : epq_path = GetExistingLocalJoinPath(joinrel);
7766 [ - + ]: 81 : if (!epq_path)
7767 : : {
7768 [ # # ]: 0 : elog(DEBUG3, "could not push down foreign join because a local path suitable for EPQ checks was not found");
7769 : 0 : return;
7770 : : }
7771 : : }
7772 : : else
7773 : 369 : epq_path = NULL;
7774 : :
7775 [ + + ]: 450 : if (!foreign_join_ok(root, joinrel, jointype, outerrel, innerrel, extra))
7776 : : {
7777 : : /* Free path required for EPQ if we copied one; we don't need it now */
7778 [ + + ]: 69 : if (epq_path)
7779 : 2 : pfree(epq_path);
7780 : 69 : return;
7781 : : }
7782 : :
7783 : : /*
7784 : : * Compute the selectivity and cost of the local_conds, so we don't have
7785 : : * to do it over again for each path. The best we can do for these
7786 : : * conditions is to estimate selectivity on the basis of local statistics.
7787 : : * The local conditions are applied after the join has been computed on
7788 : : * the remote side like quals in WHERE clause, so pass jointype as
7789 : : * JOIN_INNER.
7790 : : */
7791 : 381 : fpinfo->local_conds_sel = clauselist_selectivity(root,
7792 : : fpinfo->local_conds,
7793 : : 0,
7794 : : JOIN_INNER,
7795 : : NULL);
7796 : 381 : cost_qual_eval(&fpinfo->local_conds_cost, fpinfo->local_conds, root);
7797 : :
7798 : : /*
7799 : : * If we are going to estimate costs locally, estimate the join clause
7800 : : * selectivity here while we have special join info.
7801 : : */
7802 [ + + ]: 381 : if (!fpinfo->use_remote_estimate)
7803 : 154 : fpinfo->joinclause_sel = clauselist_selectivity(root, fpinfo->joinclauses,
7804 : : 0, fpinfo->jointype,
7805 : : extra->sjinfo);
7806 : :
7807 : : /* Estimate costs for bare join relation */
7808 : 381 : estimate_path_cost_size(root, joinrel, NIL, NIL, NULL,
7809 : : &rows, &width, &disabled_nodes,
7810 : : &startup_cost, &total_cost);
7811 : : /* Now update this information in the joinrel */
7812 : 381 : joinrel->rows = rows;
7813 : 381 : joinrel->reltarget->width = width;
7814 : 381 : fpinfo->rows = rows;
7815 : 381 : fpinfo->width = width;
7816 : 381 : fpinfo->disabled_nodes = disabled_nodes;
7817 : 381 : fpinfo->startup_cost = startup_cost;
7818 : 381 : fpinfo->total_cost = total_cost;
7819 : :
7820 : : /*
7821 : : * Create a new join path and add it to the joinrel which represents a
7822 : : * join between foreign tables.
7823 : : */
7824 : 381 : joinpath = create_foreign_join_path(root,
7825 : : joinrel,
7826 : : NULL, /* default pathtarget */
7827 : : rows,
7828 : : disabled_nodes,
7829 : : startup_cost,
7830 : : total_cost,
7831 : : NIL, /* no pathkeys */
7832 : : joinrel->lateral_relids,
7833 : : epq_path,
7834 : : extra->restrictlist,
7835 : : NIL); /* no fdw_private */
7836 : :
7837 : : /* Add generated path into joinrel by add_path(). */
7838 : 381 : add_path(joinrel, (Path *) joinpath);
7839 : :
7840 : : /* Consider pathkeys for the join relation */
7841 : 381 : add_paths_with_pathkeys_for_rel(root, joinrel, epq_path,
7842 : : extra->restrictlist);
7843 : :
7844 : : /* XXX Consider parameterized paths for the join relation */
7845 : : }
7846 : :
7847 : : /*
7848 : : * Assess whether the aggregation, grouping and having operations can be pushed
7849 : : * down to the foreign server. As a side effect, save information we obtain in
7850 : : * this function to PgFdwRelationInfo of the input relation.
7851 : : */
7852 : : static bool
7853 : 165 : foreign_grouping_ok(PlannerInfo *root, RelOptInfo *grouped_rel,
7854 : : Node *havingQual)
7855 : : {
7856 : 165 : Query *query = root->parse;
7857 : 165 : PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) grouped_rel->fdw_private;
7858 : 165 : PathTarget *grouping_target = grouped_rel->reltarget;
7859 : : PgFdwRelationInfo *ofpinfo;
7860 : : ListCell *lc;
7861 : : int i;
7862 : 165 : List *tlist = NIL;
7863 : :
7864 : : /* We currently don't support pushing Grouping Sets. */
7865 [ + + ]: 165 : if (query->groupingSets)
7866 : 6 : return false;
7867 : :
7868 : : /* Get the fpinfo of the underlying scan relation. */
7869 : 159 : ofpinfo = (PgFdwRelationInfo *) fpinfo->outerrel->fdw_private;
7870 : :
7871 : : /*
7872 : : * If underlying scan relation has any local conditions, those conditions
7873 : : * are required to be applied before performing aggregation. Hence the
7874 : : * aggregate cannot be pushed down.
7875 : : */
7876 [ + + ]: 159 : if (ofpinfo->local_conds)
7877 : 9 : return false;
7878 : :
7879 : : /*
7880 : : * Examine grouping expressions, as well as other expressions we'd need to
7881 : : * compute, and check whether they are safe to push down to the foreign
7882 : : * server. All GROUP BY expressions will be part of the grouping target
7883 : : * and thus there is no need to search for them separately. Add grouping
7884 : : * expressions into target list which will be passed to foreign server.
7885 : : *
7886 : : * A tricky fine point is that we must not put any expression into the
7887 : : * target list that is just a foreign param (that is, something that
7888 : : * deparse.c would conclude has to be sent to the foreign server). If we
7889 : : * do, the expression will also appear in the fdw_exprs list of the plan
7890 : : * node, and setrefs.c will get confused and decide that the fdw_exprs
7891 : : * entry is actually a reference to the fdw_scan_tlist entry, resulting in
7892 : : * a broken plan. Somewhat oddly, it's OK if the expression contains such
7893 : : * a node, as long as it's not at top level; then no match is possible.
7894 : : */
7895 : 150 : i = 0;
7896 [ + - + + : 437 : foreach(lc, grouping_target->exprs)
+ + ]
7897 : : {
7898 : 305 : Expr *expr = (Expr *) lfirst(lc);
7899 [ + - ]: 305 : Index sgref = get_pathtarget_sortgroupref(grouping_target, i);
7900 : : ListCell *l;
7901 : :
7902 : : /*
7903 : : * Check whether this expression is part of GROUP BY clause. Note we
7904 : : * check the whole GROUP BY clause not just processed_groupClause,
7905 : : * because we will ship all of it, cf. appendGroupByClause.
7906 : : */
7907 [ + + + + ]: 305 : if (sgref && get_sortgroupref_clause_noerr(sgref, query->groupClause))
7908 : 94 : {
7909 : : TargetEntry *tle;
7910 : :
7911 : : /*
7912 : : * If any GROUP BY expression is not shippable, then we cannot
7913 : : * push down aggregation to the foreign server.
7914 : : */
7915 [ + + ]: 97 : if (!is_foreign_expr(root, grouped_rel, fpinfo, expr))
7916 : 18 : return false;
7917 : :
7918 : : /*
7919 : : * If it would be a foreign param, we can't put it into the tlist,
7920 : : * so we have to fail.
7921 : : */
7922 [ + + ]: 96 : if (is_foreign_param(root, grouped_rel, expr))
7923 : 2 : return false;
7924 : :
7925 : : /*
7926 : : * Pushable, so add to tlist. We need to create a TLE for this
7927 : : * expression and apply the sortgroupref to it. We cannot use
7928 : : * add_to_flat_tlist() here because that avoids making duplicate
7929 : : * entries in the tlist. If there are duplicate entries with
7930 : : * distinct sortgrouprefs, we have to duplicate that situation in
7931 : : * the output tlist.
7932 : : */
7933 : 94 : tle = makeTargetEntry(expr, list_length(tlist) + 1, NULL, false);
7934 : 94 : tle->ressortgroupref = sgref;
7935 : 94 : tlist = lappend(tlist, tle);
7936 : : }
7937 : : else
7938 : : {
7939 : : /*
7940 : : * Non-grouping expression we need to compute. Can we ship it
7941 : : * as-is to the foreign server?
7942 : : */
7943 [ + + ]: 208 : if (is_foreign_expr(root, grouped_rel, fpinfo, expr) &&
7944 [ + + ]: 187 : !is_foreign_param(root, grouped_rel, expr))
7945 : : {
7946 : : /* Yes, so add to tlist as-is; OK to suppress duplicates */
7947 : 185 : tlist = add_to_flat_tlist(tlist, list_make1(expr));
7948 : : }
7949 : : else
7950 : : {
7951 : : /* Not pushable as a whole; extract its Vars and aggregates */
7952 : : List *aggvars;
7953 : :
7954 : 23 : aggvars = pull_var_clause((Node *) expr,
7955 : : PVC_INCLUDE_AGGREGATES);
7956 : :
7957 : : /*
7958 : : * If any aggregate expression is not shippable, then we
7959 : : * cannot push down aggregation to the foreign server. (We
7960 : : * don't have to check is_foreign_param, since that certainly
7961 : : * won't return true for any such expression.)
7962 : : */
7963 [ + + ]: 23 : if (!is_foreign_expr(root, grouped_rel, fpinfo, (Expr *) aggvars))
7964 : 15 : return false;
7965 : :
7966 : : /*
7967 : : * Add aggregates, if any, into the targetlist. Plain Vars
7968 : : * outside an aggregate can be ignored, because they should be
7969 : : * either same as some GROUP BY column or part of some GROUP
7970 : : * BY expression. In either case, they are already part of
7971 : : * the targetlist and thus no need to add them again. In fact
7972 : : * including plain Vars in the tlist when they do not match a
7973 : : * GROUP BY column would cause the foreign server to complain
7974 : : * that the shipped query is invalid.
7975 : : */
7976 [ + + + + : 14 : foreach(l, aggvars)
+ + ]
7977 : : {
7978 : 6 : Expr *aggref = (Expr *) lfirst(l);
7979 : :
7980 [ + + ]: 6 : if (IsA(aggref, Aggref))
7981 : 4 : tlist = add_to_flat_tlist(tlist, list_make1(aggref));
7982 : : }
7983 : : }
7984 : : }
7985 : :
7986 : 287 : i++;
7987 : : }
7988 : :
7989 : : /*
7990 : : * Classify the pushable and non-pushable HAVING clauses and save them in
7991 : : * remote_conds and local_conds of the grouped rel's fpinfo.
7992 : : */
7993 [ + + ]: 132 : if (havingQual)
7994 : : {
7995 [ + - + + : 34 : foreach(lc, (List *) havingQual)
+ + ]
7996 : : {
7997 : 19 : Expr *expr = (Expr *) lfirst(lc);
7998 : : RestrictInfo *rinfo;
7999 : :
8000 : : /*
8001 : : * Currently, the core code doesn't wrap havingQuals in
8002 : : * RestrictInfos, so we must make our own.
8003 : : */
8004 : : Assert(!IsA(expr, RestrictInfo));
8005 : 19 : rinfo = make_restrictinfo(root,
8006 : : expr,
8007 : : true,
8008 : : false,
8009 : : false,
8010 : : false,
8011 : : root->qual_security_level,
8012 : : grouped_rel->relids,
8013 : : NULL,
8014 : : NULL);
8015 [ + + ]: 19 : if (is_foreign_expr(root, grouped_rel, fpinfo, expr))
8016 : 16 : fpinfo->remote_conds = lappend(fpinfo->remote_conds, rinfo);
8017 : : else
8018 : 3 : fpinfo->local_conds = lappend(fpinfo->local_conds, rinfo);
8019 : : }
8020 : : }
8021 : :
8022 : : /*
8023 : : * If there are any local conditions, pull Vars and aggregates from it and
8024 : : * check whether they are safe to pushdown or not.
8025 : : */
8026 [ + + ]: 132 : if (fpinfo->local_conds)
8027 : : {
8028 : 3 : List *aggvars = NIL;
8029 : :
8030 [ + - + + : 6 : foreach(lc, fpinfo->local_conds)
+ + ]
8031 : : {
8032 : 3 : RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc);
8033 : :
8034 : 3 : aggvars = list_concat(aggvars,
8035 : 3 : pull_var_clause((Node *) rinfo->clause,
8036 : : PVC_INCLUDE_AGGREGATES));
8037 : : }
8038 : :
8039 [ + - + + : 7 : foreach(lc, aggvars)
+ + ]
8040 : : {
8041 : 5 : Expr *expr = (Expr *) lfirst(lc);
8042 : :
8043 : : /*
8044 : : * If aggregates within local conditions are not safe to push
8045 : : * down, then we cannot push down the query. Vars are already
8046 : : * part of GROUP BY clause which are checked above, so no need to
8047 : : * access them again here. Again, we need not check
8048 : : * is_foreign_param for a foreign aggregate.
8049 : : */
8050 [ + - ]: 5 : if (IsA(expr, Aggref))
8051 : : {
8052 [ + + ]: 5 : if (!is_foreign_expr(root, grouped_rel, fpinfo, expr))
8053 : 1 : return false;
8054 : :
8055 : 4 : tlist = add_to_flat_tlist(tlist, list_make1(expr));
8056 : : }
8057 : : }
8058 : : }
8059 : :
8060 : : /* Store generated targetlist */
8061 : 131 : fpinfo->grouped_tlist = tlist;
8062 : :
8063 : : /* Safe to pushdown */
8064 : 131 : fpinfo->pushdown_safe = true;
8065 : :
8066 : : /*
8067 : : * Set # of retrieved rows and cached relation costs to some negative
8068 : : * value, so that we can detect when they are set to some sensible values,
8069 : : * during one (usually the first) of the calls to estimate_path_cost_size.
8070 : : */
8071 : 131 : fpinfo->retrieved_rows = -1;
8072 : 131 : fpinfo->rel_startup_cost = -1;
8073 : 131 : fpinfo->rel_total_cost = -1;
8074 : :
8075 : : /*
8076 : : * Set the string describing this grouped relation to be used in EXPLAIN
8077 : : * output of corresponding ForeignScan. Note that the decoration we add
8078 : : * to the base relation name mustn't include any digits, or it'll confuse
8079 : : * postgresExplainForeignScan.
8080 : : */
8081 : 131 : fpinfo->relation_name = psprintf("Aggregate on (%s)",
8082 : : ofpinfo->relation_name);
8083 : :
8084 : 131 : return true;
8085 : : }
8086 : :
8087 : : /*
8088 : : * postgresGetForeignUpperPaths
8089 : : * Add paths for post-join operations like aggregation, grouping etc. if
8090 : : * corresponding operations are safe to push down.
8091 : : */
8092 : : static void
8093 : 1076 : postgresGetForeignUpperPaths(PlannerInfo *root, UpperRelationKind stage,
8094 : : RelOptInfo *input_rel, RelOptInfo *output_rel,
8095 : : void *extra)
8096 : : {
8097 : : PgFdwRelationInfo *fpinfo;
8098 : :
8099 : : /*
8100 : : * If input rel is not safe to pushdown, then simply return as we cannot
8101 : : * perform any post-join operations on the foreign server.
8102 : : */
8103 [ + + ]: 1076 : if (!input_rel->fdw_private ||
8104 [ + + ]: 1006 : !((PgFdwRelationInfo *) input_rel->fdw_private)->pushdown_safe)
8105 : 136 : return;
8106 : :
8107 : : /* Ignore stages we don't support; and skip any duplicate calls. */
8108 [ + + + + ]: 940 : if ((stage != UPPERREL_GROUP_AGG &&
8109 [ + + ]: 599 : stage != UPPERREL_ORDERED &&
8110 : 921 : stage != UPPERREL_FINAL) ||
8111 [ - + ]: 921 : output_rel->fdw_private)
8112 : 19 : return;
8113 : :
8114 : 921 : fpinfo = palloc0_object(PgFdwRelationInfo);
8115 : 921 : fpinfo->pushdown_safe = false;
8116 : 921 : fpinfo->stage = stage;
8117 : 921 : output_rel->fdw_private = fpinfo;
8118 : :
8119 [ + + + - ]: 921 : switch (stage)
8120 : : {
8121 : 165 : case UPPERREL_GROUP_AGG:
8122 : 165 : add_foreign_grouping_paths(root, input_rel, output_rel,
8123 : : (GroupPathExtraData *) extra);
8124 : 165 : break;
8125 : 176 : case UPPERREL_ORDERED:
8126 : 176 : add_foreign_ordered_paths(root, input_rel, output_rel);
8127 : 176 : break;
8128 : 580 : case UPPERREL_FINAL:
8129 : 580 : add_foreign_final_paths(root, input_rel, output_rel,
8130 : : (FinalPathExtraData *) extra);
8131 : 580 : break;
8132 : 0 : default:
8133 [ # # ]: 0 : elog(ERROR, "unexpected upper relation: %d", (int) stage);
8134 : : break;
8135 : : }
8136 : : }
8137 : :
8138 : : /*
8139 : : * add_foreign_grouping_paths
8140 : : * Add foreign path for grouping and/or aggregation.
8141 : : *
8142 : : * Given input_rel represents the underlying scan. The paths are added to the
8143 : : * given grouped_rel.
8144 : : */
8145 : : static void
8146 : 165 : add_foreign_grouping_paths(PlannerInfo *root, RelOptInfo *input_rel,
8147 : : RelOptInfo *grouped_rel,
8148 : : GroupPathExtraData *extra)
8149 : : {
8150 : 165 : Query *parse = root->parse;
8151 : 165 : PgFdwRelationInfo *ifpinfo = input_rel->fdw_private;
8152 : 165 : PgFdwRelationInfo *fpinfo = grouped_rel->fdw_private;
8153 : : ForeignPath *grouppath;
8154 : : double rows;
8155 : : int width;
8156 : : int disabled_nodes;
8157 : : Cost startup_cost;
8158 : : Cost total_cost;
8159 : :
8160 : : /* Nothing to be done, if there is no grouping or aggregation required. */
8161 [ + + + - : 165 : if (!parse->groupClause && !parse->groupingSets && !parse->hasAggs &&
- + ]
8162 [ # # ]: 0 : !root->hasHavingQual)
8163 : 34 : return;
8164 : :
8165 : : Assert(extra->patype == PARTITIONWISE_AGGREGATE_NONE ||
8166 : : extra->patype == PARTITIONWISE_AGGREGATE_FULL);
8167 : :
8168 : : /* save the input_rel as outerrel in fpinfo */
8169 : 165 : fpinfo->outerrel = input_rel;
8170 : :
8171 : : /*
8172 : : * Copy foreign table, foreign server, user mapping, FDW options etc.
8173 : : * details from the input relation's fpinfo.
8174 : : */
8175 : 165 : fpinfo->table = ifpinfo->table;
8176 : 165 : fpinfo->server = ifpinfo->server;
8177 : 165 : fpinfo->user = ifpinfo->user;
8178 : 165 : merge_fdw_options(fpinfo, ifpinfo, NULL);
8179 : :
8180 : : /*
8181 : : * Assess if it is safe to push down aggregation and grouping.
8182 : : *
8183 : : * Use HAVING qual from extra. In case of child partition, it will have
8184 : : * translated Vars.
8185 : : */
8186 [ + + ]: 165 : if (!foreign_grouping_ok(root, grouped_rel, extra->havingQual))
8187 : 34 : return;
8188 : :
8189 : : /*
8190 : : * Compute the selectivity and cost of the local_conds, so we don't have
8191 : : * to do it over again for each path. (Currently we create just a single
8192 : : * path here, but in future it would be possible that we build more paths
8193 : : * such as pre-sorted paths as in postgresGetForeignPaths and
8194 : : * postgresGetForeignJoinPaths.) The best we can do for these conditions
8195 : : * is to estimate selectivity on the basis of local statistics.
8196 : : */
8197 : 131 : fpinfo->local_conds_sel = clauselist_selectivity(root,
8198 : : fpinfo->local_conds,
8199 : : 0,
8200 : : JOIN_INNER,
8201 : : NULL);
8202 : :
8203 : 131 : cost_qual_eval(&fpinfo->local_conds_cost, fpinfo->local_conds, root);
8204 : :
8205 : : /* Estimate the cost of push down */
8206 : 131 : estimate_path_cost_size(root, grouped_rel, NIL, NIL, NULL,
8207 : : &rows, &width, &disabled_nodes,
8208 : : &startup_cost, &total_cost);
8209 : :
8210 : : /* Now update this information in the fpinfo */
8211 : 131 : fpinfo->rows = rows;
8212 : 131 : fpinfo->width = width;
8213 : 131 : fpinfo->disabled_nodes = disabled_nodes;
8214 : 131 : fpinfo->startup_cost = startup_cost;
8215 : 131 : fpinfo->total_cost = total_cost;
8216 : :
8217 : : /* Create and add foreign path to the grouping relation. */
8218 : 131 : grouppath = create_foreign_upper_path(root,
8219 : : grouped_rel,
8220 : 131 : grouped_rel->reltarget,
8221 : : rows,
8222 : : disabled_nodes,
8223 : : startup_cost,
8224 : : total_cost,
8225 : : NIL, /* no pathkeys */
8226 : : NULL,
8227 : : NIL, /* no fdw_restrictinfo list */
8228 : : NIL); /* no fdw_private */
8229 : :
8230 : : /* Add generated path into grouped_rel by add_path(). */
8231 : 131 : add_path(grouped_rel, (Path *) grouppath);
8232 : : }
8233 : :
8234 : : /*
8235 : : * add_foreign_ordered_paths
8236 : : * Add foreign paths for performing the final sort remotely.
8237 : : *
8238 : : * Given input_rel contains the source-data Paths. The paths are added to the
8239 : : * given ordered_rel.
8240 : : */
8241 : : static void
8242 : 176 : add_foreign_ordered_paths(PlannerInfo *root, RelOptInfo *input_rel,
8243 : : RelOptInfo *ordered_rel)
8244 : : {
8245 : 176 : Query *parse = root->parse;
8246 : 176 : PgFdwRelationInfo *ifpinfo = input_rel->fdw_private;
8247 : 176 : PgFdwRelationInfo *fpinfo = ordered_rel->fdw_private;
8248 : : PgFdwPathExtraData *fpextra;
8249 : : double rows;
8250 : : int width;
8251 : : int disabled_nodes;
8252 : : Cost startup_cost;
8253 : : Cost total_cost;
8254 : : List *fdw_private;
8255 : : ForeignPath *ordered_path;
8256 : : ListCell *lc;
8257 : :
8258 : : /* Shouldn't get here unless the query has ORDER BY */
8259 : : Assert(parse->sortClause);
8260 : :
8261 : : /* We don't support cases where there are any SRFs in the targetlist */
8262 [ - + ]: 176 : if (parse->hasTargetSRFs)
8263 : 132 : return;
8264 : :
8265 : : /* Save the input_rel as outerrel in fpinfo */
8266 : 176 : fpinfo->outerrel = input_rel;
8267 : :
8268 : : /*
8269 : : * Copy foreign table, foreign server, user mapping, FDW options etc.
8270 : : * details from the input relation's fpinfo.
8271 : : */
8272 : 176 : fpinfo->table = ifpinfo->table;
8273 : 176 : fpinfo->server = ifpinfo->server;
8274 : 176 : fpinfo->user = ifpinfo->user;
8275 : 176 : merge_fdw_options(fpinfo, ifpinfo, NULL);
8276 : :
8277 : : /*
8278 : : * If the input_rel is a base or join relation,
8279 : : * add_paths_with_pathkeys_for_rel() already considered the creation of
8280 : : * paths to suit query_pathkeys. sort_pathkeys can be NIL here despite
8281 : : * the query having an ORDER BY clause, and query_pathkeys can be set to
8282 : : * setop_pathkeys (see standard_qp_callback()).
8283 : : */
8284 [ + + ]: 176 : if (input_rel->reloptkind == RELOPT_BASEREL ||
8285 [ + + ]: 126 : input_rel->reloptkind == RELOPT_JOINREL)
8286 : : {
8287 : : /* mark pushdown as safe when no sort is required for the ORDER BY */
8288 [ + + ]: 128 : if (root->sort_pathkeys == NIL)
8289 : 3 : fpinfo->pushdown_safe = true;
8290 : : else
8291 : : {
8292 : : Assert(root->query_pathkeys == root->sort_pathkeys);
8293 : :
8294 : : /* Safe to push down if the query_pathkeys are safe to push down */
8295 : 125 : fpinfo->pushdown_safe = ifpinfo->qp_is_pushdown_safe;
8296 : : }
8297 : :
8298 : 128 : return;
8299 : : }
8300 : :
8301 : : /* The input_rel should be a grouping relation */
8302 : : Assert(input_rel->reloptkind == RELOPT_UPPER_REL &&
8303 : : ifpinfo->stage == UPPERREL_GROUP_AGG);
8304 : :
8305 : : /*
8306 : : * We try to create a path below by extending a simple foreign path for
8307 : : * the underlying grouping relation to perform the final sort remotely,
8308 : : * which is stored into the fdw_private list of the resulting path.
8309 : : */
8310 : :
8311 : : /* Assess if it is safe to push down the final sort */
8312 [ + + + + : 98 : foreach(lc, root->sort_pathkeys)
+ + ]
8313 : : {
8314 : 54 : PathKey *pathkey = (PathKey *) lfirst(lc);
8315 : 54 : EquivalenceClass *pathkey_ec = pathkey->pk_eclass;
8316 : :
8317 : : /*
8318 : : * is_foreign_expr would detect volatile expressions as well, but
8319 : : * checking ec_has_volatile here saves some cycles.
8320 : : */
8321 [ + + ]: 54 : if (pathkey_ec->ec_has_volatile)
8322 : 4 : return;
8323 : :
8324 : : /*
8325 : : * Can't push down the sort if pathkey's opfamily is not shippable.
8326 : : */
8327 [ - + ]: 50 : if (!is_shippable(pathkey->pk_opfamily, OperatorFamilyRelationId,
8328 : : fpinfo))
8329 : 0 : return;
8330 : :
8331 : : /*
8332 : : * The EC must contain a shippable EM that is computed in input_rel's
8333 : : * reltarget, else we can't push down the sort.
8334 : : */
8335 [ - + ]: 50 : if (find_em_for_rel_target(root,
8336 : : pathkey_ec,
8337 : : input_rel) == NULL)
8338 : 0 : return;
8339 : : }
8340 : :
8341 : : /* Safe to push down */
8342 : 44 : fpinfo->pushdown_safe = true;
8343 : :
8344 : : /* Construct PgFdwPathExtraData */
8345 : 44 : fpextra = palloc0_object(PgFdwPathExtraData);
8346 : 44 : fpextra->target = root->upper_targets[UPPERREL_ORDERED];
8347 : 44 : fpextra->has_final_sort = true;
8348 : :
8349 : : /* Estimate the costs of performing the final sort remotely */
8350 : 44 : estimate_path_cost_size(root, input_rel, NIL, root->sort_pathkeys, fpextra,
8351 : : &rows, &width, &disabled_nodes,
8352 : : &startup_cost, &total_cost);
8353 : :
8354 : : /*
8355 : : * Build the fdw_private list that will be used by postgresGetForeignPlan.
8356 : : * Items in the list must match order in enum FdwPathPrivateIndex.
8357 : : */
8358 : 44 : fdw_private = list_make2(makeBoolean(true), makeBoolean(false));
8359 : :
8360 : : /* Create foreign ordering path */
8361 : 44 : ordered_path = create_foreign_upper_path(root,
8362 : : input_rel,
8363 : 44 : root->upper_targets[UPPERREL_ORDERED],
8364 : : rows,
8365 : : disabled_nodes,
8366 : : startup_cost,
8367 : : total_cost,
8368 : : root->sort_pathkeys,
8369 : : NULL, /* no extra plan */
8370 : : NIL, /* no fdw_restrictinfo
8371 : : * list */
8372 : : fdw_private);
8373 : :
8374 : : /* and add it to the ordered_rel */
8375 : 44 : add_path(ordered_rel, (Path *) ordered_path);
8376 : : }
8377 : :
8378 : : /*
8379 : : * add_foreign_final_paths
8380 : : * Add foreign paths for performing the final processing remotely.
8381 : : *
8382 : : * Given input_rel contains the source-data Paths. The paths are added to the
8383 : : * given final_rel.
8384 : : */
8385 : : static void
8386 : 580 : add_foreign_final_paths(PlannerInfo *root, RelOptInfo *input_rel,
8387 : : RelOptInfo *final_rel,
8388 : : FinalPathExtraData *extra)
8389 : : {
8390 : 580 : Query *parse = root->parse;
8391 : 580 : PgFdwRelationInfo *ifpinfo = (PgFdwRelationInfo *) input_rel->fdw_private;
8392 : 580 : PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) final_rel->fdw_private;
8393 : 580 : bool has_final_sort = false;
8394 : 580 : List *pathkeys = NIL;
8395 : : PgFdwPathExtraData *fpextra;
8396 : 580 : bool save_use_remote_estimate = false;
8397 : : double rows;
8398 : : int width;
8399 : : int disabled_nodes;
8400 : : Cost startup_cost;
8401 : : Cost total_cost;
8402 : : List *fdw_private;
8403 : : ForeignPath *final_path;
8404 : :
8405 : : /*
8406 : : * Currently, we only support this for SELECT commands
8407 : : */
8408 [ + + ]: 580 : if (parse->commandType != CMD_SELECT)
8409 : 454 : return;
8410 : :
8411 : : /*
8412 : : * No work if there is no FOR UPDATE/SHARE clause and if there is no need
8413 : : * to add a LIMIT node
8414 : : */
8415 [ + + + + ]: 464 : if (!parse->rowMarks && !extra->limit_needed)
8416 : 324 : return;
8417 : :
8418 : : /* We don't support cases where there are any SRFs in the targetlist */
8419 [ - + ]: 140 : if (parse->hasTargetSRFs)
8420 : 0 : return;
8421 : :
8422 : : /* Save the input_rel as outerrel in fpinfo */
8423 : 140 : fpinfo->outerrel = input_rel;
8424 : :
8425 : : /*
8426 : : * Copy foreign table, foreign server, user mapping, FDW options etc.
8427 : : * details from the input relation's fpinfo.
8428 : : */
8429 : 140 : fpinfo->table = ifpinfo->table;
8430 : 140 : fpinfo->server = ifpinfo->server;
8431 : 140 : fpinfo->user = ifpinfo->user;
8432 : 140 : merge_fdw_options(fpinfo, ifpinfo, NULL);
8433 : :
8434 : : /*
8435 : : * If there is no need to add a LIMIT node, there might be a ForeignPath
8436 : : * in the input_rel's pathlist that implements all behavior of the query.
8437 : : * Note: we would already have accounted for the query's FOR UPDATE/SHARE
8438 : : * (if any) before we get here.
8439 : : */
8440 [ + + ]: 140 : if (!extra->limit_needed)
8441 : : {
8442 : : ListCell *lc;
8443 : :
8444 : : Assert(parse->rowMarks);
8445 : :
8446 : : /*
8447 : : * Grouping and aggregation are not supported with FOR UPDATE/SHARE,
8448 : : * so the input_rel should be a base, join, or ordered relation; and
8449 : : * if it's an ordered relation, its input relation should be a base or
8450 : : * join relation.
8451 : : */
8452 : : Assert(input_rel->reloptkind == RELOPT_BASEREL ||
8453 : : input_rel->reloptkind == RELOPT_JOINREL ||
8454 : : (input_rel->reloptkind == RELOPT_UPPER_REL &&
8455 : : ifpinfo->stage == UPPERREL_ORDERED &&
8456 : : (ifpinfo->outerrel->reloptkind == RELOPT_BASEREL ||
8457 : : ifpinfo->outerrel->reloptkind == RELOPT_JOINREL)));
8458 : :
8459 [ + - + - : 4 : foreach(lc, input_rel->pathlist)
+ - ]
8460 : : {
8461 : 4 : Path *path = (Path *) lfirst(lc);
8462 : :
8463 : : /*
8464 : : * apply_scanjoin_target_to_paths() uses create_projection_path()
8465 : : * to adjust each of its input paths if needed, whereas
8466 : : * create_ordered_paths() uses apply_projection_to_path() to do
8467 : : * that. So the former might have put a ProjectionPath on top of
8468 : : * the ForeignPath; look through ProjectionPath and see if the
8469 : : * path underneath it is ForeignPath.
8470 : : */
8471 [ - + ]: 4 : if (IsA(path, ForeignPath) ||
8472 [ # # ]: 0 : (IsA(path, ProjectionPath) &&
8473 [ # # ]: 0 : IsA(((ProjectionPath *) path)->subpath, ForeignPath)))
8474 : : {
8475 : : /*
8476 : : * Create foreign final path; this gets rid of a
8477 : : * no-longer-needed outer plan (if any), which makes the
8478 : : * EXPLAIN output look cleaner
8479 : : */
8480 : 4 : final_path = create_foreign_upper_path(root,
8481 : : path->parent,
8482 : : path->pathtarget,
8483 : : path->rows,
8484 : : path->disabled_nodes,
8485 : : path->startup_cost,
8486 : : path->total_cost,
8487 : : path->pathkeys,
8488 : : NULL, /* no extra plan */
8489 : : NIL, /* no fdw_restrictinfo
8490 : : * list */
8491 : : NIL); /* no fdw_private */
8492 : :
8493 : : /* and add it to the final_rel */
8494 : 4 : add_path(final_rel, (Path *) final_path);
8495 : :
8496 : : /* Safe to push down */
8497 : 4 : fpinfo->pushdown_safe = true;
8498 : :
8499 : 4 : return;
8500 : : }
8501 : : }
8502 : :
8503 : : /*
8504 : : * If we get here it means no ForeignPaths; since we would already
8505 : : * have considered pushing down all operations for the query to the
8506 : : * remote server, give up on it.
8507 : : */
8508 : 0 : return;
8509 : : }
8510 : :
8511 : : Assert(extra->limit_needed);
8512 : :
8513 : : /*
8514 : : * If the input_rel is an ordered relation, replace the input_rel with its
8515 : : * input relation
8516 : : */
8517 [ + + ]: 136 : if (input_rel->reloptkind == RELOPT_UPPER_REL &&
8518 [ + - ]: 78 : ifpinfo->stage == UPPERREL_ORDERED)
8519 : : {
8520 : 78 : input_rel = ifpinfo->outerrel;
8521 : 78 : ifpinfo = (PgFdwRelationInfo *) input_rel->fdw_private;
8522 : 78 : has_final_sort = true;
8523 : 78 : pathkeys = root->sort_pathkeys;
8524 : : }
8525 : :
8526 : : /* The input_rel should be a base, join, or grouping relation */
8527 : : Assert(input_rel->reloptkind == RELOPT_BASEREL ||
8528 : : input_rel->reloptkind == RELOPT_JOINREL ||
8529 : : (input_rel->reloptkind == RELOPT_UPPER_REL &&
8530 : : ifpinfo->stage == UPPERREL_GROUP_AGG));
8531 : :
8532 : : /*
8533 : : * We try to create a path below by extending a simple foreign path for
8534 : : * the underlying base, join, or grouping relation to perform the final
8535 : : * sort (if has_final_sort) and the LIMIT restriction remotely, which is
8536 : : * stored into the fdw_private list of the resulting path. (We
8537 : : * re-estimate the costs of sorting the underlying relation, if
8538 : : * has_final_sort.)
8539 : : */
8540 : :
8541 : : /*
8542 : : * Assess if it is safe to push down the LIMIT and OFFSET to the remote
8543 : : * server
8544 : : */
8545 : :
8546 : : /*
8547 : : * If the underlying relation has any local conditions, the LIMIT/OFFSET
8548 : : * cannot be pushed down.
8549 : : */
8550 [ + + ]: 136 : if (ifpinfo->local_conds)
8551 : 8 : return;
8552 : :
8553 : : /*
8554 : : * If the query has FETCH FIRST .. WITH TIES, 1) it must have ORDER BY as
8555 : : * well, which is used to determine which additional rows tie for the last
8556 : : * place in the result set, and 2) ORDER BY must already have been
8557 : : * determined to be safe to push down before we get here. So in that case
8558 : : * the FETCH clause is safe to push down with ORDER BY if the remote
8559 : : * server is v13 or later, but if not, the remote query will fail entirely
8560 : : * for lack of support for it. Since we do not currently have a way to do
8561 : : * a remote-version check (without accessing the remote server), disable
8562 : : * pushing the FETCH clause for now.
8563 : : */
8564 [ + + ]: 128 : if (parse->limitOption == LIMIT_OPTION_WITH_TIES)
8565 : 2 : return;
8566 : :
8567 : : /*
8568 : : * Also, the LIMIT/OFFSET cannot be pushed down, if their expressions are
8569 : : * not safe to remote.
8570 : : */
8571 [ + - ]: 126 : if (!is_foreign_expr(root, input_rel, ifpinfo, (Expr *) parse->limitOffset) ||
8572 [ - + ]: 126 : !is_foreign_expr(root, input_rel, ifpinfo, (Expr *) parse->limitCount))
8573 : 0 : return;
8574 : :
8575 : : /* Safe to push down */
8576 : 126 : fpinfo->pushdown_safe = true;
8577 : :
8578 : : /* Construct PgFdwPathExtraData */
8579 : 126 : fpextra = palloc0_object(PgFdwPathExtraData);
8580 : 126 : fpextra->target = root->upper_targets[UPPERREL_FINAL];
8581 : 126 : fpextra->has_final_sort = has_final_sort;
8582 : 126 : fpextra->has_limit = extra->limit_needed;
8583 : 126 : fpextra->limit_tuples = extra->limit_tuples;
8584 : 126 : fpextra->count_est = extra->count_est;
8585 : 126 : fpextra->offset_est = extra->offset_est;
8586 : :
8587 : : /*
8588 : : * Estimate the costs of performing the final sort and the LIMIT
8589 : : * restriction remotely. If has_final_sort is false, we wouldn't need to
8590 : : * execute EXPLAIN anymore if use_remote_estimate, since the costs can be
8591 : : * roughly estimated using the costs we already have for the underlying
8592 : : * relation, in the same way as when use_remote_estimate is false. Since
8593 : : * it's pretty expensive to execute EXPLAIN, force use_remote_estimate to
8594 : : * false in that case.
8595 : : */
8596 [ + + ]: 126 : if (!fpextra->has_final_sort)
8597 : : {
8598 : 55 : save_use_remote_estimate = ifpinfo->use_remote_estimate;
8599 : 55 : ifpinfo->use_remote_estimate = false;
8600 : : }
8601 : 126 : estimate_path_cost_size(root, input_rel, NIL, pathkeys, fpextra,
8602 : : &rows, &width, &disabled_nodes,
8603 : : &startup_cost, &total_cost);
8604 [ + + ]: 126 : if (!fpextra->has_final_sort)
8605 : 55 : ifpinfo->use_remote_estimate = save_use_remote_estimate;
8606 : :
8607 : : /*
8608 : : * Build the fdw_private list that will be used by postgresGetForeignPlan.
8609 : : * Items in the list must match order in enum FdwPathPrivateIndex.
8610 : : */
8611 : 126 : fdw_private = list_make2(makeBoolean(has_final_sort),
8612 : : makeBoolean(extra->limit_needed));
8613 : :
8614 : : /*
8615 : : * Create foreign final path; this gets rid of a no-longer-needed outer
8616 : : * plan (if any), which makes the EXPLAIN output look cleaner
8617 : : */
8618 : 126 : final_path = create_foreign_upper_path(root,
8619 : : input_rel,
8620 : 126 : root->upper_targets[UPPERREL_FINAL],
8621 : : rows,
8622 : : disabled_nodes,
8623 : : startup_cost,
8624 : : total_cost,
8625 : : pathkeys,
8626 : : NULL, /* no extra plan */
8627 : : NIL, /* no fdw_restrictinfo list */
8628 : : fdw_private);
8629 : :
8630 : : /* and add it to the final_rel */
8631 : 126 : add_path(final_rel, (Path *) final_path);
8632 : : }
8633 : :
8634 : : /*
8635 : : * postgresIsForeignPathAsyncCapable
8636 : : * Check whether a given ForeignPath node is async-capable.
8637 : : */
8638 : : static bool
8639 : 312 : postgresIsForeignPathAsyncCapable(ForeignPath *path)
8640 : : {
8641 : 312 : RelOptInfo *rel = ((Path *) path)->parent;
8642 : 312 : PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) rel->fdw_private;
8643 : :
8644 : 312 : return fpinfo->async_capable;
8645 : : }
8646 : :
8647 : : /*
8648 : : * postgresForeignAsyncRequest
8649 : : * Asynchronously request next tuple from a foreign PostgreSQL table.
8650 : : */
8651 : : static void
8652 : 7876 : postgresForeignAsyncRequest(AsyncRequest *areq)
8653 : : {
8654 : 7876 : produce_tuple_asynchronously(areq, true);
8655 : 7876 : }
8656 : :
8657 : : /*
8658 : : * postgresForeignAsyncConfigureWait
8659 : : * Configure a file descriptor event for which we wish to wait.
8660 : : */
8661 : : static void
8662 : 309 : postgresForeignAsyncConfigureWait(AsyncRequest *areq)
8663 : : {
8664 : 309 : ForeignScanState *node = (ForeignScanState *) areq->requestee;
8665 : 309 : PgFdwScanState *fsstate = (PgFdwScanState *) node->fdw_state;
8666 : 309 : AsyncRequest *pendingAreq = fsstate->conn_state->pendingAreq;
8667 : 309 : PlanState *requestor = areq->requestor;
8668 : 309 : WaitEventSet *set = ExecAsyncGetRequestorEventSet(requestor);
8669 : :
8670 : : /* This should not be called unless callback_pending */
8671 : : Assert(areq->callback_pending);
8672 : : /* The requestor should be an Append or MergeAppend node */
8673 : : Assert(IsA(requestor, AppendState) || IsA(requestor, MergeAppendState));
8674 : :
8675 : : /*
8676 : : * If process_pending_request() has been invoked on the given request
8677 : : * before we get here, we might have some tuples already; in which case
8678 : : * complete the request
8679 : : */
8680 [ + + ]: 309 : if (fsstate->next_tuple < fsstate->num_tuples)
8681 : : {
8682 : 5 : complete_pending_request(areq);
8683 [ + + ]: 5 : if (areq->request_complete)
8684 : 3 : return;
8685 : : Assert(areq->callback_pending);
8686 : : }
8687 : :
8688 : : /* We must have run out of tuples */
8689 : : Assert(fsstate->next_tuple >= fsstate->num_tuples);
8690 : :
8691 : : /* The core code would have registered postmaster death event */
8692 : : Assert(GetNumRegisteredWaitEvents(set) >= 1);
8693 : :
8694 : : /* Begin an asynchronous data fetch if appropriate */
8695 [ + + ]: 306 : if (!pendingAreq)
8696 : 9 : fetch_more_data_begin(areq);
8697 [ + + ]: 297 : else if (pendingAreq->requestor != requestor)
8698 : : {
8699 : : /*
8700 : : * This is the case when an asynchronous request made by another
8701 : : * requestor is currently in-progress. If our requestor is an Append,
8702 : : * consider skipping configuration of the file descriptor event to
8703 : : * improve concurrency. If it's a MergeAppend, it cannot make
8704 : : * progress unless the given request returns a result; in which case
8705 : : * configure the file descriptor event below.
8706 : : */
8707 [ + - ]: 8 : if (IsA(requestor, AppendState))
8708 : : {
8709 : : /*
8710 : : * If the Append node already has results that are ready for new
8711 : : * requests or it has already configured file descriptor events
8712 : : * for other subplans, skip the configuration.
8713 : : */
8714 [ - + ]: 8 : if (!bms_is_empty(((AppendState *) requestor)->as_needrequest))
8715 : 0 : return;
8716 [ + + ]: 8 : if (GetNumRegisteredWaitEvents(set) > 1)
8717 : 6 : return;
8718 : : }
8719 : :
8720 : : /*
8721 : : * Otherwise, process the in-progress request, begin an asynchronous
8722 : : * data fetch for the given request, and configure the file descriptor
8723 : : * event below.
8724 : : */
8725 : 2 : process_pending_request(pendingAreq);
8726 : 2 : fetch_more_data_begin(areq);
8727 : : }
8728 [ + + ]: 289 : else if (pendingAreq->requestee != areq->requestee)
8729 : : {
8730 : : /*
8731 : : * This is the case when an asynchronous request made by the requestor
8732 : : * for another subplan is currently in-progress. Skip the
8733 : : * configuration even in the MergeAppend case; in that case just defer
8734 : : * the configuration until the caller drains the request(s) for
8735 : : * preceding subplan(s).
8736 : : */
8737 : 15 : return;
8738 : : }
8739 : : else
8740 : : Assert(pendingAreq == areq);
8741 : :
8742 : 283 : AddWaitEventToSet(set, WL_SOCKET_READABLE, PQsocket(fsstate->conn),
8743 : : NULL, areq);
8744 : : }
8745 : :
8746 : : /*
8747 : : * postgresForeignAsyncNotify
8748 : : * Fetch some more tuples from a file descriptor that becomes ready,
8749 : : * requesting next tuple.
8750 : : */
8751 : : static void
8752 : 218 : postgresForeignAsyncNotify(AsyncRequest *areq)
8753 : : {
8754 : 218 : ForeignScanState *node = (ForeignScanState *) areq->requestee;
8755 : 218 : PgFdwScanState *fsstate = (PgFdwScanState *) node->fdw_state;
8756 : :
8757 : : /* The core code would have initialized the callback_pending flag */
8758 : : Assert(!areq->callback_pending);
8759 : :
8760 : : /*
8761 : : * If process_pending_request() has been invoked on the given request
8762 : : * before we get here, we might have some tuples already; in which case
8763 : : * produce the next tuple
8764 : : */
8765 [ - + ]: 218 : if (fsstate->next_tuple < fsstate->num_tuples)
8766 : : {
8767 : 0 : produce_tuple_asynchronously(areq, true);
8768 : 0 : return;
8769 : : }
8770 : :
8771 : : /* We must have run out of tuples */
8772 : : Assert(fsstate->next_tuple >= fsstate->num_tuples);
8773 : :
8774 : : /* The request should be currently in-process */
8775 : : Assert(fsstate->conn_state->pendingAreq == areq);
8776 : :
8777 : : /* On error, report the original query, not the FETCH. */
8778 [ - + ]: 218 : if (!PQconsumeInput(fsstate->conn))
8779 : 0 : pgfdw_report_error(NULL, fsstate->conn, fsstate->query);
8780 : :
8781 : 218 : fetch_more_data(node);
8782 : :
8783 : 218 : produce_tuple_asynchronously(areq, true);
8784 : : }
8785 : :
8786 : : /*
8787 : : * Asynchronously produce next tuple from a foreign PostgreSQL table.
8788 : : */
8789 : : static void
8790 : 8099 : produce_tuple_asynchronously(AsyncRequest *areq, bool fetch)
8791 : : {
8792 : 8099 : ForeignScanState *node = (ForeignScanState *) areq->requestee;
8793 : 8099 : PgFdwScanState *fsstate = (PgFdwScanState *) node->fdw_state;
8794 : 8099 : AsyncRequest *pendingAreq = fsstate->conn_state->pendingAreq;
8795 : : TupleTableSlot *result;
8796 : :
8797 : : /* This should not be called if the request is currently in-process */
8798 : : Assert(areq != pendingAreq);
8799 : :
8800 : : /* Fetch some more tuples, if we've run out */
8801 [ + + ]: 8099 : if (fsstate->next_tuple >= fsstate->num_tuples)
8802 : : {
8803 : : /* No point in another fetch if we already detected EOF, though */
8804 [ + + ]: 263 : if (!fsstate->eof_reached)
8805 : : {
8806 : : /* Mark the request as pending for a callback */
8807 : 183 : ExecAsyncRequestPending(areq);
8808 : : /* Begin another fetch if requested and if no pending request */
8809 [ + - + + ]: 183 : if (fetch && !pendingAreq)
8810 : 174 : fetch_more_data_begin(areq);
8811 : : }
8812 : : else
8813 : : {
8814 : : /* There's nothing more to do; just return a NULL pointer */
8815 : 80 : result = NULL;
8816 : : /* Mark the request as complete */
8817 : 80 : ExecAsyncRequestDone(areq, result);
8818 : : }
8819 : 263 : return;
8820 : : }
8821 : :
8822 : : /* Get a tuple from the ForeignScan node */
8823 : 7836 : result = areq->requestee->ExecProcNodeReal(areq->requestee);
8824 [ + - + + ]: 7836 : if (!TupIsNull(result))
8825 : : {
8826 : : /* Mark the request as complete */
8827 : 7788 : ExecAsyncRequestDone(areq, result);
8828 : 7788 : return;
8829 : : }
8830 : :
8831 : : /* We must have run out of tuples */
8832 : : Assert(fsstate->next_tuple >= fsstate->num_tuples);
8833 : :
8834 : : /* Fetch some more tuples, if we've not detected EOF yet */
8835 [ + - ]: 48 : if (!fsstate->eof_reached)
8836 : : {
8837 : : /* Mark the request as pending for a callback */
8838 : 48 : ExecAsyncRequestPending(areq);
8839 : : /* Begin another fetch if requested and if no pending request */
8840 [ + + + - ]: 48 : if (fetch && !pendingAreq)
8841 : 46 : fetch_more_data_begin(areq);
8842 : : }
8843 : : else
8844 : : {
8845 : : /* There's nothing more to do; just return a NULL pointer */
8846 : 0 : result = NULL;
8847 : : /* Mark the request as complete */
8848 : 0 : ExecAsyncRequestDone(areq, result);
8849 : : }
8850 : : }
8851 : :
8852 : : /*
8853 : : * Begin an asynchronous data fetch.
8854 : : *
8855 : : * Note: this function assumes there is no currently-in-progress asynchronous
8856 : : * data fetch.
8857 : : *
8858 : : * Note: fetch_more_data must be called to fetch the result.
8859 : : */
8860 : : static void
8861 : 231 : fetch_more_data_begin(AsyncRequest *areq)
8862 : : {
8863 : 231 : ForeignScanState *node = (ForeignScanState *) areq->requestee;
8864 : 231 : PgFdwScanState *fsstate = (PgFdwScanState *) node->fdw_state;
8865 : : char sql[64];
8866 : :
8867 : : Assert(!fsstate->conn_state->pendingAreq);
8868 : :
8869 : : /* Create the cursor synchronously. */
8870 [ + + ]: 231 : if (!fsstate->cursor_exists)
8871 : 107 : create_cursor(node);
8872 : :
8873 : : /* We will send this query, but not wait for the response. */
8874 : 229 : snprintf(sql, sizeof(sql), "FETCH %d FROM c%u",
8875 : : fsstate->fetch_size, fsstate->cursor_number);
8876 : :
8877 [ - + ]: 229 : if (!PQsendQuery(fsstate->conn, sql))
8878 : 0 : pgfdw_report_error(NULL, fsstate->conn, fsstate->query);
8879 : :
8880 : : /* Remember that the request is in process */
8881 : 229 : fsstate->conn_state->pendingAreq = areq;
8882 : 229 : }
8883 : :
8884 : : /*
8885 : : * Process a pending asynchronous request.
8886 : : */
8887 : : void
8888 : 10 : process_pending_request(AsyncRequest *areq)
8889 : : {
8890 : 10 : ForeignScanState *node = (ForeignScanState *) areq->requestee;
8891 : 10 : PgFdwScanState *fsstate = (PgFdwScanState *) node->fdw_state;
8892 : :
8893 : : /* The request would have been pending for a callback */
8894 : : Assert(areq->callback_pending);
8895 : :
8896 : : /* The request should be currently in-process */
8897 : : Assert(fsstate->conn_state->pendingAreq == areq);
8898 : :
8899 : 10 : fetch_more_data(node);
8900 : :
8901 : : /*
8902 : : * If we didn't get any tuples, must be end of data; complete the request
8903 : : * now. Otherwise, we postpone completing the request until we are called
8904 : : * from postgresForeignAsyncConfigureWait()/postgresForeignAsyncNotify().
8905 : : */
8906 [ - + ]: 10 : if (fsstate->next_tuple >= fsstate->num_tuples)
8907 : : {
8908 : : /* Unlike AsyncNotify, we unset callback_pending ourselves */
8909 : 0 : areq->callback_pending = false;
8910 : : /* Mark the request as complete */
8911 : 0 : ExecAsyncRequestDone(areq, NULL);
8912 : : /* Unlike AsyncNotify, we call ExecAsyncResponse ourselves */
8913 : 0 : ExecAsyncResponse(areq);
8914 : : }
8915 : 10 : }
8916 : :
8917 : : /*
8918 : : * Complete a pending asynchronous request.
8919 : : */
8920 : : static void
8921 : 5 : complete_pending_request(AsyncRequest *areq)
8922 : : {
8923 : : /* The request would have been pending for a callback */
8924 : : Assert(areq->callback_pending);
8925 : :
8926 : : /* Unlike AsyncNotify, we unset callback_pending ourselves */
8927 : 5 : areq->callback_pending = false;
8928 : :
8929 : : /* We begin a fetch afterwards if necessary; don't fetch */
8930 : 5 : produce_tuple_asynchronously(areq, false);
8931 : :
8932 : : /* Unlike AsyncNotify, we call ExecAsyncResponse ourselves */
8933 : 5 : ExecAsyncResponse(areq);
8934 : :
8935 : : /* Also, we do instrumentation ourselves, if required */
8936 [ + + ]: 5 : if (areq->requestee->instrument)
8937 : 1 : InstrUpdateTupleCount(areq->requestee->instrument,
8938 [ + - - + ]: 1 : TupIsNull(areq->result) ? 0.0 : 1.0);
8939 : 5 : }
8940 : :
8941 : : /*
8942 : : * Create a tuple from the specified row of the PGresult.
8943 : : *
8944 : : * rel is the local representation of the foreign table, attinmeta is
8945 : : * conversion data for the rel's tupdesc, and retrieved_attrs is an
8946 : : * integer list of the table column numbers present in the PGresult.
8947 : : * fsstate is the ForeignScan plan node's execution state.
8948 : : * temp_context is a working context that can be reset after each tuple.
8949 : : *
8950 : : * Note: either rel or fsstate, but not both, can be NULL. rel is NULL
8951 : : * if we're processing a remote join, while fsstate is NULL in a non-query
8952 : : * context such as ANALYZE, or if we're processing a non-scan query node.
8953 : : */
8954 : : static HeapTuple
8955 : 100659 : make_tuple_from_result_row(PGresult *res,
8956 : : int row,
8957 : : Relation rel,
8958 : : AttInMetadata *attinmeta,
8959 : : List *retrieved_attrs,
8960 : : ForeignScanState *fsstate,
8961 : : MemoryContext temp_context)
8962 : : {
8963 : : HeapTuple tuple;
8964 : : TupleDesc tupdesc;
8965 : : Datum *values;
8966 : : bool *nulls;
8967 : 100659 : ItemPointer ctid = NULL;
8968 : : ConversionLocation errpos;
8969 : : ErrorContextCallback errcallback;
8970 : : MemoryContext oldcontext;
8971 : : ListCell *lc;
8972 : : int j;
8973 : :
8974 : : Assert(row < PQntuples(res));
8975 : :
8976 : : /*
8977 : : * Do the following work in a temp context that we reset after each tuple.
8978 : : * This cleans up not only the data we have direct access to, but any
8979 : : * cruft the I/O functions might leak.
8980 : : */
8981 : 100659 : oldcontext = MemoryContextSwitchTo(temp_context);
8982 : :
8983 : : /*
8984 : : * Get the tuple descriptor for the row. Use the rel's tupdesc if rel is
8985 : : * provided, otherwise look to the scan node's ScanTupleSlot.
8986 : : */
8987 [ + + ]: 100659 : if (rel)
8988 : 64323 : tupdesc = RelationGetDescr(rel);
8989 : : else
8990 : : {
8991 : : Assert(fsstate);
8992 : 36336 : tupdesc = fsstate->ss.ss_ScanTupleSlot->tts_tupleDescriptor;
8993 : : }
8994 : :
8995 : 100659 : values = palloc0_array(Datum, tupdesc->natts);
8996 : 100659 : nulls = palloc_array(bool, tupdesc->natts);
8997 : : /* Initialize to nulls for any columns not present in result */
8998 : 100659 : memset(nulls, true, tupdesc->natts * sizeof(bool));
8999 : :
9000 : : /*
9001 : : * Set up and install callback to report where conversion error occurs.
9002 : : */
9003 : 100659 : errpos.cur_attno = 0;
9004 : 100659 : errpos.rel = rel;
9005 : 100659 : errpos.fsstate = fsstate;
9006 : 100659 : errcallback.callback = conversion_error_callback;
9007 : 100659 : errcallback.arg = &errpos;
9008 : 100659 : errcallback.previous = error_context_stack;
9009 : 100659 : error_context_stack = &errcallback;
9010 : :
9011 : : /*
9012 : : * i indexes columns in the relation, j indexes columns in the PGresult.
9013 : : */
9014 : 100659 : j = 0;
9015 [ + + + + : 381862 : foreach(lc, retrieved_attrs)
+ + ]
9016 : : {
9017 : 281208 : int i = lfirst_int(lc);
9018 : : const char *valstr;
9019 : :
9020 : : /* fetch next column's textual value */
9021 [ + + ]: 281208 : if (PQgetisnull(res, row, j))
9022 : 11346 : valstr = NULL;
9023 : : else
9024 : 269862 : valstr = PQgetvalue(res, row, j);
9025 : :
9026 : : /*
9027 : : * convert value to internal representation
9028 : : *
9029 : : * Note: we ignore system columns other than ctid and oid in result
9030 : : */
9031 : 281208 : errpos.cur_attno = i;
9032 [ + + ]: 281208 : if (i > 0)
9033 : : {
9034 : : /* ordinary column */
9035 : : Assert(i <= tupdesc->natts);
9036 : 278090 : nulls[i - 1] = (valstr == NULL);
9037 : : /* Apply the input function even to nulls, to support domains */
9038 : 278085 : values[i - 1] = InputFunctionCall(&attinmeta->attinfuncs[i - 1],
9039 : : valstr,
9040 : 278090 : attinmeta->attioparams[i - 1],
9041 : 278090 : attinmeta->atttypmods[i - 1]);
9042 : : }
9043 [ + - ]: 3118 : else if (i == SelfItemPointerAttributeNumber)
9044 : : {
9045 : : /* ctid */
9046 [ + - ]: 3118 : if (valstr != NULL)
9047 : : {
9048 : : Datum datum;
9049 : :
9050 : 3118 : datum = DirectFunctionCall1(tidin, CStringGetDatum(valstr));
9051 : 3118 : ctid = (ItemPointer) DatumGetPointer(datum);
9052 : : }
9053 : : }
9054 : 281203 : errpos.cur_attno = 0;
9055 : :
9056 : 281203 : j++;
9057 : : }
9058 : :
9059 : : /* Uninstall error context callback. */
9060 : 100654 : error_context_stack = errcallback.previous;
9061 : :
9062 : : /*
9063 : : * Check we got the expected number of columns. Note: j == 0 and
9064 : : * PQnfields == 1 is expected, since deparse emits a NULL if no columns.
9065 : : */
9066 [ + + - + ]: 100654 : if (j > 0 && j != PQnfields(res))
9067 [ # # ]: 0 : elog(ERROR, "remote query result does not match the foreign table");
9068 : :
9069 : : /*
9070 : : * Build the result tuple in caller's memory context.
9071 : : */
9072 : 100654 : MemoryContextSwitchTo(oldcontext);
9073 : :
9074 : 100654 : tuple = heap_form_tuple(tupdesc, values, nulls);
9075 : :
9076 : : /*
9077 : : * If we have a CTID to return, install it in both t_self and t_ctid.
9078 : : * t_self is the normal place, but if the tuple is converted to a
9079 : : * composite Datum, t_self will be lost; setting t_ctid allows CTID to be
9080 : : * preserved during EvalPlanQual re-evaluations (see ROW_MARK_COPY code).
9081 : : */
9082 [ + + ]: 100654 : if (ctid)
9083 : 3118 : tuple->t_self = tuple->t_data->t_ctid = *ctid;
9084 : :
9085 : : /*
9086 : : * Stomp on the xmin, xmax, and cmin fields from the tuple created by
9087 : : * heap_form_tuple. heap_form_tuple actually creates the tuple with
9088 : : * DatumTupleFields, not HeapTupleFields, but the executor expects
9089 : : * HeapTupleFields and will happily extract system columns on that
9090 : : * assumption. If we don't do this then, for example, the tuple length
9091 : : * ends up in the xmin field, which isn't what we want.
9092 : : */
9093 : 100654 : HeapTupleHeaderSetXmax(tuple->t_data, InvalidTransactionId);
9094 : 100654 : HeapTupleHeaderSetXmin(tuple->t_data, InvalidTransactionId);
9095 : 100654 : HeapTupleHeaderSetCmin(tuple->t_data, InvalidTransactionId);
9096 : :
9097 : : /* Clean up */
9098 : 100654 : MemoryContextReset(temp_context);
9099 : :
9100 : 100654 : return tuple;
9101 : : }
9102 : :
9103 : : /*
9104 : : * Callback function which is called when error occurs during column value
9105 : : * conversion. Print names of column and relation.
9106 : : *
9107 : : * Note that this function mustn't do any catalog lookups, since we are in
9108 : : * an already-failed transaction. Fortunately, we can get the needed info
9109 : : * from the relation or the query's rangetable instead.
9110 : : */
9111 : : static void
9112 : 5 : conversion_error_callback(void *arg)
9113 : : {
9114 : 5 : ConversionLocation *errpos = (ConversionLocation *) arg;
9115 : 5 : Relation rel = errpos->rel;
9116 : 5 : ForeignScanState *fsstate = errpos->fsstate;
9117 : 5 : const char *attname = NULL;
9118 : 5 : const char *relname = NULL;
9119 : 5 : bool is_wholerow = false;
9120 : :
9121 : : /*
9122 : : * If we're in a scan node, always use aliases from the rangetable, for
9123 : : * consistency between the simple-relation and remote-join cases. Look at
9124 : : * the relation's tupdesc only if we're not in a scan node.
9125 : : */
9126 [ + + ]: 5 : if (fsstate)
9127 : : {
9128 : : /* ForeignScan case */
9129 : 4 : ForeignScan *fsplan = castNode(ForeignScan, fsstate->ss.ps.plan);
9130 : 4 : int varno = 0;
9131 : 4 : AttrNumber colno = 0;
9132 : :
9133 [ + + ]: 4 : if (fsplan->scan.scanrelid > 0)
9134 : : {
9135 : : /* error occurred in a scan against a foreign table */
9136 : 1 : varno = fsplan->scan.scanrelid;
9137 : 1 : colno = errpos->cur_attno;
9138 : : }
9139 : : else
9140 : : {
9141 : : /* error occurred in a scan against a foreign join */
9142 : : TargetEntry *tle;
9143 : :
9144 : 3 : tle = list_nth_node(TargetEntry, fsplan->fdw_scan_tlist,
9145 : : errpos->cur_attno - 1);
9146 : :
9147 : : /*
9148 : : * Target list can have Vars and expressions. For Vars, we can
9149 : : * get some information, however for expressions we can't. Thus
9150 : : * for expressions, just show generic context message.
9151 : : */
9152 [ + + ]: 3 : if (IsA(tle->expr, Var))
9153 : : {
9154 : 2 : Var *var = (Var *) tle->expr;
9155 : :
9156 : 2 : varno = var->varno;
9157 : 2 : colno = var->varattno;
9158 : : }
9159 : : }
9160 : :
9161 [ + + ]: 4 : if (varno > 0)
9162 : : {
9163 : 3 : EState *estate = fsstate->ss.ps.state;
9164 : 3 : RangeTblEntry *rte = exec_rt_fetch(varno, estate);
9165 : :
9166 : 3 : relname = rte->eref->aliasname;
9167 : :
9168 [ + + ]: 3 : if (colno == 0)
9169 : 1 : is_wholerow = true;
9170 [ + - + - ]: 2 : else if (colno > 0 && colno <= list_length(rte->eref->colnames))
9171 : 2 : attname = strVal(list_nth(rte->eref->colnames, colno - 1));
9172 [ # # ]: 0 : else if (colno == SelfItemPointerAttributeNumber)
9173 : 0 : attname = "ctid";
9174 : : }
9175 : : }
9176 [ + - ]: 1 : else if (rel)
9177 : : {
9178 : : /* Non-ForeignScan case (we should always have a rel here) */
9179 : 1 : TupleDesc tupdesc = RelationGetDescr(rel);
9180 : :
9181 : 1 : relname = RelationGetRelationName(rel);
9182 [ + - + - ]: 1 : if (errpos->cur_attno > 0 && errpos->cur_attno <= tupdesc->natts)
9183 : 1 : {
9184 : 1 : Form_pg_attribute attr = TupleDescAttr(tupdesc,
9185 : 1 : errpos->cur_attno - 1);
9186 : :
9187 : 1 : attname = NameStr(attr->attname);
9188 : : }
9189 [ # # ]: 0 : else if (errpos->cur_attno == SelfItemPointerAttributeNumber)
9190 : 0 : attname = "ctid";
9191 : : }
9192 : :
9193 [ + + + + ]: 5 : if (relname && is_wholerow)
9194 : 1 : errcontext("whole-row reference to foreign table \"%s\"", relname);
9195 [ + + + - ]: 4 : else if (relname && attname)
9196 : 3 : errcontext("column \"%s\" of foreign table \"%s\"", attname, relname);
9197 : : else
9198 : 1 : errcontext("processing expression at position %d in select list",
9199 : 1 : errpos->cur_attno);
9200 : 5 : }
9201 : :
9202 : : /*
9203 : : * Given an EquivalenceClass and a foreign relation, find an EC member
9204 : : * that can be used to sort the relation remotely according to a pathkey
9205 : : * using this EC.
9206 : : *
9207 : : * If there is more than one suitable candidate, return an arbitrary
9208 : : * one of them. If there is none, return NULL.
9209 : : *
9210 : : * This checks that the EC member expression uses only Vars from the given
9211 : : * rel and is shippable. Caller must separately verify that the pathkey's
9212 : : * ordering operator is shippable.
9213 : : */
9214 : : EquivalenceMember *
9215 : 2068 : find_em_for_rel(PlannerInfo *root, EquivalenceClass *ec, RelOptInfo *rel)
9216 : : {
9217 : 2068 : PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) rel->fdw_private;
9218 : : EquivalenceMemberIterator it;
9219 : : EquivalenceMember *em;
9220 : :
9221 : 2068 : setup_eclass_member_iterator(&it, ec, rel->relids);
9222 [ + + ]: 3500 : while ((em = eclass_member_iterator_next(&it)) != NULL)
9223 : : {
9224 : : /*
9225 : : * Note we require !bms_is_empty, else we'd accept constant
9226 : : * expressions which are not suitable for the purpose.
9227 : : */
9228 [ + + ]: 3208 : if (bms_is_subset(em->em_relids, rel->relids) &&
9229 [ + + + + ]: 3609 : !bms_is_empty(em->em_relids) &&
9230 [ + + ]: 3596 : bms_is_empty(bms_intersect(em->em_relids, fpinfo->hidden_subquery_rels)) &&
9231 : 1792 : is_foreign_expr(root, rel, fpinfo, em->em_expr))
9232 : 1776 : return em;
9233 : : }
9234 : :
9235 : 292 : return NULL;
9236 : : }
9237 : :
9238 : : /*
9239 : : * Find an EquivalenceClass member that is to be computed as a sort column
9240 : : * in the given rel's reltarget, and is shippable.
9241 : : *
9242 : : * If there is more than one suitable candidate, return an arbitrary
9243 : : * one of them. If there is none, return NULL.
9244 : : *
9245 : : * This checks that the EC member expression uses only Vars from the given
9246 : : * rel and is shippable. Caller must separately verify that the pathkey's
9247 : : * ordering operator is shippable.
9248 : : */
9249 : : EquivalenceMember *
9250 : 263 : find_em_for_rel_target(PlannerInfo *root, EquivalenceClass *ec,
9251 : : RelOptInfo *rel)
9252 : : {
9253 : 263 : PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) rel->fdw_private;
9254 : 263 : PathTarget *target = rel->reltarget;
9255 : : ListCell *lc1;
9256 : : int i;
9257 : :
9258 : 263 : i = 0;
9259 [ + - + - : 433 : foreach(lc1, target->exprs)
+ - ]
9260 : : {
9261 : 433 : Expr *expr = (Expr *) lfirst(lc1);
9262 [ + - ]: 433 : Index sgref = get_pathtarget_sortgroupref(target, i);
9263 : : ListCell *lc2;
9264 : :
9265 : : /* Ignore non-sort expressions */
9266 [ + + + + ]: 781 : if (sgref == 0 ||
9267 : 348 : get_sortgroupref_clause_noerr(sgref,
9268 : 348 : root->parse->sortClause) == NULL)
9269 : : {
9270 : 93 : i++;
9271 : 93 : continue;
9272 : : }
9273 : :
9274 : : /* We ignore binary-compatible relabeling on both ends */
9275 [ + - - + ]: 340 : while (expr && IsA(expr, RelabelType))
9276 : 0 : expr = ((RelabelType *) expr)->arg;
9277 : :
9278 : : /*
9279 : : * Locate an EquivalenceClass member matching this expr, if any.
9280 : : * Ignore child members.
9281 : : */
9282 [ + - + + : 421 : foreach(lc2, ec->ec_members)
+ + ]
9283 : : {
9284 : 344 : EquivalenceMember *em = (EquivalenceMember *) lfirst(lc2);
9285 : : Expr *em_expr;
9286 : :
9287 : : /* Don't match constants */
9288 [ - + ]: 344 : if (em->em_is_const)
9289 : 0 : continue;
9290 : :
9291 : : /* Child members should not exist in ec_members */
9292 : : Assert(!em->em_is_child);
9293 : :
9294 : : /* Match if same expression (after stripping relabel) */
9295 : 344 : em_expr = em->em_expr;
9296 [ + - + + ]: 356 : while (em_expr && IsA(em_expr, RelabelType))
9297 : 12 : em_expr = ((RelabelType *) em_expr)->arg;
9298 : :
9299 [ + + ]: 344 : if (!equal(em_expr, expr))
9300 : 81 : continue;
9301 : :
9302 : : /* Check that expression (including relabels!) is shippable */
9303 [ + - ]: 263 : if (is_foreign_expr(root, rel, fpinfo, em->em_expr))
9304 : 263 : return em;
9305 : : }
9306 : :
9307 : 77 : i++;
9308 : : }
9309 : :
9310 : 0 : return NULL;
9311 : : }
9312 : :
9313 : : /*
9314 : : * Determine batch size for a given foreign table. The option specified for
9315 : : * a table has precedence.
9316 : : */
9317 : : static int
9318 : 152 : get_batch_size_option(Relation rel)
9319 : : {
9320 : 152 : Oid foreigntableid = RelationGetRelid(rel);
9321 : : ForeignTable *table;
9322 : : ForeignServer *server;
9323 : : List *options;
9324 : : ListCell *lc;
9325 : :
9326 : : /* we use 1 by default, which means "no batching" */
9327 : 152 : int batch_size = 1;
9328 : :
9329 : : /*
9330 : : * Load options for table and server. We append server options after table
9331 : : * options, because table options take precedence.
9332 : : */
9333 : 152 : table = GetForeignTable(foreigntableid);
9334 : 152 : server = GetForeignServer(table->serverid);
9335 : :
9336 : 152 : options = NIL;
9337 : 152 : options = list_concat(options, table->options);
9338 : 152 : options = list_concat(options, server->options);
9339 : :
9340 : : /* See if either table or server specifies batch_size. */
9341 [ + - + + : 807 : foreach(lc, options)
+ + ]
9342 : : {
9343 : 691 : DefElem *def = (DefElem *) lfirst(lc);
9344 : :
9345 [ + + ]: 691 : if (strcmp(def->defname, "batch_size") == 0)
9346 : : {
9347 : 36 : (void) parse_int(defGetString(def), &batch_size, 0, NULL);
9348 : 36 : break;
9349 : : }
9350 : : }
9351 : :
9352 : 152 : return batch_size;
9353 : : }
|