LCOV - code coverage report
Current view: top level - contrib/postgres_fdw - deparse.c (source / functions) Coverage Total Hit
Test: PostgreSQL 20devel Lines: 88.7 % 1541 1367
Test Date: 2026-09-04 06:15:53 Functions: 100.0 % 63 63
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 76.2 % 1072 817

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

Generated by: LCOV version 2.0-1