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