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

Generated by: LCOV version 1.13