LCOV - code coverage report
Current view: top level - contrib/postgres_fdw - deparse.c (source / functions) Hit Total Coverage
Test: PostgreSQL 12devel Lines: 1008 1121 89.9 %
Date: 2018-10-17 03:20:55 Functions: 51 51 100.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*-------------------------------------------------------------------------
       2             :  *
       3             :  * deparse.c
       4             :  *        Query deparser for postgres_fdw
       5             :  *
       6             :  * This file includes functions that examine query WHERE clauses to see
       7             :  * whether they're safe to send to the remote server for execution, as
       8             :  * well as functions to construct the query text to be sent.  The latter
       9             :  * functionality is annoyingly duplicative of ruleutils.c, but there are
      10             :  * enough special considerations that it seems best to keep this separate.
      11             :  * One saving grace is that we only need deparse logic for node types that
      12             :  * we consider safe to send.
      13             :  *
      14             :  * We assume that the remote session's search_path is exactly "pg_catalog",
      15             :  * and thus we need schema-qualify all and only names outside pg_catalog.
      16             :  *
      17             :  * We do not consider that it is ever safe to send COLLATE expressions to
      18             :  * the remote server: it might not have the same collation names we do.
      19             :  * (Later we might consider it safe to send COLLATE "C", but even that would
      20             :  * fail on old remote servers.)  An expression is considered safe to send
      21             :  * only if all operator/function input collations used in it are traceable to
      22             :  * Var(s) of the foreign table.  That implies that if the remote server gets
      23             :  * a different answer than we do, the foreign table's columns are not marked
      24             :  * with collations that match the remote table's columns, which we can
      25             :  * consider to be user error.
      26             :  *
      27             :  * Portions Copyright (c) 2012-2018, PostgreSQL Global Development Group
      28             :  *
      29             :  * IDENTIFICATION
      30             :  *        contrib/postgres_fdw/deparse.c
      31             :  *
      32             :  *-------------------------------------------------------------------------
      33             :  */
      34             : #include "postgres.h"
      35             : 
      36             : #include "postgres_fdw.h"
      37             : 
      38             : #include "access/heapam.h"
      39             : #include "access/htup_details.h"
      40             : #include "access/sysattr.h"
      41             : #include "catalog/pg_aggregate.h"
      42             : #include "catalog/pg_collation.h"
      43             : #include "catalog/pg_namespace.h"
      44             : #include "catalog/pg_operator.h"
      45             : #include "catalog/pg_proc.h"
      46             : #include "catalog/pg_type.h"
      47             : #include "commands/defrem.h"
      48             : #include "nodes/makefuncs.h"
      49             : #include "nodes/nodeFuncs.h"
      50             : #include "nodes/plannodes.h"
      51             : #include "optimizer/clauses.h"
      52             : #include "optimizer/prep.h"
      53             : #include "optimizer/tlist.h"
      54             : #include "optimizer/var.h"
      55             : #include "parser/parsetree.h"
      56             : #include "utils/builtins.h"
      57             : #include "utils/lsyscache.h"
      58             : #include "utils/rel.h"
      59             : #include "utils/syscache.h"
      60             : #include "utils/typcache.h"
      61             : 
      62             : 
      63             : /*
      64             :  * Global context for foreign_expr_walker's search of an expression tree.
      65             :  */
      66             : typedef struct foreign_glob_cxt
      67             : {
      68             :     PlannerInfo *root;          /* global planner state */
      69             :     RelOptInfo *foreignrel;     /* the foreign relation we are planning for */
      70             :     Relids      relids;         /* relids of base relations in the underlying
      71             :                                  * scan */
      72             : } foreign_glob_cxt;
      73             : 
      74             : /*
      75             :  * Local (per-tree-level) context for foreign_expr_walker's search.
      76             :  * This is concerned with identifying collations used in the expression.
      77             :  */
      78             : typedef enum
      79             : {
      80             :     FDW_COLLATE_NONE,           /* expression is of a noncollatable type, or
      81             :                                  * it has default collation that is not
      82             :                                  * traceable to a foreign Var */
      83             :     FDW_COLLATE_SAFE,           /* collation derives from a foreign Var */
      84             :     FDW_COLLATE_UNSAFE          /* collation is non-default and derives from
      85             :                                  * something other than a foreign Var */
      86             : } FDWCollateState;
      87             : 
      88             : typedef struct foreign_loc_cxt
      89             : {
      90             :     Oid         collation;      /* OID of current collation, if any */
      91             :     FDWCollateState state;      /* state of current collation choice */
      92             : } foreign_loc_cxt;
      93             : 
      94             : /*
      95             :  * Context for deparseExpr
      96             :  */
      97             : typedef struct deparse_expr_cxt
      98             : {
      99             :     PlannerInfo *root;          /* global planner state */
     100             :     RelOptInfo *foreignrel;     /* the foreign relation we are planning for */
     101             :     RelOptInfo *scanrel;        /* the underlying scan relation. Same as
     102             :                                  * foreignrel, when that represents a join or
     103             :                                  * a base relation. */
     104             :     StringInfo  buf;            /* output buffer to append to */
     105             :     List      **params_list;    /* exprs that will become remote Params */
     106             : } deparse_expr_cxt;
     107             : 
     108             : #define REL_ALIAS_PREFIX    "r"
     109             : /* Handy macro to add relation name qualification */
     110             : #define ADD_REL_QUALIFIER(buf, varno)   \
     111             :         appendStringInfo((buf), "%s%d.", REL_ALIAS_PREFIX, (varno))
     112             : #define SUBQUERY_REL_ALIAS_PREFIX   "s"
     113             : #define SUBQUERY_COL_ALIAS_PREFIX   "c"
     114             : 
     115             : /*
     116             :  * Functions to determine whether an expression can be evaluated safely on
     117             :  * remote server.
     118             :  */
     119             : static bool foreign_expr_walker(Node *node,
     120             :                     foreign_glob_cxt *glob_cxt,
     121             :                     foreign_loc_cxt *outer_cxt);
     122             : static char *deparse_type_name(Oid type_oid, int32 typemod);
     123             : 
     124             : /*
     125             :  * Functions to construct string representation of a node tree.
     126             :  */
     127             : static void deparseTargetList(StringInfo buf,
     128             :                   RangeTblEntry *rte,
     129             :                   Index rtindex,
     130             :                   Relation rel,
     131             :                   bool is_returning,
     132             :                   Bitmapset *attrs_used,
     133             :                   bool qualify_col,
     134             :                   List **retrieved_attrs);
     135             : static void deparseExplicitTargetList(List *tlist,
     136             :                           bool is_returning,
     137             :                           List **retrieved_attrs,
     138             :                           deparse_expr_cxt *context);
     139             : static void deparseSubqueryTargetList(deparse_expr_cxt *context);
     140             : static void deparseReturningList(StringInfo buf, RangeTblEntry *rte,
     141             :                      Index rtindex, Relation rel,
     142             :                      bool trig_after_row,
     143             :                      List *withCheckOptionList,
     144             :                      List *returningList,
     145             :                      List **retrieved_attrs);
     146             : static void deparseColumnRef(StringInfo buf, int varno, int varattno,
     147             :                  RangeTblEntry *rte, bool qualify_col);
     148             : static void deparseRelation(StringInfo buf, Relation rel);
     149             : static void deparseExpr(Expr *expr, deparse_expr_cxt *context);
     150             : static void deparseVar(Var *node, deparse_expr_cxt *context);
     151             : static void deparseConst(Const *node, deparse_expr_cxt *context, int showtype);
     152             : static void deparseParam(Param *node, deparse_expr_cxt *context);
     153             : static void deparseArrayRef(ArrayRef *node, deparse_expr_cxt *context);
     154             : static void deparseFuncExpr(FuncExpr *node, deparse_expr_cxt *context);
     155             : static void deparseOpExpr(OpExpr *node, deparse_expr_cxt *context);
     156             : static void deparseOperatorName(StringInfo buf, Form_pg_operator opform);
     157             : static void deparseDistinctExpr(DistinctExpr *node, deparse_expr_cxt *context);
     158             : static void deparseScalarArrayOpExpr(ScalarArrayOpExpr *node,
     159             :                          deparse_expr_cxt *context);
     160             : static void deparseRelabelType(RelabelType *node, deparse_expr_cxt *context);
     161             : static void deparseBoolExpr(BoolExpr *node, deparse_expr_cxt *context);
     162             : static void deparseNullTest(NullTest *node, deparse_expr_cxt *context);
     163             : static void deparseArrayExpr(ArrayExpr *node, deparse_expr_cxt *context);
     164             : static void printRemoteParam(int paramindex, Oid paramtype, int32 paramtypmod,
     165             :                  deparse_expr_cxt *context);
     166             : static void printRemotePlaceholder(Oid paramtype, int32 paramtypmod,
     167             :                        deparse_expr_cxt *context);
     168             : static void deparseSelectSql(List *tlist, bool is_subquery, List **retrieved_attrs,
     169             :                  deparse_expr_cxt *context);
     170             : static void deparseLockingClause(deparse_expr_cxt *context);
     171             : static void appendOrderByClause(List *pathkeys, deparse_expr_cxt *context);
     172             : static void appendConditions(List *exprs, deparse_expr_cxt *context);
     173             : static void deparseFromExprForRel(StringInfo buf, PlannerInfo *root,
     174             :                       RelOptInfo *foreignrel, bool use_alias,
     175             :                       Index ignore_rel, List **ignore_conds,
     176             :                       List **params_list);
     177             : static void deparseFromExpr(List *quals, deparse_expr_cxt *context);
     178             : static void deparseRangeTblRef(StringInfo buf, PlannerInfo *root,
     179             :                    RelOptInfo *foreignrel, bool make_subquery,
     180             :                    Index ignore_rel, List **ignore_conds, List **params_list);
     181             : static void deparseAggref(Aggref *node, deparse_expr_cxt *context);
     182             : static void appendGroupByClause(List *tlist, deparse_expr_cxt *context);
     183             : static void appendAggOrderBy(List *orderList, List *targetList,
     184             :                  deparse_expr_cxt *context);
     185             : static void appendFunctionName(Oid funcid, deparse_expr_cxt *context);
     186             : static Node *deparseSortGroupClause(Index ref, List *tlist, bool force_colno,
     187             :                        deparse_expr_cxt *context);
     188             : 
     189             : /*
     190             :  * Helper functions
     191             :  */
     192             : static bool is_subquery_var(Var *node, RelOptInfo *foreignrel,
     193             :                 int *relno, int *colno);
     194             : static void get_relation_column_alias_ids(Var *node, RelOptInfo *foreignrel,
     195             :                               int *relno, int *colno);
     196             : 
     197             : 
     198             : /*
     199             :  * Examine each qual clause in input_conds, and classify them into two groups,
     200             :  * which are returned as two lists:
     201             :  *  - remote_conds contains expressions that can be evaluated remotely
     202             :  *  - local_conds contains expressions that can't be evaluated remotely
     203             :  */
     204             : void
     205        3206 : classifyConditions(PlannerInfo *root,
     206             :                    RelOptInfo *baserel,
     207             :                    List *input_conds,
     208             :                    List **remote_conds,
     209             :                    List **local_conds)
     210             : {
     211             :     ListCell   *lc;
     212             : 
     213        3206 :     *remote_conds = NIL;
     214        3206 :     *local_conds = NIL;
     215             : 
     216        4234 :     foreach(lc, input_conds)
     217             :     {
     218        1028 :         RestrictInfo *ri = lfirst_node(RestrictInfo, lc);
     219             : 
     220        1028 :         if (is_foreign_expr(root, baserel, ri->clause))
     221         958 :             *remote_conds = lappend(*remote_conds, ri);
     222             :         else
     223          70 :             *local_conds = lappend(*local_conds, ri);
     224             :     }
     225        3206 : }
     226             : 
     227             : /*
     228             :  * Returns true if given expr is safe to evaluate on the foreign server.
     229             :  */
     230             : bool
     231        3822 : is_foreign_expr(PlannerInfo *root,
     232             :                 RelOptInfo *baserel,
     233             :                 Expr *expr)
     234             : {
     235             :     foreign_glob_cxt glob_cxt;
     236             :     foreign_loc_cxt loc_cxt;
     237        3822 :     PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) (baserel->fdw_private);
     238             : 
     239             :     /*
     240             :      * Check that the expression consists of nodes that are safe to execute
     241             :      * remotely.
     242             :      */
     243        3822 :     glob_cxt.root = root;
     244        3822 :     glob_cxt.foreignrel = baserel;
     245             : 
     246             :     /*
     247             :      * For an upper relation, use relids from its underneath scan relation,
     248             :      * because the upperrel's own relids currently aren't set to anything
     249             :      * meaningful by the core code.  For other relation, use their own relids.
     250             :      */
     251        3822 :     if (IS_UPPER_REL(baserel))
     252         594 :         glob_cxt.relids = fpinfo->outerrel->relids;
     253             :     else
     254        3228 :         glob_cxt.relids = baserel->relids;
     255        3822 :     loc_cxt.collation = InvalidOid;
     256        3822 :     loc_cxt.state = FDW_COLLATE_NONE;
     257        3822 :     if (!foreign_expr_walker((Node *) expr, &glob_cxt, &loc_cxt))
     258         198 :         return false;
     259             : 
     260             :     /*
     261             :      * If the expression has a valid collation that does not arise from a
     262             :      * foreign var, the expression can not be sent over.
     263             :      */
     264        3624 :     if (loc_cxt.state == FDW_COLLATE_UNSAFE)
     265           4 :         return false;
     266             : 
     267             :     /*
     268             :      * An expression which includes any mutable functions can't be sent over
     269             :      * because its result is not stable.  For example, sending now() remote
     270             :      * side could cause confusion from clock offsets.  Future versions might
     271             :      * be able to make this choice with more granularity.  (We check this last
     272             :      * because it requires a lot of expensive catalog lookups.)
     273             :      */
     274        3620 :     if (contain_mutable_functions((Node *) expr))
     275          42 :         return false;
     276             : 
     277             :     /* OK to evaluate on the remote server */
     278        3578 :     return true;
     279             : }
     280             : 
     281             : /*
     282             :  * Check if expression is safe to execute remotely, and return true if so.
     283             :  *
     284             :  * In addition, *outer_cxt is updated with collation information.
     285             :  *
     286             :  * We must check that the expression contains only node types we can deparse,
     287             :  * that all types/functions/operators are safe to send (they are "shippable"),
     288             :  * and that all collations used in the expression derive from Vars of the
     289             :  * foreign table.  Because of the latter, the logic is pretty close to
     290             :  * assign_collations_walker() in parse_collate.c, though we can assume here
     291             :  * that the given expression is valid.  Note function mutability is not
     292             :  * currently considered here.
     293             :  */
     294             : static bool
     295       11738 : foreign_expr_walker(Node *node,
     296             :                     foreign_glob_cxt *glob_cxt,
     297             :                     foreign_loc_cxt *outer_cxt)
     298             : {
     299       11738 :     bool        check_type = true;
     300             :     PgFdwRelationInfo *fpinfo;
     301             :     foreign_loc_cxt inner_cxt;
     302             :     Oid         collation;
     303             :     FDWCollateState state;
     304             : 
     305             :     /* Need do nothing for empty subexpressions */
     306       11738 :     if (node == NULL)
     307         350 :         return true;
     308             : 
     309             :     /* May need server info from baserel's fdw_private struct */
     310       11388 :     fpinfo = (PgFdwRelationInfo *) (glob_cxt->foreignrel->fdw_private);
     311             : 
     312             :     /* Set up inner_cxt for possible recursion to child nodes */
     313       11388 :     inner_cxt.collation = InvalidOid;
     314       11388 :     inner_cxt.state = FDW_COLLATE_NONE;
     315             : 
     316       11388 :     switch (nodeTag(node))
     317             :     {
     318             :         case T_Var:
     319             :             {
     320        4756 :                 Var        *var = (Var *) node;
     321             : 
     322             :                 /*
     323             :                  * If the Var is from the foreign table, we consider its
     324             :                  * collation (if any) safe to use.  If it is from another
     325             :                  * table, we treat its collation the same way as we would a
     326             :                  * Param's collation, ie it's not safe for it to have a
     327             :                  * non-default collation.
     328             :                  */
     329        8920 :                 if (bms_is_member(var->varno, glob_cxt->relids) &&
     330        4164 :                     var->varlevelsup == 0)
     331             :                 {
     332             :                     /* Var belongs to foreign table */
     333             : 
     334             :                     /*
     335             :                      * System columns other than ctid and oid should not be
     336             :                      * sent to the remote, since we don't make any effort to
     337             :                      * ensure that local and remote values match (tableoid, in
     338             :                      * particular, almost certainly doesn't match).
     339             :                      */
     340        4180 :                     if (var->varattno < 0 &&
     341          28 :                         var->varattno != SelfItemPointerAttributeNumber &&
     342          12 :                         var->varattno != ObjectIdAttributeNumber)
     343          12 :                         return false;
     344             : 
     345             :                     /* Else check the collation */
     346        4152 :                     collation = var->varcollid;
     347        4152 :                     state = OidIsValid(collation) ? FDW_COLLATE_SAFE : FDW_COLLATE_NONE;
     348             :                 }
     349             :                 else
     350             :                 {
     351             :                     /* Var belongs to some other table */
     352         592 :                     collation = var->varcollid;
     353         592 :                     if (collation == InvalidOid ||
     354             :                         collation == DEFAULT_COLLATION_OID)
     355             :                     {
     356             :                         /*
     357             :                          * It's noncollatable, or it's safe to combine with a
     358             :                          * collatable foreign Var, so set state to NONE.
     359             :                          */
     360         592 :                         state = FDW_COLLATE_NONE;
     361             :                     }
     362             :                     else
     363             :                     {
     364             :                         /*
     365             :                          * Do not fail right away, since the Var might appear
     366             :                          * in a collation-insensitive context.
     367             :                          */
     368           0 :                         state = FDW_COLLATE_UNSAFE;
     369             :                     }
     370             :                 }
     371             :             }
     372        4744 :             break;
     373             :         case T_Const:
     374             :             {
     375        1074 :                 Const      *c = (Const *) node;
     376             : 
     377             :                 /*
     378             :                  * If the constant has nondefault collation, either it's of a
     379             :                  * non-builtin type, or it reflects folding of a CollateExpr.
     380             :                  * It's unsafe to send to the remote unless it's used in a
     381             :                  * non-collation-sensitive context.
     382             :                  */
     383        1074 :                 collation = c->constcollid;
     384        1074 :                 if (collation == InvalidOid ||
     385             :                     collation == DEFAULT_COLLATION_OID)
     386        1070 :                     state = FDW_COLLATE_NONE;
     387             :                 else
     388           4 :                     state = FDW_COLLATE_UNSAFE;
     389             :             }
     390        1074 :             break;
     391             :         case T_Param:
     392             :             {
     393          26 :                 Param      *p = (Param *) node;
     394             : 
     395             :                 /*
     396             :                  * Collation rule is same as for Consts and non-foreign Vars.
     397             :                  */
     398          26 :                 collation = p->paramcollid;
     399          26 :                 if (collation == InvalidOid ||
     400             :                     collation == DEFAULT_COLLATION_OID)
     401          26 :                     state = FDW_COLLATE_NONE;
     402             :                 else
     403           0 :                     state = FDW_COLLATE_UNSAFE;
     404             :             }
     405          26 :             break;
     406             :         case T_ArrayRef:
     407             :             {
     408           2 :                 ArrayRef   *ar = (ArrayRef *) node;
     409             : 
     410             :                 /* Assignment should not be in restrictions. */
     411           2 :                 if (ar->refassgnexpr != NULL)
     412           0 :                     return false;
     413             : 
     414             :                 /*
     415             :                  * Recurse to remaining subexpressions.  Since the array
     416             :                  * subscripts must yield (noncollatable) integers, they won't
     417             :                  * affect the inner_cxt state.
     418             :                  */
     419           2 :                 if (!foreign_expr_walker((Node *) ar->refupperindexpr,
     420             :                                          glob_cxt, &inner_cxt))
     421           0 :                     return false;
     422           2 :                 if (!foreign_expr_walker((Node *) ar->reflowerindexpr,
     423             :                                          glob_cxt, &inner_cxt))
     424           0 :                     return false;
     425           2 :                 if (!foreign_expr_walker((Node *) ar->refexpr,
     426             :                                          glob_cxt, &inner_cxt))
     427           0 :                     return false;
     428             : 
     429             :                 /*
     430             :                  * Array subscripting should yield same collation as input,
     431             :                  * but for safety use same logic as for function nodes.
     432             :                  */
     433           2 :                 collation = ar->refcollid;
     434           2 :                 if (collation == InvalidOid)
     435           2 :                     state = FDW_COLLATE_NONE;
     436           0 :                 else if (inner_cxt.state == FDW_COLLATE_SAFE &&
     437           0 :                          collation == inner_cxt.collation)
     438           0 :                     state = FDW_COLLATE_SAFE;
     439           0 :                 else if (collation == DEFAULT_COLLATION_OID)
     440           0 :                     state = FDW_COLLATE_NONE;
     441             :                 else
     442           0 :                     state = FDW_COLLATE_UNSAFE;
     443             :             }
     444           2 :             break;
     445             :         case T_FuncExpr:
     446             :             {
     447         212 :                 FuncExpr   *fe = (FuncExpr *) node;
     448             : 
     449             :                 /*
     450             :                  * If function used by the expression is not shippable, it
     451             :                  * can't be sent to remote because it might have incompatible
     452             :                  * semantics on remote side.
     453             :                  */
     454         212 :                 if (!is_shippable(fe->funcid, ProcedureRelationId, fpinfo))
     455          10 :                     return false;
     456             : 
     457             :                 /*
     458             :                  * Recurse to input subexpressions.
     459             :                  */
     460         202 :                 if (!foreign_expr_walker((Node *) fe->args,
     461             :                                          glob_cxt, &inner_cxt))
     462          12 :                     return false;
     463             : 
     464             :                 /*
     465             :                  * If function's input collation is not derived from a foreign
     466             :                  * Var, it can't be sent to remote.
     467             :                  */
     468         190 :                 if (fe->inputcollid == InvalidOid)
     469             :                      /* OK, inputs are all noncollatable */ ;
     470          68 :                 else if (inner_cxt.state != FDW_COLLATE_SAFE ||
     471          24 :                          fe->inputcollid != inner_cxt.collation)
     472          20 :                     return false;
     473             : 
     474             :                 /*
     475             :                  * Detect whether node is introducing a collation not derived
     476             :                  * from a foreign Var.  (If so, we just mark it unsafe for now
     477             :                  * rather than immediately returning false, since the parent
     478             :                  * node might not care.)
     479             :                  */
     480         170 :                 collation = fe->funccollid;
     481         170 :                 if (collation == InvalidOid)
     482         146 :                     state = FDW_COLLATE_NONE;
     483          48 :                 else if (inner_cxt.state == FDW_COLLATE_SAFE &&
     484          24 :                          collation == inner_cxt.collation)
     485          24 :                     state = FDW_COLLATE_SAFE;
     486           0 :                 else if (collation == DEFAULT_COLLATION_OID)
     487           0 :                     state = FDW_COLLATE_NONE;
     488             :                 else
     489           0 :                     state = FDW_COLLATE_UNSAFE;
     490             :             }
     491         170 :             break;
     492             :         case T_OpExpr:
     493             :         case T_DistinctExpr:    /* struct-equivalent to OpExpr */
     494             :             {
     495        2202 :                 OpExpr     *oe = (OpExpr *) node;
     496             : 
     497             :                 /*
     498             :                  * Similarly, only shippable operators can be sent to remote.
     499             :                  * (If the operator is shippable, we assume its underlying
     500             :                  * function is too.)
     501             :                  */
     502        2202 :                 if (!is_shippable(oe->opno, OperatorRelationId, fpinfo))
     503          22 :                     return false;
     504             : 
     505             :                 /*
     506             :                  * Recurse to input subexpressions.
     507             :                  */
     508        2180 :                 if (!foreign_expr_walker((Node *) oe->args,
     509             :                                          glob_cxt, &inner_cxt))
     510          76 :                     return false;
     511             : 
     512             :                 /*
     513             :                  * If operator's input collation is not derived from a foreign
     514             :                  * Var, it can't be sent to remote.
     515             :                  */
     516        2104 :                 if (oe->inputcollid == InvalidOid)
     517             :                      /* OK, inputs are all noncollatable */ ;
     518         166 :                 else if (inner_cxt.state != FDW_COLLATE_SAFE ||
     519          78 :                          oe->inputcollid != inner_cxt.collation)
     520          10 :                     return false;
     521             : 
     522             :                 /* Result-collation handling is same as for functions */
     523        2094 :                 collation = oe->opcollid;
     524        2094 :                 if (collation == InvalidOid)
     525        2078 :                     state = FDW_COLLATE_NONE;
     526          32 :                 else if (inner_cxt.state == FDW_COLLATE_SAFE &&
     527          16 :                          collation == inner_cxt.collation)
     528          16 :                     state = FDW_COLLATE_SAFE;
     529           0 :                 else if (collation == DEFAULT_COLLATION_OID)
     530           0 :                     state = FDW_COLLATE_NONE;
     531             :                 else
     532           0 :                     state = FDW_COLLATE_UNSAFE;
     533             :             }
     534        2094 :             break;
     535             :         case T_ScalarArrayOpExpr:
     536             :             {
     537           6 :                 ScalarArrayOpExpr *oe = (ScalarArrayOpExpr *) node;
     538             : 
     539             :                 /*
     540             :                  * Again, only shippable operators can be sent to remote.
     541             :                  */
     542           6 :                 if (!is_shippable(oe->opno, OperatorRelationId, fpinfo))
     543           0 :                     return false;
     544             : 
     545             :                 /*
     546             :                  * Recurse to input subexpressions.
     547             :                  */
     548           6 :                 if (!foreign_expr_walker((Node *) oe->args,
     549             :                                          glob_cxt, &inner_cxt))
     550           0 :                     return false;
     551             : 
     552             :                 /*
     553             :                  * If operator's input collation is not derived from a foreign
     554             :                  * Var, it can't be sent to remote.
     555             :                  */
     556           6 :                 if (oe->inputcollid == InvalidOid)
     557             :                      /* OK, inputs are all noncollatable */ ;
     558           0 :                 else if (inner_cxt.state != FDW_COLLATE_SAFE ||
     559           0 :                          oe->inputcollid != inner_cxt.collation)
     560           0 :                     return false;
     561             : 
     562             :                 /* Output is always boolean and so noncollatable. */
     563           6 :                 collation = InvalidOid;
     564           6 :                 state = FDW_COLLATE_NONE;
     565             :             }
     566           6 :             break;
     567             :         case T_RelabelType:
     568             :             {
     569          82 :                 RelabelType *r = (RelabelType *) node;
     570             : 
     571             :                 /*
     572             :                  * Recurse to input subexpression.
     573             :                  */
     574          82 :                 if (!foreign_expr_walker((Node *) r->arg,
     575             :                                          glob_cxt, &inner_cxt))
     576           0 :                     return false;
     577             : 
     578             :                 /*
     579             :                  * RelabelType must not introduce a collation not derived from
     580             :                  * an input foreign Var (same logic as for a real function).
     581             :                  */
     582          82 :                 collation = r->resultcollid;
     583          82 :                 if (collation == InvalidOid)
     584           0 :                     state = FDW_COLLATE_NONE;
     585         156 :                 else if (inner_cxt.state == FDW_COLLATE_SAFE &&
     586          74 :                          collation == inner_cxt.collation)
     587          64 :                     state = FDW_COLLATE_SAFE;
     588          18 :                 else if (collation == DEFAULT_COLLATION_OID)
     589           6 :                     state = FDW_COLLATE_NONE;
     590             :                 else
     591          12 :                     state = FDW_COLLATE_UNSAFE;
     592             :             }
     593          82 :             break;
     594             :         case T_BoolExpr:
     595             :             {
     596          64 :                 BoolExpr   *b = (BoolExpr *) node;
     597             : 
     598             :                 /*
     599             :                  * Recurse to input subexpressions.
     600             :                  */
     601          64 :                 if (!foreign_expr_walker((Node *) b->args,
     602             :                                          glob_cxt, &inner_cxt))
     603           0 :                     return false;
     604             : 
     605             :                 /* Output is always boolean and so noncollatable. */
     606          64 :                 collation = InvalidOid;
     607          64 :                 state = FDW_COLLATE_NONE;
     608             :             }
     609          64 :             break;
     610             :         case T_NullTest:
     611             :             {
     612          54 :                 NullTest   *nt = (NullTest *) node;
     613             : 
     614             :                 /*
     615             :                  * Recurse to input subexpressions.
     616             :                  */
     617          54 :                 if (!foreign_expr_walker((Node *) nt->arg,
     618             :                                          glob_cxt, &inner_cxt))
     619           0 :                     return false;
     620             : 
     621             :                 /* Output is always boolean and so noncollatable. */
     622          54 :                 collation = InvalidOid;
     623          54 :                 state = FDW_COLLATE_NONE;
     624             :             }
     625          54 :             break;
     626             :         case T_ArrayExpr:
     627             :             {
     628           8 :                 ArrayExpr  *a = (ArrayExpr *) node;
     629             : 
     630             :                 /*
     631             :                  * Recurse to input subexpressions.
     632             :                  */
     633           8 :                 if (!foreign_expr_walker((Node *) a->elements,
     634             :                                          glob_cxt, &inner_cxt))
     635           0 :                     return false;
     636             : 
     637             :                 /*
     638             :                  * ArrayExpr must not introduce a collation not derived from
     639             :                  * an input foreign Var (same logic as for a function).
     640             :                  */
     641           8 :                 collation = a->array_collid;
     642           8 :                 if (collation == InvalidOid)
     643           8 :                     state = FDW_COLLATE_NONE;
     644           0 :                 else if (inner_cxt.state == FDW_COLLATE_SAFE &&
     645           0 :                          collation == inner_cxt.collation)
     646           0 :                     state = FDW_COLLATE_SAFE;
     647           0 :                 else if (collation == DEFAULT_COLLATION_OID)
     648           0 :                     state = FDW_COLLATE_NONE;
     649             :                 else
     650           0 :                     state = FDW_COLLATE_UNSAFE;
     651             :             }
     652           8 :             break;
     653             :         case T_List:
     654             :             {
     655        2468 :                 List       *l = (List *) node;
     656             :                 ListCell   *lc;
     657             : 
     658             :                 /*
     659             :                  * Recurse to component subexpressions.
     660             :                  */
     661        7010 :                 foreach(lc, l)
     662             :                 {
     663        4656 :                     if (!foreign_expr_walker((Node *) lfirst(lc),
     664             :                                              glob_cxt, &inner_cxt))
     665         114 :                         return false;
     666             :                 }
     667             : 
     668             :                 /*
     669             :                  * When processing a list, collation state just bubbles up
     670             :                  * from the list elements.
     671             :                  */
     672        2354 :                 collation = inner_cxt.collation;
     673        2354 :                 state = inner_cxt.state;
     674             : 
     675             :                 /* Don't apply exprType() to the list. */
     676        2354 :                 check_type = false;
     677             :             }
     678        2354 :             break;
     679             :         case T_Aggref:
     680             :             {
     681         376 :                 Aggref     *agg = (Aggref *) node;
     682             :                 ListCell   *lc;
     683             : 
     684             :                 /* Not safe to pushdown when not in grouping context */
     685         376 :                 if (!IS_UPPER_REL(glob_cxt->foreignrel))
     686           0 :                     return false;
     687             : 
     688             :                 /* Only non-split aggregates are pushable. */
     689         376 :                 if (agg->aggsplit != AGGSPLIT_SIMPLE)
     690           0 :                     return false;
     691             : 
     692             :                 /* As usual, it must be shippable. */
     693         376 :                 if (!is_shippable(agg->aggfnoid, ProcedureRelationId, fpinfo))
     694           8 :                     return false;
     695             : 
     696             :                 /*
     697             :                  * Recurse to input args. aggdirectargs, aggorder and
     698             :                  * aggdistinct are all present in args, so no need to check
     699             :                  * their shippability explicitly.
     700             :                  */
     701         666 :                 foreach(lc, agg->args)
     702             :                 {
     703         322 :                     Node       *n = (Node *) lfirst(lc);
     704             : 
     705             :                     /* If TargetEntry, extract the expression from it */
     706         322 :                     if (IsA(n, TargetEntry))
     707             :                     {
     708         322 :                         TargetEntry *tle = (TargetEntry *) n;
     709             : 
     710         322 :                         n = (Node *) tle->expr;
     711             :                     }
     712             : 
     713         322 :                     if (!foreign_expr_walker(n, glob_cxt, &inner_cxt))
     714          24 :                         return false;
     715             :                 }
     716             : 
     717             :                 /*
     718             :                  * For aggorder elements, check whether the sort operator, if
     719             :                  * specified, is shippable or not.
     720             :                  */
     721         344 :                 if (agg->aggorder)
     722             :                 {
     723             :                     ListCell   *lc;
     724             : 
     725          92 :                     foreach(lc, agg->aggorder)
     726             :                     {
     727          52 :                         SortGroupClause *srt = (SortGroupClause *) lfirst(lc);
     728             :                         Oid         sortcoltype;
     729             :                         TypeCacheEntry *typentry;
     730             :                         TargetEntry *tle;
     731             : 
     732          52 :                         tle = get_sortgroupref_tle(srt->tleSortGroupRef,
     733             :                                                    agg->args);
     734          52 :                         sortcoltype = exprType((Node *) tle->expr);
     735          52 :                         typentry = lookup_type_cache(sortcoltype,
     736             :                                                      TYPECACHE_LT_OPR | TYPECACHE_GT_OPR);
     737             :                         /* Check shippability of non-default sort operator. */
     738          72 :                         if (srt->sortop != typentry->lt_opr &&
     739          32 :                             srt->sortop != typentry->gt_opr &&
     740          12 :                             !is_shippable(srt->sortop, OperatorRelationId,
     741             :                                           fpinfo))
     742           8 :                             return false;
     743             :                     }
     744             :                 }
     745             : 
     746             :                 /* Check aggregate filter */
     747         336 :                 if (!foreign_expr_walker((Node *) agg->aggfilter,
     748             :                                          glob_cxt, &inner_cxt))
     749           4 :                     return false;
     750             : 
     751             :                 /*
     752             :                  * If aggregate's input collation is not derived from a
     753             :                  * foreign Var, it can't be sent to remote.
     754             :                  */
     755         332 :                 if (agg->inputcollid == InvalidOid)
     756             :                      /* OK, inputs are all noncollatable */ ;
     757          48 :                 else if (inner_cxt.state != FDW_COLLATE_SAFE ||
     758          24 :                          agg->inputcollid != inner_cxt.collation)
     759           0 :                     return false;
     760             : 
     761             :                 /*
     762             :                  * Detect whether node is introducing a collation not derived
     763             :                  * from a foreign Var.  (If so, we just mark it unsafe for now
     764             :                  * rather than immediately returning false, since the parent
     765             :                  * node might not care.)
     766             :                  */
     767         332 :                 collation = agg->aggcollid;
     768         332 :                 if (collation == InvalidOid)
     769         330 :                     state = FDW_COLLATE_NONE;
     770           4 :                 else if (inner_cxt.state == FDW_COLLATE_SAFE &&
     771           2 :                          collation == inner_cxt.collation)
     772           2 :                     state = FDW_COLLATE_SAFE;
     773           0 :                 else if (collation == DEFAULT_COLLATION_OID)
     774           0 :                     state = FDW_COLLATE_NONE;
     775             :                 else
     776           0 :                     state = FDW_COLLATE_UNSAFE;
     777             :             }
     778         332 :             break;
     779             :         default:
     780             : 
     781             :             /*
     782             :              * If it's anything else, assume it's unsafe.  This list can be
     783             :              * expanded later, but don't forget to add deparse support below.
     784             :              */
     785          58 :             return false;
     786             :     }
     787             : 
     788             :     /*
     789             :      * If result type of given expression is not shippable, it can't be sent
     790             :      * to remote because it might have incompatible semantics on remote side.
     791             :      */
     792       11010 :     if (check_type && !is_shippable(exprType(node), TypeRelationId, fpinfo))
     793          50 :         return false;
     794             : 
     795             :     /*
     796             :      * Now, merge my collation information into my parent's state.
     797             :      */
     798       10960 :     if (state > outer_cxt->state)
     799             :     {
     800             :         /* Override previous parent state */
     801         530 :         outer_cxt->collation = collation;
     802         530 :         outer_cxt->state = state;
     803             :     }
     804       10430 :     else if (state == outer_cxt->state)
     805             :     {
     806             :         /* Merge, or detect error if there's a collation conflict */
     807       10370 :         switch (state)
     808             :         {
     809             :             case FDW_COLLATE_NONE:
     810             :                 /* Nothing + nothing is still nothing */
     811       10364 :                 break;
     812             :             case FDW_COLLATE_SAFE:
     813           4 :                 if (collation != outer_cxt->collation)
     814             :                 {
     815             :                     /*
     816             :                      * Non-default collation always beats default.
     817             :                      */
     818           0 :                     if (outer_cxt->collation == DEFAULT_COLLATION_OID)
     819             :                     {
     820             :                         /* Override previous parent state */
     821           0 :                         outer_cxt->collation = collation;
     822             :                     }
     823           0 :                     else if (collation != DEFAULT_COLLATION_OID)
     824             :                     {
     825             :                         /*
     826             :                          * Conflict; show state as indeterminate.  We don't
     827             :                          * want to "return false" right away, since parent
     828             :                          * node might not care about collation.
     829             :                          */
     830           0 :                         outer_cxt->state = FDW_COLLATE_UNSAFE;
     831             :                     }
     832             :                 }
     833           4 :                 break;
     834             :             case FDW_COLLATE_UNSAFE:
     835             :                 /* We're still conflicted ... */
     836           2 :                 break;
     837             :         }
     838             :     }
     839             : 
     840             :     /* It looks OK */
     841       10960 :     return true;
     842             : }
     843             : 
     844             : /*
     845             :  * Convert type OID + typmod info into a type name we can ship to the remote
     846             :  * server.  Someplace else had better have verified that this type name is
     847             :  * expected to be known on the remote end.
     848             :  *
     849             :  * This is almost just format_type_with_typemod(), except that if left to its
     850             :  * own devices, that function will make schema-qualification decisions based
     851             :  * on the local search_path, which is wrong.  We must schema-qualify all
     852             :  * type names that are not in pg_catalog.  We assume here that built-in types
     853             :  * are all in pg_catalog and need not be qualified; otherwise, qualify.
     854             :  */
     855             : static char *
     856         494 : deparse_type_name(Oid type_oid, int32 typemod)
     857             : {
     858         494 :     bits16      flags = FORMAT_TYPE_TYPEMOD_GIVEN;
     859             : 
     860         494 :     if (!is_builtin(type_oid))
     861           0 :         flags |= FORMAT_TYPE_FORCE_QUALIFY;
     862             : 
     863         494 :     return format_type_extended(type_oid, typemod, flags);
     864             : }
     865             : 
     866             : /*
     867             :  * Build the targetlist for given relation to be deparsed as SELECT clause.
     868             :  *
     869             :  * The output targetlist contains the columns that need to be fetched from the
     870             :  * foreign server for the given relation.  If foreignrel is an upper relation,
     871             :  * then the output targetlist can also contain expressions to be evaluated on
     872             :  * foreign server.
     873             :  */
     874             : List *
     875         956 : build_tlist_to_deparse(RelOptInfo *foreignrel)
     876             : {
     877         956 :     List       *tlist = NIL;
     878         956 :     PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) foreignrel->fdw_private;
     879             :     ListCell   *lc;
     880             : 
     881             :     /*
     882             :      * For an upper relation, we have already built the target list while
     883             :      * checking shippability, so just return that.
     884             :      */
     885         956 :     if (IS_UPPER_REL(foreignrel))
     886         246 :         return fpinfo->grouped_tlist;
     887             : 
     888             :     /*
     889             :      * We require columns specified in foreignrel->reltarget->exprs and those
     890             :      * required for evaluating the local conditions.
     891             :      */
     892         710 :     tlist = add_to_flat_tlist(tlist,
     893         710 :                               pull_var_clause((Node *) foreignrel->reltarget->exprs,
     894             :                                               PVC_RECURSE_PLACEHOLDERS));
     895         746 :     foreach(lc, fpinfo->local_conds)
     896             :     {
     897          36 :         RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc);
     898             : 
     899          36 :         tlist = add_to_flat_tlist(tlist,
     900          36 :                                   pull_var_clause((Node *) rinfo->clause,
     901             :                                                   PVC_RECURSE_PLACEHOLDERS));
     902             :     }
     903             : 
     904         710 :     return tlist;
     905             : }
     906             : 
     907             : /*
     908             :  * Deparse SELECT statement for given relation into buf.
     909             :  *
     910             :  * tlist contains the list of desired columns to be fetched from foreign server.
     911             :  * For a base relation fpinfo->attrs_used is used to construct SELECT clause,
     912             :  * hence the tlist is ignored for a base relation.
     913             :  *
     914             :  * remote_conds is the list of conditions to be deparsed into the WHERE clause
     915             :  * (or, in the case of upper relations, into the HAVING clause).
     916             :  *
     917             :  * If params_list is not NULL, it receives a list of Params and other-relation
     918             :  * Vars used in the clauses; these values must be transmitted to the remote
     919             :  * server as parameter values.
     920             :  *
     921             :  * If params_list is NULL, we're generating the query for EXPLAIN purposes,
     922             :  * so Params and other-relation Vars should be replaced by dummy values.
     923             :  *
     924             :  * pathkeys is the list of pathkeys to order the result by.
     925             :  *
     926             :  * is_subquery is the flag to indicate whether to deparse the specified
     927             :  * relation as a subquery.
     928             :  *
     929             :  * List of columns selected is returned in retrieved_attrs.
     930             :  */
     931             : void
     932        3048 : deparseSelectStmtForRel(StringInfo buf, PlannerInfo *root, RelOptInfo *rel,
     933             :                         List *tlist, List *remote_conds, List *pathkeys,
     934             :                         bool is_subquery, List **retrieved_attrs,
     935             :                         List **params_list)
     936             : {
     937             :     deparse_expr_cxt context;
     938        3048 :     PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) rel->fdw_private;
     939             :     List       *quals;
     940             : 
     941             :     /*
     942             :      * We handle relations for foreign tables, joins between those and upper
     943             :      * relations.
     944             :      */
     945             :     Assert(IS_JOIN_REL(rel) || IS_SIMPLE_REL(rel) || IS_UPPER_REL(rel));
     946             : 
     947             :     /* Fill portions of context common to upper, join and base relation */
     948        3048 :     context.buf = buf;
     949        3048 :     context.root = root;
     950        3048 :     context.foreignrel = rel;
     951        3048 :     context.scanrel = IS_UPPER_REL(rel) ? fpinfo->outerrel : rel;
     952        3048 :     context.params_list = params_list;
     953             : 
     954             :     /* Construct SELECT clause */
     955        3048 :     deparseSelectSql(tlist, is_subquery, retrieved_attrs, &context);
     956             : 
     957             :     /*
     958             :      * For upper relations, the WHERE clause is built from the remote
     959             :      * conditions of the underlying scan relation; otherwise, we can use the
     960             :      * supplied list of remote conditions directly.
     961             :      */
     962        3048 :     if (IS_UPPER_REL(rel))
     963         246 :     {
     964             :         PgFdwRelationInfo *ofpinfo;
     965             : 
     966         246 :         ofpinfo = (PgFdwRelationInfo *) fpinfo->outerrel->fdw_private;
     967         246 :         quals = ofpinfo->remote_conds;
     968             :     }
     969             :     else
     970        2802 :         quals = remote_conds;
     971             : 
     972             :     /* Construct FROM and WHERE clauses */
     973        3048 :     deparseFromExpr(quals, &context);
     974             : 
     975        3048 :     if (IS_UPPER_REL(rel))
     976             :     {
     977             :         /* Append GROUP BY clause */
     978         246 :         appendGroupByClause(tlist, &context);
     979             : 
     980             :         /* Append HAVING clause */
     981         246 :         if (remote_conds)
     982             :         {
     983          32 :             appendStringInfoString(buf, " HAVING ");
     984          32 :             appendConditions(remote_conds, &context);
     985             :         }
     986             :     }
     987             : 
     988             :     /* Add ORDER BY clause if we found any useful pathkeys */
     989        3048 :     if (pathkeys)
     990         776 :         appendOrderByClause(pathkeys, &context);
     991             : 
     992             :     /* Add any necessary FOR UPDATE/SHARE. */
     993        3048 :     deparseLockingClause(&context);
     994        3048 : }
     995             : 
     996             : /*
     997             :  * Construct a simple SELECT statement that retrieves desired columns
     998             :  * of the specified foreign table, and append it to "buf".  The output
     999             :  * contains just "SELECT ... ".
    1000             :  *
    1001             :  * We also create an integer List of the columns being retrieved, which is
    1002             :  * returned to *retrieved_attrs, unless we deparse the specified relation
    1003             :  * as a subquery.
    1004             :  *
    1005             :  * tlist is the list of desired columns.  is_subquery is the flag to
    1006             :  * indicate whether to deparse the specified relation as a subquery.
    1007             :  * Read prologue of deparseSelectStmtForRel() for details.
    1008             :  */
    1009             : static void
    1010        3048 : deparseSelectSql(List *tlist, bool is_subquery, List **retrieved_attrs,
    1011             :                  deparse_expr_cxt *context)
    1012             : {
    1013        3048 :     StringInfo  buf = context->buf;
    1014        3048 :     RelOptInfo *foreignrel = context->foreignrel;
    1015        3048 :     PlannerInfo *root = context->root;
    1016        3048 :     PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) foreignrel->fdw_private;
    1017             : 
    1018             :     /*
    1019             :      * Construct SELECT list
    1020             :      */
    1021        3048 :     appendStringInfoString(buf, "SELECT ");
    1022             : 
    1023        3048 :     if (is_subquery)
    1024             :     {
    1025             :         /*
    1026             :          * For a relation that is deparsed as a subquery, emit expressions
    1027             :          * specified in the relation's reltarget.  Note that since this is for
    1028             :          * the subquery, no need to care about *retrieved_attrs.
    1029             :          */
    1030          56 :         deparseSubqueryTargetList(context);
    1031             :     }
    1032        2992 :     else if (IS_JOIN_REL(foreignrel) || IS_UPPER_REL(foreignrel))
    1033             :     {
    1034             :         /*
    1035             :          * For a join or upper relation the input tlist gives the list of
    1036             :          * columns required to be fetched from the foreign server.
    1037             :          */
    1038         956 :         deparseExplicitTargetList(tlist, false, retrieved_attrs, context);
    1039             :     }
    1040             :     else
    1041             :     {
    1042             :         /*
    1043             :          * For a base relation fpinfo->attrs_used gives the list of columns
    1044             :          * required to be fetched from the foreign server.
    1045             :          */
    1046        2036 :         RangeTblEntry *rte = planner_rt_fetch(foreignrel->relid, root);
    1047             : 
    1048             :         /*
    1049             :          * Core code already has some lock on each rel being planned, so we
    1050             :          * can use NoLock here.
    1051             :          */
    1052        2036 :         Relation    rel = heap_open(rte->relid, NoLock);
    1053             : 
    1054        2036 :         deparseTargetList(buf, rte, foreignrel->relid, rel, false,
    1055             :                           fpinfo->attrs_used, false, retrieved_attrs);
    1056        2036 :         heap_close(rel, NoLock);
    1057             :     }
    1058        3048 : }
    1059             : 
    1060             : /*
    1061             :  * Construct a FROM clause and, if needed, a WHERE clause, and append those to
    1062             :  * "buf".
    1063             :  *
    1064             :  * quals is the list of clauses to be included in the WHERE clause.
    1065             :  * (These may or may not include RestrictInfo decoration.)
    1066             :  */
    1067             : static void
    1068        3048 : deparseFromExpr(List *quals, deparse_expr_cxt *context)
    1069             : {
    1070        3048 :     StringInfo  buf = context->buf;
    1071        3048 :     RelOptInfo *scanrel = context->scanrel;
    1072             : 
    1073             :     /* For upper relations, scanrel must be either a joinrel or a baserel */
    1074             :     Assert(!IS_UPPER_REL(context->foreignrel) ||
    1075             :            IS_JOIN_REL(scanrel) || IS_SIMPLE_REL(scanrel));
    1076             : 
    1077             :     /* Construct FROM clause */
    1078        3048 :     appendStringInfoString(buf, " FROM ");
    1079        6096 :     deparseFromExprForRel(buf, context->root, scanrel,
    1080        3048 :                           (bms_membership(scanrel->relids) == BMS_MULTIPLE),
    1081             :                           (Index) 0, NULL, context->params_list);
    1082             : 
    1083             :     /* Construct WHERE clause */
    1084        3048 :     if (quals != NIL)
    1085             :     {
    1086        1194 :         appendStringInfoString(buf, " WHERE ");
    1087        1194 :         appendConditions(quals, context);
    1088             :     }
    1089        3048 : }
    1090             : 
    1091             : /*
    1092             :  * Emit a target list that retrieves the columns specified in attrs_used.
    1093             :  * This is used for both SELECT and RETURNING targetlists; the is_returning
    1094             :  * parameter is true only for a RETURNING targetlist.
    1095             :  *
    1096             :  * The tlist text is appended to buf, and we also create an integer List
    1097             :  * of the columns being retrieved, which is returned to *retrieved_attrs.
    1098             :  *
    1099             :  * If qualify_col is true, add relation alias before the column name.
    1100             :  */
    1101             : static void
    1102        2538 : deparseTargetList(StringInfo buf,
    1103             :                   RangeTblEntry *rte,
    1104             :                   Index rtindex,
    1105             :                   Relation rel,
    1106             :                   bool is_returning,
    1107             :                   Bitmapset *attrs_used,
    1108             :                   bool qualify_col,
    1109             :                   List **retrieved_attrs)
    1110             : {
    1111        2538 :     TupleDesc   tupdesc = RelationGetDescr(rel);
    1112             :     bool        have_wholerow;
    1113             :     bool        first;
    1114             :     int         i;
    1115             : 
    1116        2538 :     *retrieved_attrs = NIL;
    1117             : 
    1118             :     /* If there's a whole-row reference, we'll need all the columns. */
    1119        2538 :     have_wholerow = bms_is_member(0 - FirstLowInvalidHeapAttributeNumber,
    1120             :                                   attrs_used);
    1121             : 
    1122        2538 :     first = true;
    1123       18626 :     for (i = 1; i <= tupdesc->natts; i++)
    1124             :     {
    1125       16088 :         Form_pg_attribute attr = TupleDescAttr(tupdesc, i - 1);
    1126             : 
    1127             :         /* Ignore dropped attributes. */
    1128       16088 :         if (attr->attisdropped)
    1129        1470 :             continue;
    1130             : 
    1131       25516 :         if (have_wholerow ||
    1132       10898 :             bms_is_member(i - FirstLowInvalidHeapAttributeNumber,
    1133             :                           attrs_used))
    1134             :         {
    1135        8400 :             if (!first)
    1136        5966 :                 appendStringInfoString(buf, ", ");
    1137        2434 :             else if (is_returning)
    1138         150 :                 appendStringInfoString(buf, " RETURNING ");
    1139        8400 :             first = false;
    1140             : 
    1141        8400 :             deparseColumnRef(buf, rtindex, i, rte, qualify_col);
    1142             : 
    1143        8400 :             *retrieved_attrs = lappend_int(*retrieved_attrs, i);
    1144             :         }
    1145             :     }
    1146             : 
    1147             :     /*
    1148             :      * Add ctid and oid if needed.  We currently don't support retrieving any
    1149             :      * other system columns.
    1150             :      */
    1151        2538 :     if (bms_is_member(SelfItemPointerAttributeNumber - FirstLowInvalidHeapAttributeNumber,
    1152             :                       attrs_used))
    1153             :     {
    1154         424 :         if (!first)
    1155         342 :             appendStringInfoString(buf, ", ");
    1156          82 :         else if (is_returning)
    1157           0 :             appendStringInfoString(buf, " RETURNING ");
    1158         424 :         first = false;
    1159             : 
    1160         424 :         if (qualify_col)
    1161           0 :             ADD_REL_QUALIFIER(buf, rtindex);
    1162         424 :         appendStringInfoString(buf, "ctid");
    1163             : 
    1164         424 :         *retrieved_attrs = lappend_int(*retrieved_attrs,
    1165             :                                        SelfItemPointerAttributeNumber);
    1166             :     }
    1167        2538 :     if (bms_is_member(ObjectIdAttributeNumber - FirstLowInvalidHeapAttributeNumber,
    1168             :                       attrs_used))
    1169             :     {
    1170           4 :         if (!first)
    1171           4 :             appendStringInfoString(buf, ", ");
    1172           0 :         else if (is_returning)
    1173           0 :             appendStringInfoString(buf, " RETURNING ");
    1174           4 :         first = false;
    1175             : 
    1176           4 :         if (qualify_col)
    1177           0 :             ADD_REL_QUALIFIER(buf, rtindex);
    1178           4 :         appendStringInfoString(buf, "oid");
    1179             : 
    1180           4 :         *retrieved_attrs = lappend_int(*retrieved_attrs,
    1181             :                                        ObjectIdAttributeNumber);
    1182             :     }
    1183             : 
    1184             :     /* Don't generate bad syntax if no undropped columns */
    1185        2538 :     if (first && !is_returning)
    1186          10 :         appendStringInfoString(buf, "NULL");
    1187        2538 : }
    1188             : 
    1189             : /*
    1190             :  * Deparse the appropriate locking clause (FOR UPDATE or FOR SHARE) for a
    1191             :  * given relation (context->scanrel).
    1192             :  */
    1193             : static void
    1194        3048 : deparseLockingClause(deparse_expr_cxt *context)
    1195             : {
    1196        3048 :     StringInfo  buf = context->buf;
    1197        3048 :     PlannerInfo *root = context->root;
    1198        3048 :     RelOptInfo *rel = context->scanrel;
    1199        3048 :     PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) rel->fdw_private;
    1200        3048 :     int         relid = -1;
    1201             : 
    1202       10070 :     while ((relid = bms_next_member(rel->relids, relid)) >= 0)
    1203             :     {
    1204             :         /*
    1205             :          * Ignore relation if it appears in a lower subquery.  Locking clause
    1206             :          * for such a relation is included in the subquery if necessary.
    1207             :          */
    1208        3974 :         if (bms_is_member(relid, fpinfo->lower_subquery_rels))
    1209          64 :             continue;
    1210             : 
    1211             :         /*
    1212             :          * Add FOR UPDATE/SHARE if appropriate.  We apply locking during the
    1213             :          * initial row fetch, rather than later on as is done for local
    1214             :          * tables. The extra roundtrips involved in trying to duplicate the
    1215             :          * local semantics exactly don't seem worthwhile (see also comments
    1216             :          * for RowMarkType).
    1217             :          *
    1218             :          * Note: because we actually run the query as a cursor, this assumes
    1219             :          * that DECLARE CURSOR ... FOR UPDATE is supported, which it isn't
    1220             :          * before 8.3.
    1221             :          */
    1222        4336 :         if (relid == root->parse->resultRelation &&
    1223         614 :             (root->parse->commandType == CMD_UPDATE ||
    1224         188 :              root->parse->commandType == CMD_DELETE))
    1225             :         {
    1226             :             /* Relation is UPDATE/DELETE target, so use FOR UPDATE */
    1227         426 :             appendStringInfoString(buf, " FOR UPDATE");
    1228             : 
    1229             :             /* Add the relation alias if we are here for a join relation */
    1230         852 :             if (IS_JOIN_REL(rel))
    1231          84 :                 appendStringInfo(buf, " OF %s%d", REL_ALIAS_PREFIX, relid);
    1232             :         }
    1233             :         else
    1234             :         {
    1235        3484 :             PlanRowMark *rc = get_plan_rowmark(root->rowMarks, relid);
    1236             : 
    1237        3484 :             if (rc)
    1238             :             {
    1239             :                 /*
    1240             :                  * Relation is specified as a FOR UPDATE/SHARE target, so
    1241             :                  * handle that.  (But we could also see LCS_NONE, meaning this
    1242             :                  * isn't a target relation after all.)
    1243             :                  *
    1244             :                  * For now, just ignore any [NO] KEY specification, since (a)
    1245             :                  * it's not clear what that means for a remote table that we
    1246             :                  * don't have complete information about, and (b) it wouldn't
    1247             :                  * work anyway on older remote servers.  Likewise, we don't
    1248             :                  * worry about NOWAIT.
    1249             :                  */
    1250         572 :                 switch (rc->strength)
    1251             :                 {
    1252             :                     case LCS_NONE:
    1253             :                         /* No locking needed */
    1254         292 :                         break;
    1255             :                     case LCS_FORKEYSHARE:
    1256             :                     case LCS_FORSHARE:
    1257          68 :                         appendStringInfoString(buf, " FOR SHARE");
    1258          68 :                         break;
    1259             :                     case LCS_FORNOKEYUPDATE:
    1260             :                     case LCS_FORUPDATE:
    1261         212 :                         appendStringInfoString(buf, " FOR UPDATE");
    1262         212 :                         break;
    1263             :                 }
    1264             : 
    1265             :                 /* Add the relation alias if we are here for a join relation */
    1266         880 :                 if (bms_membership(rel->relids) == BMS_MULTIPLE &&
    1267         308 :                     rc->strength != LCS_NONE)
    1268         168 :                     appendStringInfo(buf, " OF %s%d", REL_ALIAS_PREFIX, relid);
    1269             :             }
    1270             :         }
    1271             :     }
    1272        3048 : }
    1273             : 
    1274             : /*
    1275             :  * Deparse conditions from the provided list and append them to buf.
    1276             :  *
    1277             :  * The conditions in the list are assumed to be ANDed. This function is used to
    1278             :  * deparse WHERE clauses, JOIN .. ON clauses and HAVING clauses.
    1279             :  *
    1280             :  * Depending on the caller, the list elements might be either RestrictInfos
    1281             :  * or bare clauses.
    1282             :  */
    1283             : static void
    1284        2210 : appendConditions(List *exprs, deparse_expr_cxt *context)
    1285             : {
    1286             :     int         nestlevel;
    1287             :     ListCell   *lc;
    1288        2210 :     bool        is_first = true;
    1289        2210 :     StringInfo  buf = context->buf;
    1290             : 
    1291             :     /* Make sure any constants in the exprs are printed portably */
    1292        2210 :     nestlevel = set_transmission_modes();
    1293             : 
    1294        5058 :     foreach(lc, exprs)
    1295             :     {
    1296        2848 :         Expr       *expr = (Expr *) lfirst(lc);
    1297             : 
    1298             :         /* Extract clause from RestrictInfo, if required */
    1299        2848 :         if (IsA(expr, RestrictInfo))
    1300        2340 :             expr = ((RestrictInfo *) expr)->clause;
    1301             : 
    1302             :         /* Connect expressions with "AND" and parenthesize each condition. */
    1303        2848 :         if (!is_first)
    1304         638 :             appendStringInfoString(buf, " AND ");
    1305             : 
    1306        2848 :         appendStringInfoChar(buf, '(');
    1307        2848 :         deparseExpr(expr, context);
    1308        2848 :         appendStringInfoChar(buf, ')');
    1309             : 
    1310        2848 :         is_first = false;
    1311             :     }
    1312             : 
    1313        2210 :     reset_transmission_modes(nestlevel);
    1314        2210 : }
    1315             : 
    1316             : /* Output join name for given join type */
    1317             : const char *
    1318        1350 : get_jointype_name(JoinType jointype)
    1319             : {
    1320        1350 :     switch (jointype)
    1321             :     {
    1322             :         case JOIN_INNER:
    1323         770 :             return "INNER";
    1324             : 
    1325             :         case JOIN_LEFT:
    1326         364 :             return "LEFT";
    1327             : 
    1328             :         case JOIN_RIGHT:
    1329           0 :             return "RIGHT";
    1330             : 
    1331             :         case JOIN_FULL:
    1332         216 :             return "FULL";
    1333             : 
    1334             :         default:
    1335             :             /* Shouldn't come here, but protect from buggy code. */
    1336           0 :             elog(ERROR, "unsupported join type %d", jointype);
    1337             :     }
    1338             : 
    1339             :     /* Keep compiler happy */
    1340             :     return NULL;
    1341             : }
    1342             : 
    1343             : /*
    1344             :  * Deparse given targetlist and append it to context->buf.
    1345             :  *
    1346             :  * tlist is list of TargetEntry's which in turn contain Var nodes.
    1347             :  *
    1348             :  * retrieved_attrs is the list of continuously increasing integers starting
    1349             :  * from 1. It has same number of entries as tlist.
    1350             :  *
    1351             :  * This is used for both SELECT and RETURNING targetlists; the is_returning
    1352             :  * parameter is true only for a RETURNING targetlist.
    1353             :  */
    1354             : static void
    1355         980 : deparseExplicitTargetList(List *tlist,
    1356             :                           bool is_returning,
    1357             :                           List **retrieved_attrs,
    1358             :                           deparse_expr_cxt *context)
    1359             : {
    1360             :     ListCell   *lc;
    1361         980 :     StringInfo  buf = context->buf;
    1362         980 :     int         i = 0;
    1363             : 
    1364         980 :     *retrieved_attrs = NIL;
    1365             : 
    1366        4752 :     foreach(lc, tlist)
    1367             :     {
    1368        3772 :         TargetEntry *tle = lfirst_node(TargetEntry, lc);
    1369             : 
    1370        3772 :         if (i > 0)
    1371        2808 :             appendStringInfoString(buf, ", ");
    1372         964 :         else if (is_returning)
    1373          12 :             appendStringInfoString(buf, " RETURNING ");
    1374             : 
    1375        3772 :         deparseExpr((Expr *) tle->expr, context);
    1376             : 
    1377        3772 :         *retrieved_attrs = lappend_int(*retrieved_attrs, i + 1);
    1378        3772 :         i++;
    1379             :     }
    1380             : 
    1381         980 :     if (i == 0 && !is_returning)
    1382           4 :         appendStringInfoString(buf, "NULL");
    1383         980 : }
    1384             : 
    1385             : /*
    1386             :  * Emit expressions specified in the given relation's reltarget.
    1387             :  *
    1388             :  * This is used for deparsing the given relation as a subquery.
    1389             :  */
    1390             : static void
    1391          56 : deparseSubqueryTargetList(deparse_expr_cxt *context)
    1392             : {
    1393          56 :     StringInfo  buf = context->buf;
    1394          56 :     RelOptInfo *foreignrel = context->foreignrel;
    1395             :     bool        first;
    1396             :     ListCell   *lc;
    1397             : 
    1398             :     /* Should only be called in these cases. */
    1399             :     Assert(IS_SIMPLE_REL(foreignrel) || IS_JOIN_REL(foreignrel));
    1400             : 
    1401          56 :     first = true;
    1402         120 :     foreach(lc, foreignrel->reltarget->exprs)
    1403             :     {
    1404          64 :         Node       *node = (Node *) lfirst(lc);
    1405             : 
    1406          64 :         if (!first)
    1407          16 :             appendStringInfoString(buf, ", ");
    1408          64 :         first = false;
    1409             : 
    1410          64 :         deparseExpr((Expr *) node, context);
    1411             :     }
    1412             : 
    1413             :     /* Don't generate bad syntax if no expressions */
    1414          56 :     if (first)
    1415           8 :         appendStringInfoString(buf, "NULL");
    1416          56 : }
    1417             : 
    1418             : /*
    1419             :  * Construct FROM clause for given relation
    1420             :  *
    1421             :  * The function constructs ... JOIN ... ON ... for join relation. For a base
    1422             :  * relation it just returns schema-qualified tablename, with the appropriate
    1423             :  * alias if so requested.
    1424             :  *
    1425             :  * 'ignore_rel' is either zero or the RT index of a target relation.  In the
    1426             :  * latter case the function constructs FROM clause of UPDATE or USING clause
    1427             :  * of DELETE; it deparses the join relation as if the relation never contained
    1428             :  * the target relation, and creates a List of conditions to be deparsed into
    1429             :  * the top-level WHERE clause, which is returned to *ignore_conds.
    1430             :  */
    1431             : static void
    1432        4892 : deparseFromExprForRel(StringInfo buf, PlannerInfo *root, RelOptInfo *foreignrel,
    1433             :                       bool use_alias, Index ignore_rel, List **ignore_conds,
    1434             :                       List **params_list)
    1435             : {
    1436        4892 :     PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) foreignrel->fdw_private;
    1437             : 
    1438        4892 :     if (IS_JOIN_REL(foreignrel))
    1439         926 :     {
    1440             :         StringInfoData join_sql_o;
    1441             :         StringInfoData join_sql_i;
    1442         950 :         RelOptInfo *outerrel = fpinfo->outerrel;
    1443         950 :         RelOptInfo *innerrel = fpinfo->innerrel;
    1444         950 :         bool        outerrel_is_target = false;
    1445         950 :         bool        innerrel_is_target = false;
    1446             : 
    1447         950 :         if (ignore_rel > 0 && bms_is_member(ignore_rel, foreignrel->relids))
    1448             :         {
    1449             :             /*
    1450             :              * If this is an inner join, add joinclauses to *ignore_conds and
    1451             :              * set it to empty so that those can be deparsed into the WHERE
    1452             :              * clause.  Note that since the target relation can never be
    1453             :              * within the nullable side of an outer join, those could safely
    1454             :              * be pulled up into the WHERE clause (see foreign_join_ok()).
    1455             :              * Note also that since the target relation is only inner-joined
    1456             :              * to any other relation in the query, all conditions in the join
    1457             :              * tree mentioning the target relation could be deparsed into the
    1458             :              * WHERE clause by doing this recursively.
    1459             :              */
    1460          32 :             if (fpinfo->jointype == JOIN_INNER)
    1461             :             {
    1462          28 :                 *ignore_conds = list_concat(*ignore_conds,
    1463          28 :                                             list_copy(fpinfo->joinclauses));
    1464          28 :                 fpinfo->joinclauses = NIL;
    1465             :             }
    1466             : 
    1467             :             /*
    1468             :              * Check if either of the input relations is the target relation.
    1469             :              */
    1470          32 :             if (outerrel->relid == ignore_rel)
    1471          24 :                 outerrel_is_target = true;
    1472           8 :             else if (innerrel->relid == ignore_rel)
    1473           0 :                 innerrel_is_target = true;
    1474             :         }
    1475             : 
    1476             :         /* Deparse outer relation if not the target relation. */
    1477         950 :         if (!outerrel_is_target)
    1478             :         {
    1479         926 :             initStringInfo(&join_sql_o);
    1480         926 :             deparseRangeTblRef(&join_sql_o, root, outerrel,
    1481         926 :                                fpinfo->make_outerrel_subquery,
    1482             :                                ignore_rel, ignore_conds, params_list);
    1483             : 
    1484             :             /*
    1485             :              * If inner relation is the target relation, skip deparsing it.
    1486             :              * Note that since the join of the target relation with any other
    1487             :              * relation in the query is an inner join and can never be within
    1488             :              * the nullable side of an outer join, the join could be
    1489             :              * interchanged with higher-level joins (cf. identity 1 on outer
    1490             :              * join reordering shown in src/backend/optimizer/README), which
    1491             :              * means it's safe to skip the target-relation deparsing here.
    1492             :              */
    1493         926 :             if (innerrel_is_target)
    1494             :             {
    1495             :                 Assert(fpinfo->jointype == JOIN_INNER);
    1496             :                 Assert(fpinfo->joinclauses == NIL);
    1497           0 :                 appendStringInfo(buf, "%s", join_sql_o.data);
    1498           0 :                 return;
    1499             :             }
    1500             :         }
    1501             : 
    1502             :         /* Deparse inner relation if not the target relation. */
    1503         950 :         if (!innerrel_is_target)
    1504             :         {
    1505         950 :             initStringInfo(&join_sql_i);
    1506         950 :             deparseRangeTblRef(&join_sql_i, root, innerrel,
    1507         950 :                                fpinfo->make_innerrel_subquery,
    1508             :                                ignore_rel, ignore_conds, params_list);
    1509             : 
    1510             :             /*
    1511             :              * If outer relation is the target relation, skip deparsing it.
    1512             :              * See the above note about safety.
    1513             :              */
    1514         950 :             if (outerrel_is_target)
    1515             :             {
    1516             :                 Assert(fpinfo->jointype == JOIN_INNER);
    1517             :                 Assert(fpinfo->joinclauses == NIL);
    1518          24 :                 appendStringInfo(buf, "%s", join_sql_i.data);
    1519          24 :                 return;
    1520             :             }
    1521             :         }
    1522             : 
    1523             :         /* Neither of the relations is the target relation. */
    1524             :         Assert(!outerrel_is_target && !innerrel_is_target);
    1525             : 
    1526             :         /*
    1527             :          * For a join relation FROM clause entry is deparsed as
    1528             :          *
    1529             :          * ((outer relation) <join type> (inner relation) ON (joinclauses))
    1530             :          */
    1531         926 :         appendStringInfo(buf, "(%s %s JOIN %s ON ", join_sql_o.data,
    1532             :                          get_jointype_name(fpinfo->jointype), join_sql_i.data);
    1533             : 
    1534             :         /* Append join clause; (TRUE) if no join clause */
    1535         926 :         if (fpinfo->joinclauses)
    1536             :         {
    1537             :             deparse_expr_cxt context;
    1538             : 
    1539         902 :             context.buf = buf;
    1540         902 :             context.foreignrel = foreignrel;
    1541         902 :             context.scanrel = foreignrel;
    1542         902 :             context.root = root;
    1543         902 :             context.params_list = params_list;
    1544             : 
    1545         902 :             appendStringInfoChar(buf, '(');
    1546         902 :             appendConditions(fpinfo->joinclauses, &context);
    1547         902 :             appendStringInfoChar(buf, ')');
    1548             :         }
    1549             :         else
    1550          24 :             appendStringInfoString(buf, "(TRUE)");
    1551             : 
    1552             :         /* End the FROM clause entry. */
    1553         926 :         appendStringInfoChar(buf, ')');
    1554             :     }
    1555             :     else
    1556             :     {
    1557        3942 :         RangeTblEntry *rte = planner_rt_fetch(foreignrel->relid, root);
    1558             : 
    1559             :         /*
    1560             :          * Core code already has some lock on each rel being planned, so we
    1561             :          * can use NoLock here.
    1562             :          */
    1563        3942 :         Relation    rel = heap_open(rte->relid, NoLock);
    1564             : 
    1565        3942 :         deparseRelation(buf, rel);
    1566             : 
    1567             :         /*
    1568             :          * Add a unique alias to avoid any conflict in relation names due to
    1569             :          * pulled up subqueries in the query being built for a pushed down
    1570             :          * join.
    1571             :          */
    1572        3942 :         if (use_alias)
    1573        1644 :             appendStringInfo(buf, " %s%d", REL_ALIAS_PREFIX, foreignrel->relid);
    1574             : 
    1575        3942 :         heap_close(rel, NoLock);
    1576             :     }
    1577             : }
    1578             : 
    1579             : /*
    1580             :  * Append FROM clause entry for the given relation into buf.
    1581             :  */
    1582             : static void
    1583        1876 : deparseRangeTblRef(StringInfo buf, PlannerInfo *root, RelOptInfo *foreignrel,
    1584             :                    bool make_subquery, Index ignore_rel, List **ignore_conds,
    1585             :                    List **params_list)
    1586             : {
    1587        1876 :     PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) foreignrel->fdw_private;
    1588             : 
    1589             :     /* Should only be called in these cases. */
    1590             :     Assert(IS_SIMPLE_REL(foreignrel) || IS_JOIN_REL(foreignrel));
    1591             : 
    1592             :     Assert(fpinfo->local_conds == NIL);
    1593             : 
    1594             :     /* If make_subquery is true, deparse the relation as a subquery. */
    1595        1876 :     if (make_subquery)
    1596             :     {
    1597             :         List       *retrieved_attrs;
    1598             :         int         ncols;
    1599             : 
    1600             :         /*
    1601             :          * The given relation shouldn't contain the target relation, because
    1602             :          * this should only happen for input relations for a full join, and
    1603             :          * such relations can never contain an UPDATE/DELETE target.
    1604             :          */
    1605             :         Assert(ignore_rel == 0 ||
    1606             :                !bms_is_member(ignore_rel, foreignrel->relids));
    1607             : 
    1608             :         /* Deparse the subquery representing the relation. */
    1609          56 :         appendStringInfoChar(buf, '(');
    1610          56 :         deparseSelectStmtForRel(buf, root, foreignrel, NIL,
    1611             :                                 fpinfo->remote_conds, NIL, true,
    1612             :                                 &retrieved_attrs, params_list);
    1613          56 :         appendStringInfoChar(buf, ')');
    1614             : 
    1615             :         /* Append the relation alias. */
    1616          56 :         appendStringInfo(buf, " %s%d", SUBQUERY_REL_ALIAS_PREFIX,
    1617             :                          fpinfo->relation_index);
    1618             : 
    1619             :         /*
    1620             :          * Append the column aliases if needed.  Note that the subquery emits
    1621             :          * expressions specified in the relation's reltarget (see
    1622             :          * deparseSubqueryTargetList).
    1623             :          */
    1624          56 :         ncols = list_length(foreignrel->reltarget->exprs);
    1625          56 :         if (ncols > 0)
    1626             :         {
    1627             :             int         i;
    1628             : 
    1629          48 :             appendStringInfoChar(buf, '(');
    1630         112 :             for (i = 1; i <= ncols; i++)
    1631             :             {
    1632          64 :                 if (i > 1)
    1633          16 :                     appendStringInfoString(buf, ", ");
    1634             : 
    1635          64 :                 appendStringInfo(buf, "%s%d", SUBQUERY_COL_ALIAS_PREFIX, i);
    1636             :             }
    1637          48 :             appendStringInfoChar(buf, ')');
    1638             :         }
    1639             :     }
    1640             :     else
    1641        1820 :         deparseFromExprForRel(buf, root, foreignrel, true, ignore_rel,
    1642             :                               ignore_conds, params_list);
    1643        1876 : }
    1644             : 
    1645             : /*
    1646             :  * deparse remote INSERT statement
    1647             :  *
    1648             :  * The statement text is appended to buf, and we also create an integer List
    1649             :  * of the columns being retrieved by WITH CHECK OPTION or RETURNING (if any),
    1650             :  * which is returned to *retrieved_attrs.
    1651             :  */
    1652             : void
    1653         156 : deparseInsertSql(StringInfo buf, RangeTblEntry *rte,
    1654             :                  Index rtindex, Relation rel,
    1655             :                  List *targetAttrs, bool doNothing,
    1656             :                  List *withCheckOptionList, List *returningList,
    1657             :                  List **retrieved_attrs)
    1658             : {
    1659             :     AttrNumber  pindex;
    1660             :     bool        first;
    1661             :     ListCell   *lc;
    1662             : 
    1663         156 :     appendStringInfoString(buf, "INSERT INTO ");
    1664         156 :     deparseRelation(buf, rel);
    1665             : 
    1666         156 :     if (targetAttrs)
    1667             :     {
    1668         156 :         appendStringInfoChar(buf, '(');
    1669             : 
    1670         156 :         first = true;
    1671         682 :         foreach(lc, targetAttrs)
    1672             :         {
    1673         526 :             int         attnum = lfirst_int(lc);
    1674             : 
    1675         526 :             if (!first)
    1676         370 :                 appendStringInfoString(buf, ", ");
    1677         526 :             first = false;
    1678             : 
    1679         526 :             deparseColumnRef(buf, rtindex, attnum, rte, false);
    1680             :         }
    1681             : 
    1682         156 :         appendStringInfoString(buf, ") VALUES (");
    1683             : 
    1684         156 :         pindex = 1;
    1685         156 :         first = true;
    1686         682 :         foreach(lc, targetAttrs)
    1687             :         {
    1688         526 :             if (!first)
    1689         370 :                 appendStringInfoString(buf, ", ");
    1690         526 :             first = false;
    1691             : 
    1692         526 :             appendStringInfo(buf, "$%d", pindex);
    1693         526 :             pindex++;
    1694             :         }
    1695             : 
    1696         156 :         appendStringInfoChar(buf, ')');
    1697             :     }
    1698             :     else
    1699           0 :         appendStringInfoString(buf, " DEFAULT VALUES");
    1700             : 
    1701         156 :     if (doNothing)
    1702           6 :         appendStringInfoString(buf, " ON CONFLICT DO NOTHING");
    1703             : 
    1704         156 :     deparseReturningList(buf, rte, rtindex, rel,
    1705         156 :                          rel->trigdesc && rel->trigdesc->trig_insert_after_row,
    1706             :                          withCheckOptionList, returningList, retrieved_attrs);
    1707         156 : }
    1708             : 
    1709             : /*
    1710             :  * deparse remote UPDATE statement
    1711             :  *
    1712             :  * The statement text is appended to buf, and we also create an integer List
    1713             :  * of the columns being retrieved by WITH CHECK OPTION or RETURNING (if any),
    1714             :  * which is returned to *retrieved_attrs.
    1715             :  */
    1716             : void
    1717          62 : deparseUpdateSql(StringInfo buf, RangeTblEntry *rte,
    1718             :                  Index rtindex, Relation rel,
    1719             :                  List *targetAttrs,
    1720             :                  List *withCheckOptionList, List *returningList,
    1721             :                  List **retrieved_attrs)
    1722             : {
    1723             :     AttrNumber  pindex;
    1724             :     bool        first;
    1725             :     ListCell   *lc;
    1726             : 
    1727          62 :     appendStringInfoString(buf, "UPDATE ");
    1728          62 :     deparseRelation(buf, rel);
    1729          62 :     appendStringInfoString(buf, " SET ");
    1730             : 
    1731          62 :     pindex = 2;                 /* ctid is always the first param */
    1732          62 :     first = true;
    1733         124 :     foreach(lc, targetAttrs)
    1734             :     {
    1735          62 :         int         attnum = lfirst_int(lc);
    1736             : 
    1737          62 :         if (!first)
    1738           0 :             appendStringInfoString(buf, ", ");
    1739          62 :         first = false;
    1740             : 
    1741          62 :         deparseColumnRef(buf, rtindex, attnum, rte, false);
    1742          62 :         appendStringInfo(buf, " = $%d", pindex);
    1743          62 :         pindex++;
    1744             :     }
    1745          62 :     appendStringInfoString(buf, " WHERE ctid = $1");
    1746             : 
    1747          62 :     deparseReturningList(buf, rte, rtindex, rel,
    1748          62 :                          rel->trigdesc && rel->trigdesc->trig_update_after_row,
    1749             :                          withCheckOptionList, returningList, retrieved_attrs);
    1750          62 : }
    1751             : 
    1752             : /*
    1753             :  * deparse remote UPDATE statement
    1754             :  *
    1755             :  * 'buf' is the output buffer to append the statement to
    1756             :  * 'rtindex' is the RT index of the associated target relation
    1757             :  * 'rel' is the relation descriptor for the target relation
    1758             :  * 'foreignrel' is the RelOptInfo for the target relation or the join relation
    1759             :  *      containing all base relations in the query
    1760             :  * 'targetlist' is the tlist of the underlying foreign-scan plan node
    1761             :  * 'targetAttrs' is the target columns of the UPDATE
    1762             :  * 'remote_conds' is the qual clauses that must be evaluated remotely
    1763             :  * '*params_list' is an output list of exprs that will become remote Params
    1764             :  * 'returningList' is the RETURNING targetlist
    1765             :  * '*retrieved_attrs' is an output list of integers of columns being retrieved
    1766             :  *      by RETURNING (if any)
    1767             :  */
    1768             : void
    1769          74 : deparseDirectUpdateSql(StringInfo buf, PlannerInfo *root,
    1770             :                        Index rtindex, Relation rel,
    1771             :                        RelOptInfo *foreignrel,
    1772             :                        List *targetlist,
    1773             :                        List *targetAttrs,
    1774             :                        List *remote_conds,
    1775             :                        List **params_list,
    1776             :                        List *returningList,
    1777             :                        List **retrieved_attrs)
    1778             : {
    1779             :     deparse_expr_cxt context;
    1780             :     int         nestlevel;
    1781             :     bool        first;
    1782             :     ListCell   *lc;
    1783          74 :     RangeTblEntry *rte = planner_rt_fetch(rtindex, root);
    1784             : 
    1785             :     /* Set up context struct for recursion */
    1786          74 :     context.root = root;
    1787          74 :     context.foreignrel = foreignrel;
    1788          74 :     context.scanrel = foreignrel;
    1789          74 :     context.buf = buf;
    1790          74 :     context.params_list = params_list;
    1791             : 
    1792          74 :     appendStringInfoString(buf, "UPDATE ");
    1793          74 :     deparseRelation(buf, rel);
    1794          74 :     if (foreignrel->reloptkind == RELOPT_JOINREL)
    1795          12 :         appendStringInfo(buf, " %s%d", REL_ALIAS_PREFIX, rtindex);
    1796          74 :     appendStringInfoString(buf, " SET ");
    1797             : 
    1798             :     /* Make sure any constants in the exprs are printed portably */
    1799          74 :     nestlevel = set_transmission_modes();
    1800             : 
    1801          74 :     first = true;
    1802         164 :     foreach(lc, targetAttrs)
    1803             :     {
    1804          90 :         int         attnum = lfirst_int(lc);
    1805          90 :         TargetEntry *tle = get_tle_by_resno(targetlist, attnum);
    1806             : 
    1807          90 :         if (!tle)
    1808           0 :             elog(ERROR, "attribute number %d not found in UPDATE targetlist",
    1809             :                  attnum);
    1810             : 
    1811          90 :         if (!first)
    1812          16 :             appendStringInfoString(buf, ", ");
    1813          90 :         first = false;
    1814             : 
    1815          90 :         deparseColumnRef(buf, rtindex, attnum, rte, false);
    1816          90 :         appendStringInfoString(buf, " = ");
    1817          90 :         deparseExpr((Expr *) tle->expr, &context);
    1818             :     }
    1819             : 
    1820          74 :     reset_transmission_modes(nestlevel);
    1821             : 
    1822          74 :     if (foreignrel->reloptkind == RELOPT_JOINREL)
    1823             :     {
    1824          12 :         List       *ignore_conds = NIL;
    1825             : 
    1826          12 :         appendStringInfo(buf, " FROM ");
    1827          12 :         deparseFromExprForRel(buf, root, foreignrel, true, rtindex,
    1828             :                               &ignore_conds, params_list);
    1829          12 :         remote_conds = list_concat(remote_conds, ignore_conds);
    1830             :     }
    1831             : 
    1832          74 :     if (remote_conds)
    1833             :     {
    1834          54 :         appendStringInfoString(buf, " WHERE ");
    1835          54 :         appendConditions(remote_conds, &context);
    1836             :     }
    1837             : 
    1838          74 :     if (foreignrel->reloptkind == RELOPT_JOINREL)
    1839          12 :         deparseExplicitTargetList(returningList, true, retrieved_attrs,
    1840             :                                   &context);
    1841             :     else
    1842          62 :         deparseReturningList(buf, rte, rtindex, rel, false,
    1843             :                              NIL, returningList, retrieved_attrs);
    1844          74 : }
    1845             : 
    1846             : /*
    1847             :  * deparse remote DELETE statement
    1848             :  *
    1849             :  * The statement text is appended to buf, and we also create an integer List
    1850             :  * of the columns being retrieved by RETURNING (if any), which is returned
    1851             :  * to *retrieved_attrs.
    1852             :  */
    1853             : void
    1854          18 : deparseDeleteSql(StringInfo buf, RangeTblEntry *rte,
    1855             :                  Index rtindex, Relation rel,
    1856             :                  List *returningList,
    1857             :                  List **retrieved_attrs)
    1858             : {
    1859          18 :     appendStringInfoString(buf, "DELETE FROM ");
    1860          18 :     deparseRelation(buf, rel);
    1861          18 :     appendStringInfoString(buf, " WHERE ctid = $1");
    1862             : 
    1863          18 :     deparseReturningList(buf, rte, rtindex, rel,
    1864          18 :                          rel->trigdesc && rel->trigdesc->trig_delete_after_row,
    1865             :                          NIL, returningList, retrieved_attrs);
    1866          18 : }
    1867             : 
    1868             : /*
    1869             :  * deparse remote DELETE statement
    1870             :  *
    1871             :  * 'buf' is the output buffer to append the statement to
    1872             :  * 'rtindex' is the RT index of the associated target relation
    1873             :  * 'rel' is the relation descriptor for the target relation
    1874             :  * 'foreignrel' is the RelOptInfo for the target relation or the join relation
    1875             :  *      containing all base relations in the query
    1876             :  * 'remote_conds' is the qual clauses that must be evaluated remotely
    1877             :  * '*params_list' is an output list of exprs that will become remote Params
    1878             :  * 'returningList' is the RETURNING targetlist
    1879             :  * '*retrieved_attrs' is an output list of integers of columns being retrieved
    1880             :  *      by RETURNING (if any)
    1881             :  */
    1882             : void
    1883          78 : deparseDirectDeleteSql(StringInfo buf, PlannerInfo *root,
    1884             :                        Index rtindex, Relation rel,
    1885             :                        RelOptInfo *foreignrel,
    1886             :                        List *remote_conds,
    1887             :                        List **params_list,
    1888             :                        List *returningList,
    1889             :                        List **retrieved_attrs)
    1890             : {
    1891             :     deparse_expr_cxt context;
    1892             : 
    1893             :     /* Set up context struct for recursion */
    1894          78 :     context.root = root;
    1895          78 :     context.foreignrel = foreignrel;
    1896          78 :     context.scanrel = foreignrel;
    1897          78 :     context.buf = buf;
    1898          78 :     context.params_list = params_list;
    1899             : 
    1900          78 :     appendStringInfoString(buf, "DELETE FROM ");
    1901          78 :     deparseRelation(buf, rel);
    1902          78 :     if (foreignrel->reloptkind == RELOPT_JOINREL)
    1903          12 :         appendStringInfo(buf, " %s%d", REL_ALIAS_PREFIX, rtindex);
    1904             : 
    1905          78 :     if (foreignrel->reloptkind == RELOPT_JOINREL)
    1906             :     {
    1907          12 :         List       *ignore_conds = NIL;
    1908             : 
    1909          12 :         appendStringInfo(buf, " USING ");
    1910          12 :         deparseFromExprForRel(buf, root, foreignrel, true, rtindex,
    1911             :                               &ignore_conds, params_list);
    1912          12 :         remote_conds = list_concat(remote_conds, ignore_conds);
    1913             :     }
    1914             : 
    1915          78 :     if (remote_conds)
    1916             :     {
    1917          28 :         appendStringInfoString(buf, " WHERE ");
    1918          28 :         appendConditions(remote_conds, &context);
    1919             :     }
    1920             : 
    1921          78 :     if (foreignrel->reloptkind == RELOPT_JOINREL)
    1922          12 :         deparseExplicitTargetList(returningList, true, retrieved_attrs,
    1923             :                                   &context);
    1924             :     else
    1925          66 :         deparseReturningList(buf, planner_rt_fetch(rtindex, root),
    1926             :                              rtindex, rel, false,
    1927             :                              NIL, returningList, retrieved_attrs);
    1928          78 : }
    1929             : 
    1930             : /*
    1931             :  * Add a RETURNING clause, if needed, to an INSERT/UPDATE/DELETE.
    1932             :  */
    1933             : static void
    1934         364 : deparseReturningList(StringInfo buf, RangeTblEntry *rte,
    1935             :                      Index rtindex, Relation rel,
    1936             :                      bool trig_after_row,
    1937             :                      List *withCheckOptionList,
    1938             :                      List *returningList,
    1939             :                      List **retrieved_attrs)
    1940             : {
    1941         364 :     Bitmapset  *attrs_used = NULL;
    1942             : 
    1943         364 :     if (trig_after_row)
    1944             :     {
    1945             :         /* whole-row reference acquires all non-system columns */
    1946          40 :         attrs_used =
    1947          40 :             bms_make_singleton(0 - FirstLowInvalidHeapAttributeNumber);
    1948             :     }
    1949             : 
    1950         364 :     if (withCheckOptionList != NIL)
    1951             :     {
    1952             :         /*
    1953             :          * We need the attrs, non-system and system, mentioned in the local
    1954             :          * query's WITH CHECK OPTION list.
    1955             :          *
    1956             :          * Note: we do this to ensure that WCO constraints will be evaluated
    1957             :          * on the data actually inserted/updated on the remote side, which
    1958             :          * might differ from the data supplied by the core code, for example
    1959             :          * as a result of remote triggers.
    1960             :          */
    1961          28 :         pull_varattnos((Node *) withCheckOptionList, rtindex,
    1962             :                        &attrs_used);
    1963             :     }
    1964             : 
    1965         364 :     if (returningList != NIL)
    1966             :     {
    1967             :         /*
    1968             :          * We need the attrs, non-system and system, mentioned in the local
    1969             :          * query's RETURNING list.
    1970             :          */
    1971          96 :         pull_varattnos((Node *) returningList, rtindex,
    1972             :                        &attrs_used);
    1973             :     }
    1974             : 
    1975         364 :     if (attrs_used != NULL)
    1976         162 :         deparseTargetList(buf, rte, rtindex, rel, true, attrs_used, false,
    1977             :                           retrieved_attrs);
    1978             :     else
    1979         202 :         *retrieved_attrs = NIL;
    1980         364 : }
    1981             : 
    1982             : /*
    1983             :  * Construct SELECT statement to acquire size in blocks of given relation.
    1984             :  *
    1985             :  * Note: we use local definition of block size, not remote definition.
    1986             :  * This is perhaps debatable.
    1987             :  *
    1988             :  * Note: pg_relation_size() exists in 8.1 and later.
    1989             :  */
    1990             : void
    1991          46 : deparseAnalyzeSizeSql(StringInfo buf, Relation rel)
    1992             : {
    1993             :     StringInfoData relname;
    1994             : 
    1995             :     /* We'll need the remote relation name as a literal. */
    1996          46 :     initStringInfo(&relname);
    1997          46 :     deparseRelation(&relname, rel);
    1998             : 
    1999          46 :     appendStringInfoString(buf, "SELECT pg_catalog.pg_relation_size(");
    2000          46 :     deparseStringLiteral(buf, relname.data);
    2001          46 :     appendStringInfo(buf, "::pg_catalog.regclass) / %d", BLCKSZ);
    2002          46 : }
    2003             : 
    2004             : /*
    2005             :  * Construct SELECT statement to acquire sample rows of given relation.
    2006             :  *
    2007             :  * SELECT command is appended to buf, and list of columns retrieved
    2008             :  * is returned to *retrieved_attrs.
    2009             :  */
    2010             : void
    2011          46 : deparseAnalyzeSql(StringInfo buf, Relation rel, List **retrieved_attrs)
    2012             : {
    2013          46 :     Oid         relid = RelationGetRelid(rel);
    2014          46 :     TupleDesc   tupdesc = RelationGetDescr(rel);
    2015             :     int         i;
    2016             :     char       *colname;
    2017             :     List       *options;
    2018             :     ListCell   *lc;
    2019          46 :     bool        first = true;
    2020             : 
    2021          46 :     *retrieved_attrs = NIL;
    2022             : 
    2023          46 :     appendStringInfoString(buf, "SELECT ");
    2024         192 :     for (i = 0; i < tupdesc->natts; i++)
    2025             :     {
    2026             :         /* Ignore dropped columns. */
    2027         146 :         if (TupleDescAttr(tupdesc, i)->attisdropped)
    2028           2 :             continue;
    2029             : 
    2030         144 :         if (!first)
    2031          98 :             appendStringInfoString(buf, ", ");
    2032         144 :         first = false;
    2033             : 
    2034             :         /* Use attribute name or column_name option. */
    2035         144 :         colname = NameStr(TupleDescAttr(tupdesc, i)->attname);
    2036         144 :         options = GetForeignColumnOptions(relid, i + 1);
    2037             : 
    2038         144 :         foreach(lc, options)
    2039             :         {
    2040           2 :             DefElem    *def = (DefElem *) lfirst(lc);
    2041             : 
    2042           2 :             if (strcmp(def->defname, "column_name") == 0)
    2043             :             {
    2044           2 :                 colname = defGetString(def);
    2045           2 :                 break;
    2046             :             }
    2047             :         }
    2048             : 
    2049         144 :         appendStringInfoString(buf, quote_identifier(colname));
    2050             : 
    2051         144 :         *retrieved_attrs = lappend_int(*retrieved_attrs, i + 1);
    2052             :     }
    2053             : 
    2054             :     /* Don't generate bad syntax for zero-column relation. */
    2055          46 :     if (first)
    2056           0 :         appendStringInfoString(buf, "NULL");
    2057             : 
    2058             :     /*
    2059             :      * Construct FROM clause
    2060             :      */
    2061          46 :     appendStringInfoString(buf, " FROM ");
    2062          46 :     deparseRelation(buf, rel);
    2063          46 : }
    2064             : 
    2065             : /*
    2066             :  * Construct name to use for given column, and emit it into buf.
    2067             :  * If it has a column_name FDW option, use that instead of attribute name.
    2068             :  *
    2069             :  * If qualify_col is true, qualify column name with the alias of relation.
    2070             :  */
    2071             : static void
    2072       17618 : deparseColumnRef(StringInfo buf, int varno, int varattno, RangeTblEntry *rte,
    2073             :                  bool qualify_col)
    2074             : {
    2075             :     /* We support fetching the remote side's CTID and OID. */
    2076       17618 :     if (varattno == SelfItemPointerAttributeNumber)
    2077             :     {
    2078          94 :         if (qualify_col)
    2079          90 :             ADD_REL_QUALIFIER(buf, varno);
    2080          94 :         appendStringInfoString(buf, "ctid");
    2081             :     }
    2082       17524 :     else if (varattno == ObjectIdAttributeNumber)
    2083             :     {
    2084           0 :         if (qualify_col)
    2085           0 :             ADD_REL_QUALIFIER(buf, varno);
    2086           0 :         appendStringInfoString(buf, "oid");
    2087             :     }
    2088       17524 :     else if (varattno < 0)
    2089             :     {
    2090             :         /*
    2091             :          * All other system attributes are fetched as 0, except for table OID,
    2092             :          * which is fetched as the local table OID.  However, we must be
    2093             :          * careful; the table could be beneath an outer join, in which case it
    2094             :          * must go to NULL whenever the rest of the row does.
    2095             :          */
    2096           0 :         Oid         fetchval = 0;
    2097             : 
    2098           0 :         if (varattno == TableOidAttributeNumber)
    2099           0 :             fetchval = rte->relid;
    2100             : 
    2101           0 :         if (qualify_col)
    2102             :         {
    2103           0 :             appendStringInfoString(buf, "CASE WHEN (");
    2104           0 :             ADD_REL_QUALIFIER(buf, varno);
    2105           0 :             appendStringInfo(buf, "*)::text IS NOT NULL THEN %u END", fetchval);
    2106             :         }
    2107             :         else
    2108           0 :             appendStringInfo(buf, "%u", fetchval);
    2109             :     }
    2110       17524 :     else if (varattno == 0)
    2111             :     {
    2112             :         /* Whole row reference */
    2113             :         Relation    rel;
    2114             :         Bitmapset  *attrs_used;
    2115             : 
    2116             :         /* Required only to be passed down to deparseTargetList(). */
    2117             :         List       *retrieved_attrs;
    2118             : 
    2119             :         /*
    2120             :          * The lock on the relation will be held by upper callers, so it's
    2121             :          * fine to open it with no lock here.
    2122             :          */
    2123         340 :         rel = heap_open(rte->relid, NoLock);
    2124             : 
    2125             :         /*
    2126             :          * The local name of the foreign table can not be recognized by the
    2127             :          * foreign server and the table it references on foreign server might
    2128             :          * have different column ordering or different columns than those
    2129             :          * declared locally. Hence we have to deparse whole-row reference as
    2130             :          * ROW(columns referenced locally). Construct this by deparsing a
    2131             :          * "whole row" attribute.
    2132             :          */
    2133         340 :         attrs_used = bms_add_member(NULL,
    2134             :                                     0 - FirstLowInvalidHeapAttributeNumber);
    2135             : 
    2136             :         /*
    2137             :          * In case the whole-row reference is under an outer join then it has
    2138             :          * to go NULL whenever the rest of the row goes NULL. Deparsing a join
    2139             :          * query would always involve multiple relations, thus qualify_col
    2140             :          * would be true.
    2141             :          */
    2142         340 :         if (qualify_col)
    2143             :         {
    2144         332 :             appendStringInfoString(buf, "CASE WHEN (");
    2145         332 :             ADD_REL_QUALIFIER(buf, varno);
    2146         332 :             appendStringInfoString(buf, "*)::text IS NOT NULL THEN ");
    2147             :         }
    2148             : 
    2149         340 :         appendStringInfoString(buf, "ROW(");
    2150         340 :         deparseTargetList(buf, rte, varno, rel, false, attrs_used, qualify_col,
    2151             :                           &retrieved_attrs);
    2152         340 :         appendStringInfoChar(buf, ')');
    2153             : 
    2154             :         /* Complete the CASE WHEN statement started above. */
    2155         340 :         if (qualify_col)
    2156         332 :             appendStringInfoString(buf, " END");
    2157             : 
    2158         340 :         heap_close(rel, NoLock);
    2159         340 :         bms_free(attrs_used);
    2160             :     }
    2161             :     else
    2162             :     {
    2163       17184 :         char       *colname = NULL;
    2164             :         List       *options;
    2165             :         ListCell   *lc;
    2166             : 
    2167             :         /* varno must not be any of OUTER_VAR, INNER_VAR and INDEX_VAR. */
    2168             :         Assert(!IS_SPECIAL_VARNO(varno));
    2169             : 
    2170             :         /*
    2171             :          * If it's a column of a foreign table, and it has the column_name FDW
    2172             :          * option, use that value.
    2173             :          */
    2174       17184 :         options = GetForeignColumnOptions(rte->relid, varattno);
    2175       17184 :         foreach(lc, options)
    2176             :         {
    2177        4404 :             DefElem    *def = (DefElem *) lfirst(lc);
    2178             : 
    2179        4404 :             if (strcmp(def->defname, "column_name") == 0)
    2180             :             {
    2181        4404 :                 colname = defGetString(def);
    2182        4404 :                 break;
    2183             :             }
    2184             :         }
    2185             : 
    2186             :         /*
    2187             :          * If it's a column of a regular table or it doesn't have column_name
    2188             :          * FDW option, use attribute name.
    2189             :          */
    2190       17184 :         if (colname == NULL)
    2191       12780 :             colname = get_attname(rte->relid, varattno, false);
    2192             : 
    2193       17184 :         if (qualify_col)
    2194        7444 :             ADD_REL_QUALIFIER(buf, varno);
    2195             : 
    2196       17184 :         appendStringInfoString(buf, quote_identifier(colname));
    2197             :     }
    2198       17618 : }
    2199             : 
    2200             : /*
    2201             :  * Append remote name of specified foreign table to buf.
    2202             :  * Use value of table_name FDW option (if any) instead of relation's name.
    2203             :  * Similarly, schema_name FDW option overrides schema name.
    2204             :  */
    2205             : static void
    2206        4422 : deparseRelation(StringInfo buf, Relation rel)
    2207             : {
    2208             :     ForeignTable *table;
    2209        4422 :     const char *nspname = NULL;
    2210        4422 :     const char *relname = NULL;
    2211             :     ListCell   *lc;
    2212             : 
    2213             :     /* obtain additional catalog information. */
    2214        4422 :     table = GetForeignTable(RelationGetRelid(rel));
    2215             : 
    2216             :     /*
    2217             :      * Use value of FDW options if any, instead of the name of object itself.
    2218             :      */
    2219       14356 :     foreach(lc, table->options)
    2220             :     {
    2221        9934 :         DefElem    *def = (DefElem *) lfirst(lc);
    2222             : 
    2223        9934 :         if (strcmp(def->defname, "schema_name") == 0)
    2224        3062 :             nspname = defGetString(def);
    2225        6872 :         else if (strcmp(def->defname, "table_name") == 0)
    2226        4422 :             relname = defGetString(def);
    2227             :     }
    2228             : 
    2229             :     /*
    2230             :      * Note: we could skip printing the schema name if it's pg_catalog, but
    2231             :      * that doesn't seem worth the trouble.
    2232             :      */
    2233        4422 :     if (nspname == NULL)
    2234        1360 :         nspname = get_namespace_name(RelationGetNamespace(rel));
    2235        4422 :     if (relname == NULL)
    2236           0 :         relname = RelationGetRelationName(rel);
    2237             : 
    2238        4422 :     appendStringInfo(buf, "%s.%s",
    2239             :                      quote_identifier(nspname), quote_identifier(relname));
    2240        4422 : }
    2241             : 
    2242             : /*
    2243             :  * Append a SQL string literal representing "val" to buf.
    2244             :  */
    2245             : void
    2246         438 : deparseStringLiteral(StringInfo buf, const char *val)
    2247             : {
    2248             :     const char *valptr;
    2249             : 
    2250             :     /*
    2251             :      * Rather than making assumptions about the remote server's value of
    2252             :      * standard_conforming_strings, always use E'foo' syntax if there are any
    2253             :      * backslashes.  This will fail on remote servers before 8.1, but those
    2254             :      * are long out of support.
    2255             :      */
    2256         438 :     if (strchr(val, '\\') != NULL)
    2257           2 :         appendStringInfoChar(buf, ESCAPE_STRING_SYNTAX);
    2258         438 :     appendStringInfoChar(buf, '\'');
    2259        3322 :     for (valptr = val; *valptr; valptr++)
    2260             :     {
    2261        2884 :         char        ch = *valptr;
    2262             : 
    2263        2884 :         if (SQL_STR_DOUBLE(ch, true))
    2264           4 :             appendStringInfoChar(buf, ch);
    2265        2884 :         appendStringInfoChar(buf, ch);
    2266             :     }
    2267         438 :     appendStringInfoChar(buf, '\'');
    2268         438 : }
    2269             : 
    2270             : /*
    2271             :  * Deparse given expression into context->buf.
    2272             :  *
    2273             :  * This function must support all the same node types that foreign_expr_walker
    2274             :  * accepts.
    2275             :  *
    2276             :  * Note: unlike ruleutils.c, we just use a simple hard-wired parenthesization
    2277             :  * scheme: anything more complex than a Var, Const, function call or cast
    2278             :  * should be self-parenthesized.
    2279             :  */
    2280             : static void
    2281       15256 : deparseExpr(Expr *node, deparse_expr_cxt *context)
    2282             : {
    2283       15256 :     if (node == NULL)
    2284           0 :         return;
    2285             : 
    2286       15256 :     switch (nodeTag(node))
    2287             :     {
    2288             :         case T_Var:
    2289        8988 :             deparseVar((Var *) node, context);
    2290        8988 :             break;
    2291             :         case T_Const:
    2292        2182 :             deparseConst((Const *) node, context, 0);
    2293        2182 :             break;
    2294             :         case T_Param:
    2295          40 :             deparseParam((Param *) node, context);
    2296          40 :             break;
    2297             :         case T_ArrayRef:
    2298           2 :             deparseArrayRef((ArrayRef *) node, context);
    2299           2 :             break;
    2300             :         case T_FuncExpr:
    2301          96 :             deparseFuncExpr((FuncExpr *) node, context);
    2302          96 :             break;
    2303             :         case T_OpExpr:
    2304        3382 :             deparseOpExpr((OpExpr *) node, context);
    2305        3382 :             break;
    2306             :         case T_DistinctExpr:
    2307           2 :             deparseDistinctExpr((DistinctExpr *) node, context);
    2308           2 :             break;
    2309             :         case T_ScalarArrayOpExpr:
    2310           8 :             deparseScalarArrayOpExpr((ScalarArrayOpExpr *) node, context);
    2311           8 :             break;
    2312             :         case T_RelabelType:
    2313          60 :             deparseRelabelType((RelabelType *) node, context);
    2314          60 :             break;
    2315             :         case T_BoolExpr:
    2316          72 :             deparseBoolExpr((BoolExpr *) node, context);
    2317          72 :             break;
    2318             :         case T_NullTest:
    2319          56 :             deparseNullTest((NullTest *) node, context);
    2320          56 :             break;
    2321             :         case T_ArrayExpr:
    2322           8 :             deparseArrayExpr((ArrayExpr *) node, context);
    2323           8 :             break;
    2324             :         case T_Aggref:
    2325         360 :             deparseAggref((Aggref *) node, context);
    2326         360 :             break;
    2327             :         default:
    2328           0 :             elog(ERROR, "unsupported expression type for deparse: %d",
    2329             :                  (int) nodeTag(node));
    2330             :             break;
    2331             :     }
    2332             : }
    2333             : 
    2334             : /*
    2335             :  * Deparse given Var node into context->buf.
    2336             :  *
    2337             :  * If the Var belongs to the foreign relation, just print its remote name.
    2338             :  * Otherwise, it's effectively a Param (and will in fact be a Param at
    2339             :  * run time).  Handle it the same way we handle plain Params --- see
    2340             :  * deparseParam for comments.
    2341             :  */
    2342             : static void
    2343        8988 : deparseVar(Var *node, deparse_expr_cxt *context)
    2344             : {
    2345        8988 :     Relids      relids = context->scanrel->relids;
    2346             :     int         relno;
    2347             :     int         colno;
    2348             : 
    2349             :     /* Qualify columns when multiple relations are involved. */
    2350        8988 :     bool        qualify_col = (bms_membership(relids) == BMS_MULTIPLE);
    2351             : 
    2352             :     /*
    2353             :      * If the Var belongs to the foreign relation that is deparsed as a
    2354             :      * subquery, use the relation and column alias to the Var provided by the
    2355             :      * subquery, instead of the remote name.
    2356             :      */
    2357        8988 :     if (is_subquery_var(node, context->scanrel, &relno, &colno))
    2358             :     {
    2359         168 :         appendStringInfo(context->buf, "%s%d.%s%d",
    2360             :                          SUBQUERY_REL_ALIAS_PREFIX, relno,
    2361             :                          SUBQUERY_COL_ALIAS_PREFIX, colno);
    2362         168 :         return;
    2363             :     }
    2364             : 
    2365        8820 :     if (bms_is_member(node->varno, relids) && node->varlevelsup == 0)
    2366       25620 :         deparseColumnRef(context->buf, node->varno, node->varattno,
    2367       17080 :                          planner_rt_fetch(node->varno, context->root),
    2368             :                          qualify_col);
    2369             :     else
    2370             :     {
    2371             :         /* Treat like a Param */
    2372         280 :         if (context->params_list)
    2373             :         {
    2374           8 :             int         pindex = 0;
    2375             :             ListCell   *lc;
    2376             : 
    2377             :             /* find its index in params_list */
    2378           8 :             foreach(lc, *context->params_list)
    2379             :             {
    2380           0 :                 pindex++;
    2381           0 :                 if (equal(node, (Node *) lfirst(lc)))
    2382           0 :                     break;
    2383             :             }
    2384           8 :             if (lc == NULL)
    2385             :             {
    2386             :                 /* not in list, so add it */
    2387           8 :                 pindex++;
    2388           8 :                 *context->params_list = lappend(*context->params_list, node);
    2389             :             }
    2390             : 
    2391           8 :             printRemoteParam(pindex, node->vartype, node->vartypmod, context);
    2392             :         }
    2393             :         else
    2394             :         {
    2395         272 :             printRemotePlaceholder(node->vartype, node->vartypmod, context);
    2396             :         }
    2397             :     }
    2398             : }
    2399             : 
    2400             : /*
    2401             :  * Deparse given constant value into context->buf.
    2402             :  *
    2403             :  * This function has to be kept in sync with ruleutils.c's get_const_expr.
    2404             :  * As for that function, showtype can be -1 to never show "::typename" decoration,
    2405             :  * or +1 to always show it, or 0 to show it only if the constant wouldn't be assumed
    2406             :  * to be the right type by default.
    2407             :  */
    2408             : static void
    2409        2182 : deparseConst(Const *node, deparse_expr_cxt *context, int showtype)
    2410             : {
    2411        2182 :     StringInfo  buf = context->buf;
    2412             :     Oid         typoutput;
    2413             :     bool        typIsVarlena;
    2414             :     char       *extval;
    2415        2182 :     bool        isfloat = false;
    2416             :     bool        needlabel;
    2417             : 
    2418        2182 :     if (node->constisnull)
    2419             :     {
    2420          14 :         appendStringInfoString(buf, "NULL");
    2421          14 :         if (showtype >= 0)
    2422          14 :             appendStringInfo(buf, "::%s",
    2423             :                              deparse_type_name(node->consttype,
    2424             :                                                node->consttypmod));
    2425          28 :         return;
    2426             :     }
    2427             : 
    2428        2168 :     getTypeOutputInfo(node->consttype,
    2429             :                       &typoutput, &typIsVarlena);
    2430        2168 :     extval = OidOutputFunctionCall(typoutput, node->constvalue);
    2431             : 
    2432        2168 :     switch (node->consttype)
    2433             :     {
    2434             :         case INT2OID:
    2435             :         case INT4OID:
    2436             :         case INT8OID:
    2437             :         case OIDOID:
    2438             :         case FLOAT4OID:
    2439             :         case FLOAT8OID:
    2440             :         case NUMERICOID:
    2441             :             {
    2442             :                 /*
    2443             :                  * No need to quote unless it's a special value such as 'NaN'.
    2444             :                  * See comments in get_const_expr().
    2445             :                  */
    2446        2048 :                 if (strspn(extval, "0123456789+-eE.") == strlen(extval))
    2447             :                 {
    2448        2048 :                     if (extval[0] == '+' || extval[0] == '-')
    2449           2 :                         appendStringInfo(buf, "(%s)", extval);
    2450             :                     else
    2451        2046 :                         appendStringInfoString(buf, extval);
    2452        2048 :                     if (strcspn(extval, "eE.") != strlen(extval))
    2453           4 :                         isfloat = true; /* it looks like a float */
    2454             :                 }
    2455             :                 else
    2456           0 :                     appendStringInfo(buf, "'%s'", extval);
    2457             :             }
    2458        2048 :             break;
    2459             :         case BITOID:
    2460             :         case VARBITOID:
    2461           0 :             appendStringInfo(buf, "B'%s'", extval);
    2462           0 :             break;
    2463             :         case BOOLOID:
    2464           0 :             if (strcmp(extval, "t") == 0)
    2465           0 :                 appendStringInfoString(buf, "true");
    2466             :             else
    2467           0 :                 appendStringInfoString(buf, "false");
    2468           0 :             break;
    2469             :         default:
    2470         120 :             deparseStringLiteral(buf, extval);
    2471         120 :             break;
    2472             :     }
    2473             : 
    2474        2168 :     pfree(extval);
    2475             : 
    2476        2168 :     if (showtype < 0)
    2477           0 :         return;
    2478             : 
    2479             :     /*
    2480             :      * For showtype == 0, append ::typename unless the constant will be
    2481             :      * implicitly typed as the right type when it is read in.
    2482             :      *
    2483             :      * XXX this code has to be kept in sync with the behavior of the parser,
    2484             :      * especially make_const.
    2485             :      */
    2486        2168 :     switch (node->consttype)
    2487             :     {
    2488             :         case BOOLOID:
    2489             :         case INT4OID:
    2490             :         case UNKNOWNOID:
    2491        2004 :             needlabel = false;
    2492        2004 :             break;
    2493             :         case NUMERICOID:
    2494          40 :             needlabel = !isfloat || (node->consttypmod >= 0);
    2495          40 :             break;
    2496             :         default:
    2497         124 :             needlabel = true;
    2498         124 :             break;
    2499             :     }
    2500        2168 :     if (needlabel || showtype > 0)
    2501         160 :         appendStringInfo(buf, "::%s",
    2502             :                          deparse_type_name(node->consttype,
    2503             :                                            node->consttypmod));
    2504             : }
    2505             : 
    2506             : /*
    2507             :  * Deparse given Param node.
    2508             :  *
    2509             :  * If we're generating the query "for real", add the Param to
    2510             :  * context->params_list if it's not already present, and then use its index
    2511             :  * in that list as the remote parameter number.  During EXPLAIN, there's
    2512             :  * no need to identify a parameter number.
    2513             :  */
    2514             : static void
    2515          40 : deparseParam(Param *node, deparse_expr_cxt *context)
    2516             : {
    2517          40 :     if (context->params_list)
    2518             :     {
    2519          26 :         int         pindex = 0;
    2520             :         ListCell   *lc;
    2521             : 
    2522             :         /* find its index in params_list */
    2523          30 :         foreach(lc, *context->params_list)
    2524             :         {
    2525           4 :             pindex++;
    2526           4 :             if (equal(node, (Node *) lfirst(lc)))
    2527           0 :                 break;
    2528             :         }
    2529          26 :         if (lc == NULL)
    2530             :         {
    2531             :             /* not in list, so add it */
    2532          26 :             pindex++;
    2533          26 :             *context->params_list = lappend(*context->params_list, node);
    2534             :         }
    2535             : 
    2536          26 :         printRemoteParam(pindex, node->paramtype, node->paramtypmod, context);
    2537             :     }
    2538             :     else
    2539             :     {
    2540          14 :         printRemotePlaceholder(node->paramtype, node->paramtypmod, context);
    2541             :     }
    2542          40 : }
    2543             : 
    2544             : /*
    2545             :  * Deparse an array subscript expression.
    2546             :  */
    2547             : static void
    2548           2 : deparseArrayRef(ArrayRef *node, deparse_expr_cxt *context)
    2549             : {
    2550           2 :     StringInfo  buf = context->buf;
    2551             :     ListCell   *lowlist_item;
    2552             :     ListCell   *uplist_item;
    2553             : 
    2554             :     /* Always parenthesize the expression. */
    2555           2 :     appendStringInfoChar(buf, '(');
    2556             : 
    2557             :     /*
    2558             :      * Deparse referenced array expression first.  If that expression includes
    2559             :      * a cast, we have to parenthesize to prevent the array subscript from
    2560             :      * being taken as typename decoration.  We can avoid that in the typical
    2561             :      * case of subscripting a Var, but otherwise do it.
    2562             :      */
    2563           2 :     if (IsA(node->refexpr, Var))
    2564           0 :         deparseExpr(node->refexpr, context);
    2565             :     else
    2566             :     {
    2567           2 :         appendStringInfoChar(buf, '(');
    2568           2 :         deparseExpr(node->refexpr, context);
    2569           2 :         appendStringInfoChar(buf, ')');
    2570             :     }
    2571             : 
    2572             :     /* Deparse subscript expressions. */
    2573           2 :     lowlist_item = list_head(node->reflowerindexpr); /* could be NULL */
    2574           4 :     foreach(uplist_item, node->refupperindexpr)
    2575             :     {
    2576           2 :         appendStringInfoChar(buf, '[');
    2577           2 :         if (lowlist_item)
    2578             :         {
    2579           0 :             deparseExpr(lfirst(lowlist_item), context);
    2580           0 :             appendStringInfoChar(buf, ':');
    2581           0 :             lowlist_item = lnext(lowlist_item);
    2582             :         }
    2583           2 :         deparseExpr(lfirst(uplist_item), context);
    2584           2 :         appendStringInfoChar(buf, ']');
    2585             :     }
    2586             : 
    2587           2 :     appendStringInfoChar(buf, ')');
    2588           2 : }
    2589             : 
    2590             : /*
    2591             :  * Deparse a function call.
    2592             :  */
    2593             : static void
    2594          96 : deparseFuncExpr(FuncExpr *node, deparse_expr_cxt *context)
    2595             : {
    2596          96 :     StringInfo  buf = context->buf;
    2597             :     bool        use_variadic;
    2598             :     bool        first;
    2599             :     ListCell   *arg;
    2600             : 
    2601             :     /*
    2602             :      * If the function call came from an implicit coercion, then just show the
    2603             :      * first argument.
    2604             :      */
    2605          96 :     if (node->funcformat == COERCE_IMPLICIT_CAST)
    2606             :     {
    2607          44 :         deparseExpr((Expr *) linitial(node->args), context);
    2608          44 :         return;
    2609             :     }
    2610             : 
    2611             :     /*
    2612             :      * If the function call came from a cast, then show the first argument
    2613             :      * plus an explicit cast operation.
    2614             :      */
    2615          52 :     if (node->funcformat == COERCE_EXPLICIT_CAST)
    2616             :     {
    2617           0 :         Oid         rettype = node->funcresulttype;
    2618             :         int32       coercedTypmod;
    2619             : 
    2620             :         /* Get the typmod if this is a length-coercion function */
    2621           0 :         (void) exprIsLengthCoercion((Node *) node, &coercedTypmod);
    2622             : 
    2623           0 :         deparseExpr((Expr *) linitial(node->args), context);
    2624           0 :         appendStringInfo(buf, "::%s",
    2625             :                          deparse_type_name(rettype, coercedTypmod));
    2626           0 :         return;
    2627             :     }
    2628             : 
    2629             :     /* Check if need to print VARIADIC (cf. ruleutils.c) */
    2630          52 :     use_variadic = node->funcvariadic;
    2631             : 
    2632             :     /*
    2633             :      * Normal function: display as proname(args).
    2634             :      */
    2635          52 :     appendFunctionName(node->funcid, context);
    2636          52 :     appendStringInfoChar(buf, '(');
    2637             : 
    2638             :     /* ... and all the arguments */
    2639          52 :     first = true;
    2640         106 :     foreach(arg, node->args)
    2641             :     {
    2642          54 :         if (!first)
    2643           2 :             appendStringInfoString(buf, ", ");
    2644          54 :         if (use_variadic && lnext(arg) == NULL)
    2645           0 :             appendStringInfoString(buf, "VARIADIC ");
    2646          54 :         deparseExpr((Expr *) lfirst(arg), context);
    2647          54 :         first = false;
    2648             :     }
    2649          52 :     appendStringInfoChar(buf, ')');
    2650             : }
    2651             : 
    2652             : /*
    2653             :  * Deparse given operator expression.   To avoid problems around
    2654             :  * priority of operations, we always parenthesize the arguments.
    2655             :  */
    2656             : static void
    2657        3382 : deparseOpExpr(OpExpr *node, deparse_expr_cxt *context)
    2658             : {
    2659        3382 :     StringInfo  buf = context->buf;
    2660             :     HeapTuple   tuple;
    2661             :     Form_pg_operator form;
    2662             :     char        oprkind;
    2663             :     ListCell   *arg;
    2664             : 
    2665             :     /* Retrieve information about the operator from system catalog. */
    2666        3382 :     tuple = SearchSysCache1(OPEROID, ObjectIdGetDatum(node->opno));
    2667        3382 :     if (!HeapTupleIsValid(tuple))
    2668           0 :         elog(ERROR, "cache lookup failed for operator %u", node->opno);
    2669        3382 :     form = (Form_pg_operator) GETSTRUCT(tuple);
    2670        3382 :     oprkind = form->oprkind;
    2671             : 
    2672             :     /* Sanity check. */
    2673             :     Assert((oprkind == 'r' && list_length(node->args) == 1) ||
    2674             :            (oprkind == 'l' && list_length(node->args) == 1) ||
    2675             :            (oprkind == 'b' && list_length(node->args) == 2));
    2676             : 
    2677             :     /* Always parenthesize the expression. */
    2678        3382 :     appendStringInfoChar(buf, '(');
    2679             : 
    2680             :     /* Deparse left operand. */
    2681        3382 :     if (oprkind == 'r' || oprkind == 'b')
    2682             :     {
    2683        3376 :         arg = list_head(node->args);
    2684        3376 :         deparseExpr(lfirst(arg), context);
    2685        3376 :         appendStringInfoChar(buf, ' ');
    2686             :     }
    2687             : 
    2688             :     /* Deparse operator name. */
    2689        3382 :     deparseOperatorName(buf, form);
    2690             : 
    2691             :     /* Deparse right operand. */
    2692        3382 :     if (oprkind == 'l' || oprkind == 'b')
    2693             :     {
    2694        3380 :         arg = list_tail(node->args);
    2695        3380 :         appendStringInfoChar(buf, ' ');
    2696        3380 :         deparseExpr(lfirst(arg), context);
    2697             :     }
    2698             : 
    2699        3382 :     appendStringInfoChar(buf, ')');
    2700             : 
    2701        3382 :     ReleaseSysCache(tuple);
    2702        3382 : }
    2703             : 
    2704             : /*
    2705             :  * Print the name of an operator.
    2706             :  */
    2707             : static void
    2708        3398 : deparseOperatorName(StringInfo buf, Form_pg_operator opform)
    2709             : {
    2710             :     char       *opname;
    2711             : 
    2712             :     /* opname is not a SQL identifier, so we should not quote it. */
    2713        3398 :     opname = NameStr(opform->oprname);
    2714             : 
    2715             :     /* Print schema name only if it's not pg_catalog */
    2716        3398 :     if (opform->oprnamespace != PG_CATALOG_NAMESPACE)
    2717             :     {
    2718             :         const char *opnspname;
    2719             : 
    2720          14 :         opnspname = get_namespace_name(opform->oprnamespace);
    2721             :         /* Print fully qualified operator name. */
    2722          14 :         appendStringInfo(buf, "OPERATOR(%s.%s)",
    2723             :                          quote_identifier(opnspname), opname);
    2724             :     }
    2725             :     else
    2726             :     {
    2727             :         /* Just print operator name. */
    2728        3384 :         appendStringInfoString(buf, opname);
    2729             :     }
    2730        3398 : }
    2731             : 
    2732             : /*
    2733             :  * Deparse IS DISTINCT FROM.
    2734             :  */
    2735             : static void
    2736           2 : deparseDistinctExpr(DistinctExpr *node, deparse_expr_cxt *context)
    2737             : {
    2738           2 :     StringInfo  buf = context->buf;
    2739             : 
    2740             :     Assert(list_length(node->args) == 2);
    2741             : 
    2742           2 :     appendStringInfoChar(buf, '(');
    2743           2 :     deparseExpr(linitial(node->args), context);
    2744           2 :     appendStringInfoString(buf, " IS DISTINCT FROM ");
    2745           2 :     deparseExpr(lsecond(node->args), context);
    2746           2 :     appendStringInfoChar(buf, ')');
    2747           2 : }
    2748             : 
    2749             : /*
    2750             :  * Deparse given ScalarArrayOpExpr expression.  To avoid problems
    2751             :  * around priority of operations, we always parenthesize the arguments.
    2752             :  */
    2753             : static void
    2754           8 : deparseScalarArrayOpExpr(ScalarArrayOpExpr *node, deparse_expr_cxt *context)
    2755             : {
    2756           8 :     StringInfo  buf = context->buf;
    2757             :     HeapTuple   tuple;
    2758             :     Form_pg_operator form;
    2759             :     Expr       *arg1;
    2760             :     Expr       *arg2;
    2761             : 
    2762             :     /* Retrieve information about the operator from system catalog. */
    2763           8 :     tuple = SearchSysCache1(OPEROID, ObjectIdGetDatum(node->opno));
    2764           8 :     if (!HeapTupleIsValid(tuple))
    2765           0 :         elog(ERROR, "cache lookup failed for operator %u", node->opno);
    2766           8 :     form = (Form_pg_operator) GETSTRUCT(tuple);
    2767             : 
    2768             :     /* Sanity check. */
    2769             :     Assert(list_length(node->args) == 2);
    2770             : 
    2771             :     /* Always parenthesize the expression. */
    2772           8 :     appendStringInfoChar(buf, '(');
    2773             : 
    2774             :     /* Deparse left operand. */
    2775           8 :     arg1 = linitial(node->args);
    2776           8 :     deparseExpr(arg1, context);
    2777           8 :     appendStringInfoChar(buf, ' ');
    2778             : 
    2779             :     /* Deparse operator name plus decoration. */
    2780           8 :     deparseOperatorName(buf, form);
    2781           8 :     appendStringInfo(buf, " %s (", node->useOr ? "ANY" : "ALL");
    2782             : 
    2783             :     /* Deparse right operand. */
    2784           8 :     arg2 = lsecond(node->args);
    2785           8 :     deparseExpr(arg2, context);
    2786             : 
    2787           8 :     appendStringInfoChar(buf, ')');
    2788             : 
    2789             :     /* Always parenthesize the expression. */
    2790           8 :     appendStringInfoChar(buf, ')');
    2791             : 
    2792           8 :     ReleaseSysCache(tuple);
    2793           8 : }
    2794             : 
    2795             : /*
    2796             :  * Deparse a RelabelType (binary-compatible cast) node.
    2797             :  */
    2798             : static void
    2799          60 : deparseRelabelType(RelabelType *node, deparse_expr_cxt *context)
    2800             : {
    2801          60 :     deparseExpr(node->arg, context);
    2802          60 :     if (node->relabelformat != COERCE_IMPLICIT_CAST)
    2803           0 :         appendStringInfo(context->buf, "::%s",
    2804             :                          deparse_type_name(node->resulttype,
    2805             :                                            node->resulttypmod));
    2806          60 : }
    2807             : 
    2808             : /*
    2809             :  * Deparse a BoolExpr node.
    2810             :  */
    2811             : static void
    2812          72 : deparseBoolExpr(BoolExpr *node, deparse_expr_cxt *context)
    2813             : {
    2814          72 :     StringInfo  buf = context->buf;
    2815          72 :     const char *op = NULL;      /* keep compiler quiet */
    2816             :     bool        first;
    2817             :     ListCell   *lc;
    2818             : 
    2819          72 :     switch (node->boolop)
    2820             :     {
    2821             :         case AND_EXPR:
    2822          32 :             op = "AND";
    2823          32 :             break;
    2824             :         case OR_EXPR:
    2825          40 :             op = "OR";
    2826          40 :             break;
    2827             :         case NOT_EXPR:
    2828           0 :             appendStringInfoString(buf, "(NOT ");
    2829           0 :             deparseExpr(linitial(node->args), context);
    2830           0 :             appendStringInfoChar(buf, ')');
    2831           0 :             return;
    2832             :     }
    2833             : 
    2834          72 :     appendStringInfoChar(buf, '(');
    2835          72 :     first = true;
    2836         216 :     foreach(lc, node->args)
    2837             :     {
    2838         144 :         if (!first)
    2839          72 :             appendStringInfo(buf, " %s ", op);
    2840         144 :         deparseExpr((Expr *) lfirst(lc), context);
    2841         144 :         first = false;
    2842             :     }
    2843          72 :     appendStringInfoChar(buf, ')');
    2844             : }
    2845             : 
    2846             : /*
    2847             :  * Deparse IS [NOT] NULL expression.
    2848             :  */
    2849             : static void
    2850          56 : deparseNullTest(NullTest *node, deparse_expr_cxt *context)
    2851             : {
    2852          56 :     StringInfo  buf = context->buf;
    2853             : 
    2854          56 :     appendStringInfoChar(buf, '(');
    2855          56 :     deparseExpr(node->arg, context);
    2856             : 
    2857             :     /*
    2858             :      * For scalar inputs, we prefer to print as IS [NOT] NULL, which is
    2859             :      * shorter and traditional.  If it's a rowtype input but we're applying a
    2860             :      * scalar test, must print IS [NOT] DISTINCT FROM NULL to be semantically
    2861             :      * correct.
    2862             :      */
    2863          56 :     if (node->argisrow || !type_is_rowtype(exprType((Node *) node->arg)))
    2864             :     {
    2865         112 :         if (node->nulltesttype == IS_NULL)
    2866          38 :             appendStringInfoString(buf, " IS NULL)");
    2867             :         else
    2868          18 :             appendStringInfoString(buf, " IS NOT NULL)");
    2869             :     }
    2870             :     else
    2871             :     {
    2872           0 :         if (node->nulltesttype == IS_NULL)
    2873           0 :             appendStringInfoString(buf, " IS NOT DISTINCT FROM NULL)");
    2874             :         else
    2875           0 :             appendStringInfoString(buf, " IS DISTINCT FROM NULL)");
    2876             :     }
    2877          56 : }
    2878             : 
    2879             : /*
    2880             :  * Deparse ARRAY[...] construct.
    2881             :  */
    2882             : static void
    2883           8 : deparseArrayExpr(ArrayExpr *node, deparse_expr_cxt *context)
    2884             : {
    2885           8 :     StringInfo  buf = context->buf;
    2886           8 :     bool        first = true;
    2887             :     ListCell   *lc;
    2888             : 
    2889           8 :     appendStringInfoString(buf, "ARRAY[");
    2890          24 :     foreach(lc, node->elements)
    2891             :     {
    2892          16 :         if (!first)
    2893           8 :             appendStringInfoString(buf, ", ");
    2894          16 :         deparseExpr(lfirst(lc), context);
    2895          16 :         first = false;
    2896             :     }
    2897           8 :     appendStringInfoChar(buf, ']');
    2898             : 
    2899             :     /* If the array is empty, we need an explicit cast to the array type. */
    2900           8 :     if (node->elements == NIL)
    2901           0 :         appendStringInfo(buf, "::%s",
    2902             :                          deparse_type_name(node->array_typeid, -1));
    2903           8 : }
    2904             : 
    2905             : /*
    2906             :  * Deparse an Aggref node.
    2907             :  */
    2908             : static void
    2909         360 : deparseAggref(Aggref *node, deparse_expr_cxt *context)
    2910             : {
    2911         360 :     StringInfo  buf = context->buf;
    2912             :     bool        use_variadic;
    2913             : 
    2914             :     /* Only basic, non-split aggregation accepted. */
    2915             :     Assert(node->aggsplit == AGGSPLIT_SIMPLE);
    2916             : 
    2917             :     /* Check if need to print VARIADIC (cf. ruleutils.c) */
    2918         360 :     use_variadic = node->aggvariadic;
    2919             : 
    2920             :     /* Find aggregate name from aggfnoid which is a pg_proc entry */
    2921         360 :     appendFunctionName(node->aggfnoid, context);
    2922         360 :     appendStringInfoChar(buf, '(');
    2923             : 
    2924             :     /* Add DISTINCT */
    2925         360 :     appendStringInfoString(buf, (node->aggdistinct != NIL) ? "DISTINCT " : "");
    2926             : 
    2927         360 :     if (AGGKIND_IS_ORDERED_SET(node->aggkind))
    2928             :     {
    2929             :         /* Add WITHIN GROUP (ORDER BY ..) */
    2930             :         ListCell   *arg;
    2931          16 :         bool        first = true;
    2932             : 
    2933             :         Assert(!node->aggvariadic);
    2934             :         Assert(node->aggorder != NIL);
    2935             : 
    2936          36 :         foreach(arg, node->aggdirectargs)
    2937             :         {
    2938          20 :             if (!first)
    2939           4 :                 appendStringInfoString(buf, ", ");
    2940          20 :             first = false;
    2941             : 
    2942          20 :             deparseExpr((Expr *) lfirst(arg), context);
    2943             :         }
    2944             : 
    2945          16 :         appendStringInfoString(buf, ") WITHIN GROUP (ORDER BY ");
    2946          16 :         appendAggOrderBy(node->aggorder, node->args, context);
    2947             :     }
    2948             :     else
    2949             :     {
    2950             :         /* aggstar can be set only in zero-argument aggregates */
    2951         344 :         if (node->aggstar)
    2952          78 :             appendStringInfoChar(buf, '*');
    2953             :         else
    2954             :         {
    2955             :             ListCell   *arg;
    2956         266 :             bool        first = true;
    2957             : 
    2958             :             /* Add all the arguments */
    2959         540 :             foreach(arg, node->args)
    2960             :             {
    2961         274 :                 TargetEntry *tle = (TargetEntry *) lfirst(arg);
    2962         274 :                 Node       *n = (Node *) tle->expr;
    2963             : 
    2964         274 :                 if (tle->resjunk)
    2965           8 :                     continue;
    2966             : 
    2967         266 :                 if (!first)
    2968           0 :                     appendStringInfoString(buf, ", ");
    2969         266 :                 first = false;
    2970             : 
    2971             :                 /* Add VARIADIC */
    2972         266 :                 if (use_variadic && lnext(arg) == NULL)
    2973           4 :                     appendStringInfoString(buf, "VARIADIC ");
    2974             : 
    2975         266 :                 deparseExpr((Expr *) n, context);
    2976             :             }
    2977             :         }
    2978             : 
    2979             :         /* Add ORDER BY */
    2980         344 :         if (node->aggorder != NIL)
    2981             :         {
    2982          32 :             appendStringInfoString(buf, " ORDER BY ");
    2983          32 :             appendAggOrderBy(node->aggorder, node->args, context);
    2984             :         }
    2985             :     }
    2986             : 
    2987             :     /* Add FILTER (WHERE ..) */
    2988         360 :     if (node->aggfilter != NULL)
    2989             :     {
    2990          20 :         appendStringInfoString(buf, ") FILTER (WHERE ");
    2991          20 :         deparseExpr((Expr *) node->aggfilter, context);
    2992             :     }
    2993             : 
    2994         360 :     appendStringInfoChar(buf, ')');
    2995         360 : }
    2996             : 
    2997             : /*
    2998             :  * Append ORDER BY within aggregate function.
    2999             :  */
    3000             : static void
    3001          48 : appendAggOrderBy(List *orderList, List *targetList, deparse_expr_cxt *context)
    3002             : {
    3003          48 :     StringInfo  buf = context->buf;
    3004             :     ListCell   *lc;
    3005          48 :     bool        first = true;
    3006             : 
    3007         100 :     foreach(lc, orderList)
    3008             :     {
    3009          52 :         SortGroupClause *srt = (SortGroupClause *) lfirst(lc);
    3010             :         Node       *sortexpr;
    3011             :         Oid         sortcoltype;
    3012             :         TypeCacheEntry *typentry;
    3013             : 
    3014          52 :         if (!first)
    3015           4 :             appendStringInfoString(buf, ", ");
    3016          52 :         first = false;
    3017             : 
    3018          52 :         sortexpr = deparseSortGroupClause(srt->tleSortGroupRef, targetList,
    3019             :                                           false, context);
    3020          52 :         sortcoltype = exprType(sortexpr);
    3021             :         /* See whether operator is default < or > for datatype */
    3022          52 :         typentry = lookup_type_cache(sortcoltype,
    3023             :                                      TYPECACHE_LT_OPR | TYPECACHE_GT_OPR);
    3024          52 :         if (srt->sortop == typentry->lt_opr)
    3025          32 :             appendStringInfoString(buf, " ASC");
    3026          20 :         else if (srt->sortop == typentry->gt_opr)
    3027          12 :             appendStringInfoString(buf, " DESC");
    3028             :         else
    3029             :         {
    3030             :             HeapTuple   opertup;
    3031             :             Form_pg_operator operform;
    3032             : 
    3033           8 :             appendStringInfoString(buf, " USING ");
    3034             : 
    3035             :             /* Append operator name. */
    3036           8 :             opertup = SearchSysCache1(OPEROID, ObjectIdGetDatum(srt->sortop));
    3037           8 :             if (!HeapTupleIsValid(opertup))
    3038           0 :                 elog(ERROR, "cache lookup failed for operator %u", srt->sortop);
    3039           8 :             operform = (Form_pg_operator) GETSTRUCT(opertup);
    3040           8 :             deparseOperatorName(buf, operform);
    3041           8 :             ReleaseSysCache(opertup);
    3042             :         }
    3043             : 
    3044          52 :         if (srt->nulls_first)
    3045           8 :             appendStringInfoString(buf, " NULLS FIRST");
    3046             :         else
    3047          44 :             appendStringInfoString(buf, " NULLS LAST");
    3048             :     }
    3049          48 : }
    3050             : 
    3051             : /*
    3052             :  * Print the representation of a parameter to be sent to the remote side.
    3053             :  *
    3054             :  * Note: we always label the Param's type explicitly rather than relying on
    3055             :  * transmitting a numeric type OID in PQexecParams().  This allows us to
    3056             :  * avoid assuming that types have the same OIDs on the remote side as they
    3057             :  * do locally --- they need only have the same names.
    3058             :  */
    3059             : static void
    3060          34 : printRemoteParam(int paramindex, Oid paramtype, int32 paramtypmod,
    3061             :                  deparse_expr_cxt *context)
    3062             : {
    3063          34 :     StringInfo  buf = context->buf;
    3064          34 :     char       *ptypename = deparse_type_name(paramtype, paramtypmod);
    3065             : 
    3066          34 :     appendStringInfo(buf, "$%d::%s", paramindex, ptypename);
    3067          34 : }
    3068             : 
    3069             : /*
    3070             :  * Print the representation of a placeholder for a parameter that will be
    3071             :  * sent to the remote side at execution time.
    3072             :  *
    3073             :  * This is used when we're just trying to EXPLAIN the remote query.
    3074             :  * We don't have the actual value of the runtime parameter yet, and we don't
    3075             :  * want the remote planner to generate a plan that depends on such a value
    3076             :  * anyway.  Thus, we can't do something simple like "$1::paramtype".
    3077             :  * Instead, we emit "((SELECT null::paramtype)::paramtype)".
    3078             :  * In all extant versions of Postgres, the planner will see that as an unknown
    3079             :  * constant value, which is what we want.  This might need adjustment if we
    3080             :  * ever make the planner flatten scalar subqueries.  Note: the reason for the
    3081             :  * apparently useless outer cast is to ensure that the representation as a
    3082             :  * whole will be parsed as an a_expr and not a select_with_parens; the latter
    3083             :  * would do the wrong thing in the context "x = ANY(...)".
    3084             :  */
    3085             : static void
    3086         286 : printRemotePlaceholder(Oid paramtype, int32 paramtypmod,
    3087             :                        deparse_expr_cxt *context)
    3088             : {
    3089         286 :     StringInfo  buf = context->buf;
    3090         286 :     char       *ptypename = deparse_type_name(paramtype, paramtypmod);
    3091             : 
    3092         286 :     appendStringInfo(buf, "((SELECT null::%s)::%s)", ptypename, ptypename);
    3093         286 : }
    3094             : 
    3095             : /*
    3096             :  * Deparse GROUP BY clause.
    3097             :  */
    3098             : static void
    3099         246 : appendGroupByClause(List *tlist, deparse_expr_cxt *context)
    3100             : {
    3101         246 :     StringInfo  buf = context->buf;
    3102         246 :     Query      *query = context->root->parse;
    3103             :     ListCell   *lc;
    3104         246 :     bool        first = true;
    3105             : 
    3106             :     /* Nothing to be done, if there's no GROUP BY clause in the query. */
    3107         246 :     if (!query->groupClause)
    3108          72 :         return;
    3109             : 
    3110         174 :     appendStringInfoString(buf, " GROUP BY ");
    3111             : 
    3112             :     /*
    3113             :      * Queries with grouping sets are not pushed down, so we don't expect
    3114             :      * grouping sets here.
    3115             :      */
    3116             :     Assert(!query->groupingSets);
    3117             : 
    3118         372 :     foreach(lc, query->groupClause)
    3119             :     {
    3120         198 :         SortGroupClause *grp = (SortGroupClause *) lfirst(lc);
    3121             : 
    3122         198 :         if (!first)
    3123          24 :             appendStringInfoString(buf, ", ");
    3124         198 :         first = false;
    3125             : 
    3126         198 :         deparseSortGroupClause(grp->tleSortGroupRef, tlist, true, context);
    3127             :     }
    3128             : }
    3129             : 
    3130             : /*
    3131             :  * Deparse ORDER BY clause according to the given pathkeys for given base
    3132             :  * relation. From given pathkeys expressions belonging entirely to the given
    3133             :  * base relation are obtained and deparsed.
    3134             :  */
    3135             : static void
    3136         776 : appendOrderByClause(List *pathkeys, deparse_expr_cxt *context)
    3137             : {
    3138             :     ListCell   *lcell;
    3139             :     int         nestlevel;
    3140         776 :     char       *delim = " ";
    3141         776 :     RelOptInfo *baserel = context->scanrel;
    3142         776 :     StringInfo  buf = context->buf;
    3143             : 
    3144             :     /* Make sure any constants in the exprs are printed portably */
    3145         776 :     nestlevel = set_transmission_modes();
    3146             : 
    3147         776 :     appendStringInfoString(buf, " ORDER BY");
    3148        1746 :     foreach(lcell, pathkeys)
    3149             :     {
    3150         970 :         PathKey    *pathkey = lfirst(lcell);
    3151             :         Expr       *em_expr;
    3152             : 
    3153         970 :         em_expr = find_em_expr_for_rel(pathkey->pk_eclass, baserel);
    3154             :         Assert(em_expr != NULL);
    3155             : 
    3156         970 :         appendStringInfoString(buf, delim);
    3157         970 :         deparseExpr(em_expr, context);
    3158         970 :         if (pathkey->pk_strategy == BTLessStrategyNumber)
    3159         960 :             appendStringInfoString(buf, " ASC");
    3160             :         else
    3161          10 :             appendStringInfoString(buf, " DESC");
    3162             : 
    3163         970 :         if (pathkey->pk_nulls_first)
    3164          10 :             appendStringInfoString(buf, " NULLS FIRST");
    3165             :         else
    3166         960 :             appendStringInfoString(buf, " NULLS LAST");
    3167             : 
    3168         970 :         delim = ", ";
    3169             :     }
    3170         776 :     reset_transmission_modes(nestlevel);
    3171         776 : }
    3172             : 
    3173             : /*
    3174             :  * appendFunctionName
    3175             :  *      Deparses function name from given function oid.
    3176             :  */
    3177             : static void
    3178         412 : appendFunctionName(Oid funcid, deparse_expr_cxt *context)
    3179             : {
    3180         412 :     StringInfo  buf = context->buf;
    3181             :     HeapTuple   proctup;
    3182             :     Form_pg_proc procform;
    3183             :     const char *proname;
    3184             : 
    3185         412 :     proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
    3186         412 :     if (!HeapTupleIsValid(proctup))
    3187           0 :         elog(ERROR, "cache lookup failed for function %u", funcid);
    3188         412 :     procform = (Form_pg_proc) GETSTRUCT(proctup);
    3189             : 
    3190             :     /* Print schema name only if it's not pg_catalog */
    3191         412 :     if (procform->pronamespace != PG_CATALOG_NAMESPACE)
    3192             :     {
    3193             :         const char *schemaname;
    3194             : 
    3195          12 :         schemaname = get_namespace_name(procform->pronamespace);
    3196          12 :         appendStringInfo(buf, "%s.", quote_identifier(schemaname));
    3197             :     }
    3198             : 
    3199             :     /* Always print the function name */
    3200         412 :     proname = NameStr(procform->proname);
    3201         412 :     appendStringInfoString(buf, quote_identifier(proname));
    3202             : 
    3203         412 :     ReleaseSysCache(proctup);
    3204         412 : }
    3205             : 
    3206             : /*
    3207             :  * Appends a sort or group clause.
    3208             :  *
    3209             :  * Like get_rule_sortgroupclause(), returns the expression tree, so caller
    3210             :  * need not find it again.
    3211             :  */
    3212             : static Node *
    3213         250 : deparseSortGroupClause(Index ref, List *tlist, bool force_colno,
    3214             :                        deparse_expr_cxt *context)
    3215             : {
    3216         250 :     StringInfo  buf = context->buf;
    3217             :     TargetEntry *tle;
    3218             :     Expr       *expr;
    3219             : 
    3220         250 :     tle = get_sortgroupref_tle(ref, tlist);
    3221         250 :     expr = tle->expr;
    3222             : 
    3223         250 :     if (force_colno)
    3224             :     {
    3225             :         /* Use column-number form when requested by caller. */
    3226             :         Assert(!tle->resjunk);
    3227         198 :         appendStringInfo(buf, "%d", tle->resno);
    3228             :     }
    3229          52 :     else if (expr && IsA(expr, Const))
    3230             :     {
    3231             :         /*
    3232             :          * Force a typecast here so that we don't emit something like "GROUP
    3233             :          * BY 2", which will be misconstrued as a column position rather than
    3234             :          * a constant.
    3235             :          */
    3236           0 :         deparseConst((Const *) expr, context, 1);
    3237             :     }
    3238          52 :     else if (!expr || IsA(expr, Var))
    3239          32 :         deparseExpr(expr, context);
    3240             :     else
    3241             :     {
    3242             :         /* Always parenthesize the expression. */
    3243          20 :         appendStringInfoChar(buf, '(');
    3244          20 :         deparseExpr(expr, context);
    3245          20 :         appendStringInfoChar(buf, ')');
    3246             :     }
    3247             : 
    3248         250 :     return (Node *) expr;
    3249             : }
    3250             : 
    3251             : 
    3252             : /*
    3253             :  * Returns true if given Var is deparsed as a subquery output column, in
    3254             :  * which case, *relno and *colno are set to the IDs for the relation and
    3255             :  * column alias to the Var provided by the subquery.
    3256             :  */
    3257             : static bool
    3258        8988 : is_subquery_var(Var *node, RelOptInfo *foreignrel, int *relno, int *colno)
    3259             : {
    3260        8988 :     PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) foreignrel->fdw_private;
    3261        8988 :     RelOptInfo *outerrel = fpinfo->outerrel;
    3262        8988 :     RelOptInfo *innerrel = fpinfo->innerrel;
    3263             : 
    3264             :     /* Should only be called in these cases. */
    3265             :     Assert(IS_SIMPLE_REL(foreignrel) || IS_JOIN_REL(foreignrel));
    3266             : 
    3267             :     /*
    3268             :      * If the given relation isn't a join relation, it doesn't have any lower
    3269             :      * subqueries, so the Var isn't a subquery output column.
    3270             :      */
    3271        8988 :     if (!IS_JOIN_REL(foreignrel))
    3272        2902 :         return false;
    3273             : 
    3274             :     /*
    3275             :      * If the Var doesn't belong to any lower subqueries, it isn't a subquery
    3276             :      * output column.
    3277             :      */
    3278        6086 :     if (!bms_is_member(node->varno, fpinfo->lower_subquery_rels))
    3279        5918 :         return false;
    3280             : 
    3281         168 :     if (bms_is_member(node->varno, outerrel->relids))
    3282             :     {
    3283             :         /*
    3284             :          * If outer relation is deparsed as a subquery, the Var is an output
    3285             :          * column of the subquery; get the IDs for the relation/column alias.
    3286             :          */
    3287          84 :         if (fpinfo->make_outerrel_subquery)
    3288             :         {
    3289          84 :             get_relation_column_alias_ids(node, outerrel, relno, colno);
    3290          84 :             return true;
    3291             :         }
    3292             : 
    3293             :         /* Otherwise, recurse into the outer relation. */
    3294           0 :         return is_subquery_var(node, outerrel, relno, colno);
    3295             :     }
    3296             :     else
    3297             :     {
    3298             :         Assert(bms_is_member(node->varno, innerrel->relids));
    3299             : 
    3300             :         /*
    3301             :          * If inner relation is deparsed as a subquery, the Var is an output
    3302             :          * column of the subquery; get the IDs for the relation/column alias.
    3303             :          */
    3304          84 :         if (fpinfo->make_innerrel_subquery)
    3305             :         {
    3306          84 :             get_relation_column_alias_ids(node, innerrel, relno, colno);
    3307          84 :             return true;
    3308             :         }
    3309             : 
    3310             :         /* Otherwise, recurse into the inner relation. */
    3311           0 :         return is_subquery_var(node, innerrel, relno, colno);
    3312             :     }
    3313             : }
    3314             : 
    3315             : /*
    3316             :  * Get the IDs for the relation and column alias to given Var belonging to
    3317             :  * given relation, which are returned into *relno and *colno.
    3318             :  */
    3319             : static void
    3320         168 : get_relation_column_alias_ids(Var *node, RelOptInfo *foreignrel,
    3321             :                               int *relno, int *colno)
    3322             : {
    3323         168 :     PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) foreignrel->fdw_private;
    3324             :     int         i;
    3325             :     ListCell   *lc;
    3326             : 
    3327             :     /* Get the relation alias ID */
    3328         168 :     *relno = fpinfo->relation_index;
    3329             : 
    3330             :     /* Get the column alias ID */
    3331         168 :     i = 1;
    3332         192 :     foreach(lc, foreignrel->reltarget->exprs)
    3333             :     {
    3334         192 :         if (equal(lfirst(lc), (Node *) node))
    3335             :         {
    3336         168 :             *colno = i;
    3337         168 :             return;
    3338             :         }
    3339          24 :         i++;
    3340             :     }
    3341             : 
    3342             :     /* Shouldn't get here */
    3343           0 :     elog(ERROR, "unexpected expression in subquery output");
    3344             : }

Generated by: LCOV version 1.13