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

Generated by: LCOV version 1.16