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