LCOV - code coverage report
Current view: top level - src/backend/parser - parse_target.c (source / functions) Hit Total Coverage
Test: PostgreSQL 13devel Lines: 414 509 81.3 %
Date: 2019-11-21 12:06:29 Functions: 20 20 100.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*-------------------------------------------------------------------------
       2             :  *
       3             :  * parse_target.c
       4             :  *    handle target lists
       5             :  *
       6             :  * Portions Copyright (c) 1996-2019, PostgreSQL Global Development Group
       7             :  * Portions Copyright (c) 1994, Regents of the University of California
       8             :  *
       9             :  *
      10             :  * IDENTIFICATION
      11             :  *    src/backend/parser/parse_target.c
      12             :  *
      13             :  *-------------------------------------------------------------------------
      14             :  */
      15             : #include "postgres.h"
      16             : 
      17             : #include "catalog/pg_type.h"
      18             : #include "commands/dbcommands.h"
      19             : #include "funcapi.h"
      20             : #include "miscadmin.h"
      21             : #include "nodes/makefuncs.h"
      22             : #include "nodes/nodeFuncs.h"
      23             : #include "parser/parse_coerce.h"
      24             : #include "parser/parse_expr.h"
      25             : #include "parser/parse_func.h"
      26             : #include "parser/parse_relation.h"
      27             : #include "parser/parse_target.h"
      28             : #include "parser/parse_type.h"
      29             : #include "parser/parsetree.h"
      30             : #include "utils/builtins.h"
      31             : #include "utils/lsyscache.h"
      32             : #include "utils/rel.h"
      33             : #include "utils/typcache.h"
      34             : 
      35             : static void markTargetListOrigin(ParseState *pstate, TargetEntry *tle,
      36             :                                  Var *var, int levelsup);
      37             : static Node *transformAssignmentIndirection(ParseState *pstate,
      38             :                                             Node *basenode,
      39             :                                             const char *targetName,
      40             :                                             bool targetIsSubscripting,
      41             :                                             Oid targetTypeId,
      42             :                                             int32 targetTypMod,
      43             :                                             Oid targetCollation,
      44             :                                             List *indirection,
      45             :                                             ListCell *indirection_cell,
      46             :                                             Node *rhs,
      47             :                                             int location);
      48             : static Node *transformAssignmentSubscripts(ParseState *pstate,
      49             :                                            Node *basenode,
      50             :                                            const char *targetName,
      51             :                                            Oid targetTypeId,
      52             :                                            int32 targetTypMod,
      53             :                                            Oid targetCollation,
      54             :                                            List *subscripts,
      55             :                                            bool isSlice,
      56             :                                            List *indirection,
      57             :                                            ListCell *next_indirection,
      58             :                                            Node *rhs,
      59             :                                            int location);
      60             : static List *ExpandColumnRefStar(ParseState *pstate, ColumnRef *cref,
      61             :                                  bool make_target_entry);
      62             : static List *ExpandAllTables(ParseState *pstate, int location);
      63             : static List *ExpandIndirectionStar(ParseState *pstate, A_Indirection *ind,
      64             :                                    bool make_target_entry, ParseExprKind exprKind);
      65             : static List *ExpandSingleTable(ParseState *pstate, RangeTblEntry *rte,
      66             :                                int location, bool make_target_entry);
      67             : static List *ExpandRowReference(ParseState *pstate, Node *expr,
      68             :                                 bool make_target_entry);
      69             : static int  FigureColnameInternal(Node *node, char **name);
      70             : 
      71             : 
      72             : /*
      73             :  * transformTargetEntry()
      74             :  *  Transform any ordinary "expression-type" node into a targetlist entry.
      75             :  *  This is exported so that parse_clause.c can generate targetlist entries
      76             :  *  for ORDER/GROUP BY items that are not already in the targetlist.
      77             :  *
      78             :  * node     the (untransformed) parse tree for the value expression.
      79             :  * expr     the transformed expression, or NULL if caller didn't do it yet.
      80             :  * exprKind expression kind (EXPR_KIND_SELECT_TARGET, etc)
      81             :  * colname  the column name to be assigned, or NULL if none yet set.
      82             :  * resjunk  true if the target should be marked resjunk, ie, it is not
      83             :  *          wanted in the final projected tuple.
      84             :  */
      85             : TargetEntry *
      86     1172352 : transformTargetEntry(ParseState *pstate,
      87             :                      Node *node,
      88             :                      Node *expr,
      89             :                      ParseExprKind exprKind,
      90             :                      char *colname,
      91             :                      bool resjunk)
      92             : {
      93             :     /* Transform the node if caller didn't do it already */
      94     1172352 :     if (expr == NULL)
      95             :     {
      96             :         /*
      97             :          * If it's a SetToDefault node and we should allow that, pass it
      98             :          * through unmodified.  (transformExpr will throw the appropriate
      99             :          * error if we're disallowing it.)
     100             :          */
     101     1145834 :         if (exprKind == EXPR_KIND_UPDATE_SOURCE && IsA(node, SetToDefault))
     102          92 :             expr = node;
     103             :         else
     104     1145742 :             expr = transformExpr(pstate, node, exprKind);
     105             :     }
     106             : 
     107     1170632 :     if (colname == NULL && !resjunk)
     108             :     {
     109             :         /*
     110             :          * Generate a suitable column name for a column without any explicit
     111             :          * 'AS ColumnName' clause.
     112             :          */
     113      703408 :         colname = FigureColname(node);
     114             :     }
     115             : 
     116     2341264 :     return makeTargetEntry((Expr *) expr,
     117     1170632 :                            (AttrNumber) pstate->p_next_resno++,
     118             :                            colname,
     119             :                            resjunk);
     120             : }
     121             : 
     122             : 
     123             : /*
     124             :  * transformTargetList()
     125             :  * Turns a list of ResTarget's into a list of TargetEntry's.
     126             :  *
     127             :  * This code acts mostly the same for SELECT, UPDATE, or RETURNING lists;
     128             :  * the main thing is to transform the given expressions (the "val" fields).
     129             :  * The exprKind parameter distinguishes these cases when necessary.
     130             :  */
     131             : List *
     132      352866 : transformTargetList(ParseState *pstate, List *targetlist,
     133             :                     ParseExprKind exprKind)
     134             : {
     135      352866 :     List       *p_target = NIL;
     136             :     bool        expand_star;
     137             :     ListCell   *o_target;
     138             : 
     139             :     /* Shouldn't have any leftover multiassign items at start */
     140             :     Assert(pstate->p_multiassign_exprs == NIL);
     141             : 
     142             :     /* Expand "something.*" in SELECT and RETURNING, but not UPDATE */
     143      352866 :     expand_star = (exprKind != EXPR_KIND_UPDATE_SOURCE);
     144             : 
     145     1530582 :     foreach(o_target, targetlist)
     146             :     {
     147     1179440 :         ResTarget  *res = (ResTarget *) lfirst(o_target);
     148             : 
     149             :         /*
     150             :          * Check for "something.*".  Depending on the complexity of the
     151             :          * "something", the star could appear as the last field in ColumnRef,
     152             :          * or as the last indirection item in A_Indirection.
     153             :          */
     154     1179440 :         if (expand_star)
     155             :         {
     156     1166512 :             if (IsA(res->val, ColumnRef))
     157             :             {
     158      589212 :                 ColumnRef  *cref = (ColumnRef *) res->val;
     159             : 
     160      589212 :                 if (IsA(llast(cref->fields), A_Star))
     161             :                 {
     162             :                     /* It is something.*, expand into multiple items */
     163       30638 :                     p_target = list_concat(p_target,
     164       30642 :                                            ExpandColumnRefStar(pstate,
     165             :                                                                cref,
     166             :                                                                true));
     167       30638 :                     continue;
     168             :                 }
     169             :             }
     170      577300 :             else if (IsA(res->val, A_Indirection))
     171             :             {
     172        5574 :                 A_Indirection *ind = (A_Indirection *) res->val;
     173             : 
     174        5574 :                 if (IsA(llast(ind->indirection), A_Star))
     175             :                 {
     176             :                     /* It is something.*, expand into multiple items */
     177        2964 :                     p_target = list_concat(p_target,
     178        2964 :                                            ExpandIndirectionStar(pstate,
     179             :                                                                  ind,
     180             :                                                                  true,
     181             :                                                                  exprKind));
     182        2964 :                     continue;
     183             :                 }
     184             :             }
     185             :         }
     186             : 
     187             :         /*
     188             :          * Not "something.*", or we want to treat that as a plain whole-row
     189             :          * variable, so transform as a single expression
     190             :          */
     191     1144114 :         p_target = lappend(p_target,
     192     1145834 :                            transformTargetEntry(pstate,
     193             :                                                 res->val,
     194             :                                                 NULL,
     195             :                                                 exprKind,
     196             :                                                 res->name,
     197             :                                                 false));
     198             :     }
     199             : 
     200             :     /*
     201             :      * If any multiassign resjunk items were created, attach them to the end
     202             :      * of the targetlist.  This should only happen in an UPDATE tlist.  We
     203             :      * don't need to worry about numbering of these items; transformUpdateStmt
     204             :      * will set their resnos.
     205             :      */
     206      351142 :     if (pstate->p_multiassign_exprs)
     207             :     {
     208             :         Assert(exprKind == EXPR_KIND_UPDATE_SOURCE);
     209          52 :         p_target = list_concat(p_target, pstate->p_multiassign_exprs);
     210          52 :         pstate->p_multiassign_exprs = NIL;
     211             :     }
     212             : 
     213      351142 :     return p_target;
     214             : }
     215             : 
     216             : 
     217             : /*
     218             :  * transformExpressionList()
     219             :  *
     220             :  * This is the identical transformation to transformTargetList, except that
     221             :  * the input list elements are bare expressions without ResTarget decoration,
     222             :  * and the output elements are likewise just expressions without TargetEntry
     223             :  * decoration.  We use this for ROW() and VALUES() constructs.
     224             :  *
     225             :  * exprKind is not enough to tell us whether to allow SetToDefault, so
     226             :  * an additional flag is needed for that.
     227             :  */
     228             : List *
     229       64140 : transformExpressionList(ParseState *pstate, List *exprlist,
     230             :                         ParseExprKind exprKind, bool allowDefault)
     231             : {
     232       64140 :     List       *result = NIL;
     233             :     ListCell   *lc;
     234             : 
     235      224674 :     foreach(lc, exprlist)
     236             :     {
     237      160556 :         Node       *e = (Node *) lfirst(lc);
     238             : 
     239             :         /*
     240             :          * Check for "something.*".  Depending on the complexity of the
     241             :          * "something", the star could appear as the last field in ColumnRef,
     242             :          * or as the last indirection item in A_Indirection.
     243             :          */
     244      160556 :         if (IsA(e, ColumnRef))
     245             :         {
     246        8166 :             ColumnRef  *cref = (ColumnRef *) e;
     247             : 
     248        8166 :             if (IsA(llast(cref->fields), A_Star))
     249             :             {
     250             :                 /* It is something.*, expand into multiple items */
     251         152 :                 result = list_concat(result,
     252         152 :                                      ExpandColumnRefStar(pstate, cref,
     253             :                                                          false));
     254         152 :                 continue;
     255             :             }
     256             :         }
     257      152390 :         else if (IsA(e, A_Indirection))
     258             :         {
     259          16 :             A_Indirection *ind = (A_Indirection *) e;
     260             : 
     261          16 :             if (IsA(llast(ind->indirection), A_Star))
     262             :             {
     263             :                 /* It is something.*, expand into multiple items */
     264           0 :                 result = list_concat(result,
     265           0 :                                      ExpandIndirectionStar(pstate, ind,
     266             :                                                            false, exprKind));
     267           0 :                 continue;
     268             :             }
     269             :         }
     270             : 
     271             :         /*
     272             :          * Not "something.*", so transform as a single expression.  If it's a
     273             :          * SetToDefault node and we should allow that, pass it through
     274             :          * unmodified.  (transformExpr will throw the appropriate error if
     275             :          * we're disallowing it.)
     276             :          */
     277      160404 :         if (allowDefault && IsA(e, SetToDefault))
     278             :              /* do nothing */ ;
     279             :         else
     280      159798 :             e = transformExpr(pstate, e, exprKind);
     281             : 
     282      160382 :         result = lappend(result, e);
     283             :     }
     284             : 
     285             :     /* Shouldn't have any multiassign items here */
     286             :     Assert(pstate->p_multiassign_exprs == NIL);
     287             : 
     288       64118 :     return result;
     289             : }
     290             : 
     291             : 
     292             : /*
     293             :  * resolveTargetListUnknowns()
     294             :  *      Convert any unknown-type targetlist entries to type TEXT.
     295             :  *
     296             :  * We do this after we've exhausted all other ways of identifying the output
     297             :  * column types of a query.
     298             :  */
     299             : void
     300      302238 : resolveTargetListUnknowns(ParseState *pstate, List *targetlist)
     301             : {
     302             :     ListCell   *l;
     303             : 
     304     1415784 :     foreach(l, targetlist)
     305             :     {
     306     1113546 :         TargetEntry *tle = (TargetEntry *) lfirst(l);
     307     1113546 :         Oid         restype = exprType((Node *) tle->expr);
     308             : 
     309     1113546 :         if (restype == UNKNOWNOID)
     310             :         {
     311        8484 :             tle->expr = (Expr *) coerce_type(pstate, (Node *) tle->expr,
     312             :                                              restype, TEXTOID, -1,
     313             :                                              COERCION_IMPLICIT,
     314             :                                              COERCE_IMPLICIT_CAST,
     315             :                                              -1);
     316             :         }
     317             :     }
     318      302238 : }
     319             : 
     320             : 
     321             : /*
     322             :  * markTargetListOrigins()
     323             :  *      Mark targetlist columns that are simple Vars with the source
     324             :  *      table's OID and column number.
     325             :  *
     326             :  * Currently, this is done only for SELECT targetlists and RETURNING lists,
     327             :  * since we only need the info if we are going to send it to the frontend.
     328             :  */
     329             : void
     330      341028 : markTargetListOrigins(ParseState *pstate, List *targetlist)
     331             : {
     332             :     ListCell   *l;
     333             : 
     334     1618562 :     foreach(l, targetlist)
     335             :     {
     336     1277534 :         TargetEntry *tle = (TargetEntry *) lfirst(l);
     337             : 
     338     1277534 :         markTargetListOrigin(pstate, tle, (Var *) tle->expr, 0);
     339             :     }
     340      341028 : }
     341             : 
     342             : /*
     343             :  * markTargetListOrigin()
     344             :  *      If 'var' is a Var of a plain relation, mark 'tle' with its origin
     345             :  *
     346             :  * levelsup is an extra offset to interpret the Var's varlevelsup correctly.
     347             :  *
     348             :  * This is split out so it can recurse for join references.  Note that we
     349             :  * do not drill down into views, but report the view as the column owner.
     350             :  */
     351             : static void
     352     1303212 : markTargetListOrigin(ParseState *pstate, TargetEntry *tle,
     353             :                      Var *var, int levelsup)
     354             : {
     355             :     int         netlevelsup;
     356             :     RangeTblEntry *rte;
     357             :     AttrNumber  attnum;
     358             : 
     359     1303212 :     if (var == NULL || !IsA(var, Var))
     360      590516 :         return;
     361      712696 :     netlevelsup = var->varlevelsup + levelsup;
     362      712696 :     rte = GetRTEByRangeTablePosn(pstate, var->varno, netlevelsup);
     363      712696 :     attnum = var->varattno;
     364             : 
     365      712696 :     switch (rte->rtekind)
     366             :     {
     367             :         case RTE_RELATION:
     368             :             /* It's a table or view, report it */
     369      578356 :             tle->resorigtbl = rte->relid;
     370      578356 :             tle->resorigcol = attnum;
     371      578356 :             break;
     372             :         case RTE_SUBQUERY:
     373             :             /* Subselect-in-FROM: copy up from the subselect */
     374       11832 :             if (attnum != InvalidAttrNumber)
     375             :             {
     376       11804 :                 TargetEntry *ste = get_tle_by_resno(rte->subquery->targetList,
     377             :                                                     attnum);
     378             : 
     379       11804 :                 if (ste == NULL || ste->resjunk)
     380           0 :                     elog(ERROR, "subquery %s does not have attribute %d",
     381             :                          rte->eref->aliasname, attnum);
     382       11804 :                 tle->resorigtbl = ste->resorigtbl;
     383       11804 :                 tle->resorigcol = ste->resorigcol;
     384             :             }
     385       11832 :             break;
     386             :         case RTE_JOIN:
     387             :             /* Join RTE --- recursively inspect the alias variable */
     388       25678 :             if (attnum != InvalidAttrNumber)
     389             :             {
     390             :                 Var        *aliasvar;
     391             : 
     392             :                 Assert(attnum > 0 && attnum <= list_length(rte->joinaliasvars));
     393       25678 :                 aliasvar = (Var *) list_nth(rte->joinaliasvars, attnum - 1);
     394             :                 /* We intentionally don't strip implicit coercions here */
     395       25678 :                 markTargetListOrigin(pstate, tle, aliasvar, netlevelsup);
     396             :             }
     397       25678 :             break;
     398             :         case RTE_FUNCTION:
     399             :         case RTE_VALUES:
     400             :         case RTE_TABLEFUNC:
     401             :         case RTE_NAMEDTUPLESTORE:
     402             :         case RTE_RESULT:
     403             :             /* not a simple relation, leave it unmarked */
     404       94546 :             break;
     405             :         case RTE_CTE:
     406             : 
     407             :             /*
     408             :              * CTE reference: copy up from the subquery, if possible. If the
     409             :              * RTE is a recursive self-reference then we can't do anything
     410             :              * because we haven't finished analyzing it yet. However, it's no
     411             :              * big loss because we must be down inside the recursive term of a
     412             :              * recursive CTE, and so any markings on the current targetlist
     413             :              * are not going to affect the results anyway.
     414             :              */
     415        2284 :             if (attnum != InvalidAttrNumber && !rte->self_reference)
     416             :             {
     417        2064 :                 CommonTableExpr *cte = GetCTEForRTE(pstate, rte, netlevelsup);
     418             :                 TargetEntry *ste;
     419             : 
     420        2064 :                 ste = get_tle_by_resno(GetCTETargetList(cte), attnum);
     421        2064 :                 if (ste == NULL || ste->resjunk)
     422           0 :                     elog(ERROR, "subquery %s does not have attribute %d",
     423             :                          rte->eref->aliasname, attnum);
     424        2064 :                 tle->resorigtbl = ste->resorigtbl;
     425        2064 :                 tle->resorigcol = ste->resorigcol;
     426             :             }
     427        2284 :             break;
     428             :     }
     429             : }
     430             : 
     431             : 
     432             : /*
     433             :  * transformAssignedExpr()
     434             :  *  This is used in INSERT and UPDATE statements only.  It prepares an
     435             :  *  expression for assignment to a column of the target table.
     436             :  *  This includes coercing the given value to the target column's type
     437             :  *  (if necessary), and dealing with any subfield names or subscripts
     438             :  *  attached to the target column itself.  The input expression has
     439             :  *  already been through transformExpr().
     440             :  *
     441             :  * pstate       parse state
     442             :  * expr         expression to be modified
     443             :  * exprKind     indicates which type of statement we're dealing with
     444             :  * colname      target column name (ie, name of attribute to be assigned to)
     445             :  * attrno       target attribute number
     446             :  * indirection  subscripts/field names for target column, if any
     447             :  * location     error cursor position for the target column, or -1
     448             :  *
     449             :  * Returns the modified expression.
     450             :  *
     451             :  * Note: location points at the target column name (SET target or INSERT
     452             :  * column name list entry), and must therefore be -1 in an INSERT that
     453             :  * omits the column name list.  So we should usually prefer to use
     454             :  * exprLocation(expr) for errors that can happen in a default INSERT.
     455             :  */
     456             : Expr *
     457      224646 : transformAssignedExpr(ParseState *pstate,
     458             :                       Expr *expr,
     459             :                       ParseExprKind exprKind,
     460             :                       const char *colname,
     461             :                       int attrno,
     462             :                       List *indirection,
     463             :                       int location)
     464             : {
     465      224646 :     Relation    rd = pstate->p_target_relation;
     466             :     Oid         type_id;        /* type of value provided */
     467             :     Oid         attrtype;       /* type of target column */
     468             :     int32       attrtypmod;
     469             :     Oid         attrcollation;  /* collation of target column */
     470             :     ParseExprKind sv_expr_kind;
     471             : 
     472             :     /*
     473             :      * Save and restore identity of expression type we're parsing.  We must
     474             :      * set p_expr_kind here because we can parse subscripts without going
     475             :      * through transformExpr().
     476             :      */
     477             :     Assert(exprKind != EXPR_KIND_NONE);
     478      224646 :     sv_expr_kind = pstate->p_expr_kind;
     479      224646 :     pstate->p_expr_kind = exprKind;
     480             : 
     481             :     Assert(rd != NULL);
     482      224646 :     if (attrno <= 0)
     483           0 :         ereport(ERROR,
     484             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     485             :                  errmsg("cannot assign to system column \"%s\"",
     486             :                         colname),
     487             :                  parser_errposition(pstate, location)));
     488      224646 :     attrtype = attnumTypeId(rd, attrno);
     489      224646 :     attrtypmod = TupleDescAttr(rd->rd_att, attrno - 1)->atttypmod;
     490      224646 :     attrcollation = TupleDescAttr(rd->rd_att, attrno - 1)->attcollation;
     491             : 
     492             :     /*
     493             :      * If the expression is a DEFAULT placeholder, insert the attribute's
     494             :      * type/typmod/collation into it so that exprType etc will report the
     495             :      * right things.  (We expect that the eventually substituted default
     496             :      * expression will in fact have this type and typmod.  The collation
     497             :      * likely doesn't matter, but let's set it correctly anyway.)  Also,
     498             :      * reject trying to update a subfield or array element with DEFAULT, since
     499             :      * there can't be any default for portions of a column.
     500             :      */
     501      224646 :     if (expr && IsA(expr, SetToDefault))
     502             :     {
     503         678 :         SetToDefault *def = (SetToDefault *) expr;
     504             : 
     505         678 :         def->typeId = attrtype;
     506         678 :         def->typeMod = attrtypmod;
     507         678 :         def->collation = attrcollation;
     508         678 :         if (indirection)
     509             :         {
     510           8 :             if (IsA(linitial(indirection), A_Indices))
     511           4 :                 ereport(ERROR,
     512             :                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     513             :                          errmsg("cannot set an array element to DEFAULT"),
     514             :                          parser_errposition(pstate, location)));
     515             :             else
     516           4 :                 ereport(ERROR,
     517             :                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     518             :                          errmsg("cannot set a subfield to DEFAULT"),
     519             :                          parser_errposition(pstate, location)));
     520             :         }
     521             :     }
     522             : 
     523             :     /* Now we can use exprType() safely. */
     524      224638 :     type_id = exprType((Node *) expr);
     525             : 
     526             :     /*
     527             :      * If there is indirection on the target column, prepare an array or
     528             :      * subfield assignment expression.  This will generate a new column value
     529             :      * that the source value has been inserted into, which can then be placed
     530             :      * in the new tuple constructed by INSERT or UPDATE.
     531             :      */
     532      224638 :     if (indirection)
     533             :     {
     534             :         Node       *colVar;
     535             : 
     536         710 :         if (pstate->p_is_insert)
     537             :         {
     538             :             /*
     539             :              * The command is INSERT INTO table (col.something) ... so there
     540             :              * is not really a source value to work with. Insert a NULL
     541             :              * constant as the source value.
     542             :              */
     543         368 :             colVar = (Node *) makeNullConst(attrtype, attrtypmod,
     544             :                                             attrcollation);
     545             :         }
     546             :         else
     547             :         {
     548             :             /*
     549             :              * Build a Var for the column to be updated.
     550             :              */
     551         342 :             colVar = (Node *) make_var(pstate,
     552             :                                        pstate->p_target_rangetblentry,
     553             :                                        attrno,
     554             :                                        location);
     555             :         }
     556             : 
     557         710 :         expr = (Expr *)
     558         710 :             transformAssignmentIndirection(pstate,
     559             :                                            colVar,
     560             :                                            colname,
     561             :                                            false,
     562             :                                            attrtype,
     563             :                                            attrtypmod,
     564             :                                            attrcollation,
     565             :                                            indirection,
     566             :                                            list_head(indirection),
     567             :                                            (Node *) expr,
     568             :                                            location);
     569             :     }
     570             :     else
     571             :     {
     572             :         /*
     573             :          * For normal non-qualified target column, do type checking and
     574             :          * coercion.
     575             :          */
     576      223928 :         Node       *orig_expr = (Node *) expr;
     577             : 
     578      223928 :         expr = (Expr *)
     579             :             coerce_to_target_type(pstate,
     580             :                                   orig_expr, type_id,
     581             :                                   attrtype, attrtypmod,
     582             :                                   COERCION_ASSIGNMENT,
     583             :                                   COERCE_IMPLICIT_CAST,
     584             :                                   -1);
     585      223324 :         if (expr == NULL)
     586         132 :             ereport(ERROR,
     587             :                     (errcode(ERRCODE_DATATYPE_MISMATCH),
     588             :                      errmsg("column \"%s\" is of type %s"
     589             :                             " but expression is of type %s",
     590             :                             colname,
     591             :                             format_type_be(attrtype),
     592             :                             format_type_be(type_id)),
     593             :                      errhint("You will need to rewrite or cast the expression."),
     594             :                      parser_errposition(pstate, exprLocation(orig_expr))));
     595             :     }
     596             : 
     597      223902 :     pstate->p_expr_kind = sv_expr_kind;
     598             : 
     599      223902 :     return expr;
     600             : }
     601             : 
     602             : 
     603             : /*
     604             :  * updateTargetListEntry()
     605             :  *  This is used in UPDATE statements (and ON CONFLICT DO UPDATE)
     606             :  *  only.  It prepares an UPDATE TargetEntry for assignment to a
     607             :  *  column of the target table.  This includes coercing the given
     608             :  *  value to the target column's type (if necessary), and dealing with
     609             :  *  any subfield names or subscripts attached to the target column
     610             :  *  itself.
     611             :  *
     612             :  * pstate       parse state
     613             :  * tle          target list entry to be modified
     614             :  * colname      target column name (ie, name of attribute to be assigned to)
     615             :  * attrno       target attribute number
     616             :  * indirection  subscripts/field names for target column, if any
     617             :  * location     error cursor position (should point at column name), or -1
     618             :  */
     619             : void
     620       12892 : updateTargetListEntry(ParseState *pstate,
     621             :                       TargetEntry *tle,
     622             :                       char *colname,
     623             :                       int attrno,
     624             :                       List *indirection,
     625             :                       int location)
     626             : {
     627             :     /* Fix up expression as needed */
     628       12892 :     tle->expr = transformAssignedExpr(pstate,
     629             :                                       tle->expr,
     630             :                                       EXPR_KIND_UPDATE_TARGET,
     631             :                                       colname,
     632             :                                       attrno,
     633             :                                       indirection,
     634             :                                       location);
     635             : 
     636             :     /*
     637             :      * Set the resno to identify the target column --- the rewriter and
     638             :      * planner depend on this.  We also set the resname to identify the target
     639             :      * column, but this is only for debugging purposes; it should not be
     640             :      * relied on.  (In particular, it might be out of date in a stored rule.)
     641             :      */
     642       12888 :     tle->resno = (AttrNumber) attrno;
     643       12888 :     tle->resname = colname;
     644       12888 : }
     645             : 
     646             : 
     647             : /*
     648             :  * Process indirection (field selection or subscripting) of the target
     649             :  * column in INSERT/UPDATE.  This routine recurses for multiple levels
     650             :  * of indirection --- but note that several adjacent A_Indices nodes in
     651             :  * the indirection list are treated as a single multidimensional subscript
     652             :  * operation.
     653             :  *
     654             :  * In the initial call, basenode is a Var for the target column in UPDATE,
     655             :  * or a null Const of the target's type in INSERT.  In recursive calls,
     656             :  * basenode is NULL, indicating that a substitute node should be consed up if
     657             :  * needed.
     658             :  *
     659             :  * targetName is the name of the field or subfield we're assigning to, and
     660             :  * targetIsSubscripting is true if we're subscripting it.  These are just for
     661             :  * error reporting.
     662             :  *
     663             :  * targetTypeId, targetTypMod, targetCollation indicate the datatype and
     664             :  * collation of the object to be assigned to (initially the target column,
     665             :  * later some subobject).
     666             :  *
     667             :  * indirection is the list of indirection nodes, and indirection_cell is the
     668             :  * start of the sublist remaining to process.  When it's NULL, we're done
     669             :  * recursing and can just coerce and return the RHS.
     670             :  *
     671             :  * rhs is the already-transformed value to be assigned; note it has not been
     672             :  * coerced to any particular type.
     673             :  *
     674             :  * location is the cursor error position for any errors.  (Note: this points
     675             :  * to the head of the target clause, eg "foo" in "foo.bar[baz]".  Later we
     676             :  * might want to decorate indirection cells with their own location info,
     677             :  * in which case the location argument could probably be dropped.)
     678             :  */
     679             : static Node *
     680        1668 : transformAssignmentIndirection(ParseState *pstate,
     681             :                                Node *basenode,
     682             :                                const char *targetName,
     683             :                                bool targetIsSubscripting,
     684             :                                Oid targetTypeId,
     685             :                                int32 targetTypMod,
     686             :                                Oid targetCollation,
     687             :                                List *indirection,
     688             :                                ListCell *indirection_cell,
     689             :                                Node *rhs,
     690             :                                int location)
     691             : {
     692             :     Node       *result;
     693        1668 :     List       *subscripts = NIL;
     694        1668 :     bool        isSlice = false;
     695             :     ListCell   *i;
     696             : 
     697        1668 :     if (indirection_cell && !basenode)
     698             :     {
     699             :         /*
     700             :          * Set up a substitution.  We abuse CaseTestExpr for this.  It's safe
     701             :          * to do so because the only nodes that will be above the CaseTestExpr
     702             :          * in the finished expression will be FieldStore and SubscriptingRef
     703             :          * nodes. (There could be other stuff in the tree, but it will be
     704             :          * within other child fields of those node types.)
     705             :          */
     706         248 :         CaseTestExpr *ctest = makeNode(CaseTestExpr);
     707             : 
     708         248 :         ctest->typeId = targetTypeId;
     709         248 :         ctest->typeMod = targetTypMod;
     710         248 :         ctest->collation = targetCollation;
     711         248 :         basenode = (Node *) ctest;
     712             :     }
     713             : 
     714             :     /*
     715             :      * We have to split any field-selection operations apart from
     716             :      * subscripting.  Adjacent A_Indices nodes have to be treated as a single
     717             :      * multidimensional subscript operation.
     718             :      */
     719        2362 :     for_each_cell(i, indirection, indirection_cell)
     720             :     {
     721        1134 :         Node       *n = lfirst(i);
     722             : 
     723        1134 :         if (IsA(n, A_Indices))
     724             :         {
     725         694 :             subscripts = lappend(subscripts, n);
     726         694 :             if (((A_Indices *) n)->is_slice)
     727         176 :                 isSlice = true;
     728             :         }
     729         440 :         else if (IsA(n, A_Star))
     730             :         {
     731           0 :             ereport(ERROR,
     732             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     733             :                      errmsg("row expansion via \"*\" is not supported here"),
     734             :                      parser_errposition(pstate, location)));
     735             :         }
     736             :         else
     737             :         {
     738             :             FieldStore *fstore;
     739             :             Oid         baseTypeId;
     740             :             int32       baseTypeMod;
     741             :             Oid         typrelid;
     742             :             AttrNumber  attnum;
     743             :             Oid         fieldTypeId;
     744             :             int32       fieldTypMod;
     745             :             Oid         fieldCollation;
     746             : 
     747             :             Assert(IsA(n, String));
     748             : 
     749             :             /* process subscripts before this field selection */
     750         440 :             if (subscripts)
     751             :             {
     752             :                 /* recurse, and then return because we're done */
     753         136 :                 return transformAssignmentSubscripts(pstate,
     754             :                                                      basenode,
     755             :                                                      targetName,
     756             :                                                      targetTypeId,
     757             :                                                      targetTypMod,
     758             :                                                      targetCollation,
     759             :                                                      subscripts,
     760             :                                                      isSlice,
     761             :                                                      indirection,
     762             :                                                      i,
     763             :                                                      rhs,
     764             :                                                      location);
     765             :             }
     766             : 
     767             :             /* No subscripts, so can process field selection here */
     768             : 
     769             :             /*
     770             :              * Look up the composite type, accounting for possibility that
     771             :              * what we are given is a domain over composite.
     772             :              */
     773         304 :             baseTypeMod = targetTypMod;
     774         304 :             baseTypeId = getBaseTypeAndTypmod(targetTypeId, &baseTypeMod);
     775             : 
     776         304 :             typrelid = typeidTypeRelid(baseTypeId);
     777         304 :             if (!typrelid)
     778           0 :                 ereport(ERROR,
     779             :                         (errcode(ERRCODE_DATATYPE_MISMATCH),
     780             :                          errmsg("cannot assign to field \"%s\" of column \"%s\" because its type %s is not a composite type",
     781             :                                 strVal(n), targetName,
     782             :                                 format_type_be(targetTypeId)),
     783             :                          parser_errposition(pstate, location)));
     784             : 
     785         304 :             attnum = get_attnum(typrelid, strVal(n));
     786         304 :             if (attnum == InvalidAttrNumber)
     787           0 :                 ereport(ERROR,
     788             :                         (errcode(ERRCODE_UNDEFINED_COLUMN),
     789             :                          errmsg("cannot assign to field \"%s\" of column \"%s\" because there is no such column in data type %s",
     790             :                                 strVal(n), targetName,
     791             :                                 format_type_be(targetTypeId)),
     792             :                          parser_errposition(pstate, location)));
     793         304 :             if (attnum < 0)
     794           0 :                 ereport(ERROR,
     795             :                         (errcode(ERRCODE_UNDEFINED_COLUMN),
     796             :                          errmsg("cannot assign to system column \"%s\"",
     797             :                                 strVal(n)),
     798             :                          parser_errposition(pstate, location)));
     799             : 
     800         304 :             get_atttypetypmodcoll(typrelid, attnum,
     801             :                                   &fieldTypeId, &fieldTypMod, &fieldCollation);
     802             : 
     803             :             /* recurse to create appropriate RHS for field assign */
     804         608 :             rhs = transformAssignmentIndirection(pstate,
     805             :                                                  NULL,
     806         304 :                                                  strVal(n),
     807             :                                                  false,
     808             :                                                  fieldTypeId,
     809             :                                                  fieldTypMod,
     810             :                                                  fieldCollation,
     811             :                                                  indirection,
     812             :                                                  lnext(indirection, i),
     813             :                                                  rhs,
     814             :                                                  location);
     815             : 
     816             :             /* and build a FieldStore node */
     817         304 :             fstore = makeNode(FieldStore);
     818         304 :             fstore->arg = (Expr *) basenode;
     819         304 :             fstore->newvals = list_make1(rhs);
     820         304 :             fstore->fieldnums = list_make1_int(attnum);
     821         304 :             fstore->resulttype = baseTypeId;
     822             : 
     823             :             /* If target is a domain, apply constraints */
     824         304 :             if (baseTypeId != targetTypeId)
     825          56 :                 return coerce_to_domain((Node *) fstore,
     826             :                                         baseTypeId, baseTypeMod,
     827             :                                         targetTypeId,
     828             :                                         COERCION_IMPLICIT,
     829             :                                         COERCE_IMPLICIT_CAST,
     830             :                                         location,
     831             :                                         false);
     832             : 
     833         248 :             return (Node *) fstore;
     834             :         }
     835             :     }
     836             : 
     837             :     /* process trailing subscripts, if any */
     838        1228 :     if (subscripts)
     839             :     {
     840             :         /* recurse, and then return because we're done */
     841         518 :         return transformAssignmentSubscripts(pstate,
     842             :                                              basenode,
     843             :                                              targetName,
     844             :                                              targetTypeId,
     845             :                                              targetTypMod,
     846             :                                              targetCollation,
     847             :                                              subscripts,
     848             :                                              isSlice,
     849             :                                              indirection,
     850             :                                              NULL,
     851             :                                              rhs,
     852             :                                              location);
     853             :     }
     854             : 
     855             :     /* base case: just coerce RHS to match target type ID */
     856             : 
     857         710 :     result = coerce_to_target_type(pstate,
     858             :                                    rhs, exprType(rhs),
     859             :                                    targetTypeId, targetTypMod,
     860             :                                    COERCION_ASSIGNMENT,
     861             :                                    COERCE_IMPLICIT_CAST,
     862             :                                    -1);
     863         710 :     if (result == NULL)
     864             :     {
     865           0 :         if (targetIsSubscripting)
     866           0 :             ereport(ERROR,
     867             :                     (errcode(ERRCODE_DATATYPE_MISMATCH),
     868             :                      errmsg("array assignment to \"%s\" requires type %s"
     869             :                             " but expression is of type %s",
     870             :                             targetName,
     871             :                             format_type_be(targetTypeId),
     872             :                             format_type_be(exprType(rhs))),
     873             :                      errhint("You will need to rewrite or cast the expression."),
     874             :                      parser_errposition(pstate, location)));
     875             :         else
     876           0 :             ereport(ERROR,
     877             :                     (errcode(ERRCODE_DATATYPE_MISMATCH),
     878             :                      errmsg("subfield \"%s\" is of type %s"
     879             :                             " but expression is of type %s",
     880             :                             targetName,
     881             :                             format_type_be(targetTypeId),
     882             :                             format_type_be(exprType(rhs))),
     883             :                      errhint("You will need to rewrite or cast the expression."),
     884             :                      parser_errposition(pstate, location)));
     885             :     }
     886             : 
     887         710 :     return result;
     888             : }
     889             : 
     890             : /*
     891             :  * helper for transformAssignmentIndirection: process container assignment
     892             :  */
     893             : static Node *
     894         654 : transformAssignmentSubscripts(ParseState *pstate,
     895             :                               Node *basenode,
     896             :                               const char *targetName,
     897             :                               Oid targetTypeId,
     898             :                               int32 targetTypMod,
     899             :                               Oid targetCollation,
     900             :                               List *subscripts,
     901             :                               bool isSlice,
     902             :                               List *indirection,
     903             :                               ListCell *next_indirection,
     904             :                               Node *rhs,
     905             :                               int location)
     906             : {
     907             :     Node       *result;
     908             :     Oid         containerType;
     909             :     int32       containerTypMod;
     910             :     Oid         elementTypeId;
     911             :     Oid         typeNeeded;
     912             :     Oid         collationNeeded;
     913             : 
     914             :     Assert(subscripts != NIL);
     915             : 
     916             :     /* Identify the actual array type and element type involved */
     917         654 :     containerType = targetTypeId;
     918         654 :     containerTypMod = targetTypMod;
     919         654 :     elementTypeId = transformContainerType(&containerType, &containerTypMod);
     920             : 
     921             :     /* Identify type that RHS must provide */
     922         654 :     typeNeeded = isSlice ? containerType : elementTypeId;
     923             : 
     924             :     /*
     925             :      * container normally has same collation as elements, but there's an
     926             :      * exception: we might be subscripting a domain over a container type. In
     927             :      * that case use collation of the base type.
     928             :      */
     929         654 :     if (containerType == targetTypeId)
     930         566 :         collationNeeded = targetCollation;
     931             :     else
     932          88 :         collationNeeded = get_typcollation(containerType);
     933             : 
     934             :     /* recurse to create appropriate RHS for container assign */
     935         654 :     rhs = transformAssignmentIndirection(pstate,
     936             :                                          NULL,
     937             :                                          targetName,
     938             :                                          true,
     939             :                                          typeNeeded,
     940             :                                          containerTypMod,
     941             :                                          collationNeeded,
     942             :                                          indirection,
     943             :                                          next_indirection,
     944             :                                          rhs,
     945             :                                          location);
     946             : 
     947             :     /* process subscripts */
     948         654 :     result = (Node *) transformContainerSubscripts(pstate,
     949             :                                                    basenode,
     950             :                                                    containerType,
     951             :                                                    elementTypeId,
     952             :                                                    containerTypMod,
     953             :                                                    subscripts,
     954             :                                                    rhs);
     955             : 
     956             :     /* If target was a domain over container, need to coerce up to the domain */
     957         654 :     if (containerType != targetTypeId)
     958             :     {
     959          88 :         Oid         resulttype = exprType(result);
     960             : 
     961          88 :         result = coerce_to_target_type(pstate,
     962             :                                        result, resulttype,
     963             :                                        targetTypeId, targetTypMod,
     964             :                                        COERCION_ASSIGNMENT,
     965             :                                        COERCE_IMPLICIT_CAST,
     966             :                                        -1);
     967             :         /* can fail if we had int2vector/oidvector, but not for true domains */
     968          88 :         if (result == NULL)
     969           0 :             ereport(ERROR,
     970             :                     (errcode(ERRCODE_CANNOT_COERCE),
     971             :                      errmsg("cannot cast type %s to %s",
     972             :                             format_type_be(resulttype),
     973             :                             format_type_be(targetTypeId)),
     974             :                      parser_errposition(pstate, location)));
     975             :     }
     976             : 
     977         654 :     return result;
     978             : }
     979             : 
     980             : 
     981             : /*
     982             :  * checkInsertTargets -
     983             :  *    generate a list of INSERT column targets if not supplied, or
     984             :  *    test supplied column names to make sure they are in target table.
     985             :  *    Also return an integer list of the columns' attribute numbers.
     986             :  */
     987             : List *
     988       57822 : checkInsertTargets(ParseState *pstate, List *cols, List **attrnos)
     989             : {
     990       57822 :     *attrnos = NIL;
     991             : 
     992       57822 :     if (cols == NIL)
     993             :     {
     994             :         /*
     995             :          * Generate default column list for INSERT.
     996             :          */
     997       46758 :         int         numcol = RelationGetNumberOfAttributes(pstate->p_target_relation);
     998             : 
     999             :         int         i;
    1000             : 
    1001      214564 :         for (i = 0; i < numcol; i++)
    1002             :         {
    1003             :             ResTarget  *col;
    1004             :             Form_pg_attribute attr;
    1005             : 
    1006      167806 :             attr = TupleDescAttr(pstate->p_target_relation->rd_att, i);
    1007             : 
    1008      167806 :             if (attr->attisdropped)
    1009         178 :                 continue;
    1010             : 
    1011      167628 :             col = makeNode(ResTarget);
    1012      167628 :             col->name = pstrdup(NameStr(attr->attname));
    1013      167628 :             col->indirection = NIL;
    1014      167628 :             col->val = NULL;
    1015      167628 :             col->location = -1;
    1016      167628 :             cols = lappend(cols, col);
    1017      167628 :             *attrnos = lappend_int(*attrnos, i + 1);
    1018             :         }
    1019             :     }
    1020             :     else
    1021             :     {
    1022             :         /*
    1023             :          * Do initial validation of user-supplied INSERT column list.
    1024             :          */
    1025       11064 :         Bitmapset  *wholecols = NULL;
    1026       11064 :         Bitmapset  *partialcols = NULL;
    1027             :         ListCell   *tl;
    1028             : 
    1029       43622 :         foreach(tl, cols)
    1030             :         {
    1031       32590 :             ResTarget  *col = (ResTarget *) lfirst(tl);
    1032       32590 :             char       *name = col->name;
    1033             :             int         attrno;
    1034             : 
    1035             :             /* Lookup column name, ereport on failure */
    1036       32590 :             attrno = attnameAttNum(pstate->p_target_relation, name, false);
    1037       32590 :             if (attrno == InvalidAttrNumber)
    1038          32 :                 ereport(ERROR,
    1039             :                         (errcode(ERRCODE_UNDEFINED_COLUMN),
    1040             :                          errmsg("column \"%s\" of relation \"%s\" does not exist",
    1041             :                                 name,
    1042             :                                 RelationGetRelationName(pstate->p_target_relation)),
    1043             :                          parser_errposition(pstate, col->location)));
    1044             : 
    1045             :             /*
    1046             :              * Check for duplicates, but only of whole columns --- we allow
    1047             :              * INSERT INTO foo (col.subcol1, col.subcol2)
    1048             :              */
    1049       32558 :             if (col->indirection == NIL)
    1050             :             {
    1051             :                 /* whole column; must not have any other assignment */
    1052       64604 :                 if (bms_is_member(attrno, wholecols) ||
    1053       32302 :                     bms_is_member(attrno, partialcols))
    1054           0 :                     ereport(ERROR,
    1055             :                             (errcode(ERRCODE_DUPLICATE_COLUMN),
    1056             :                              errmsg("column \"%s\" specified more than once",
    1057             :                                     name),
    1058             :                              parser_errposition(pstate, col->location)));
    1059       32302 :                 wholecols = bms_add_member(wholecols, attrno);
    1060             :             }
    1061             :             else
    1062             :             {
    1063             :                 /* partial column; must not have any whole assignment */
    1064         256 :                 if (bms_is_member(attrno, wholecols))
    1065           0 :                     ereport(ERROR,
    1066             :                             (errcode(ERRCODE_DUPLICATE_COLUMN),
    1067             :                              errmsg("column \"%s\" specified more than once",
    1068             :                                     name),
    1069             :                              parser_errposition(pstate, col->location)));
    1070         256 :                 partialcols = bms_add_member(partialcols, attrno);
    1071             :             }
    1072             : 
    1073       32558 :             *attrnos = lappend_int(*attrnos, attrno);
    1074             :         }
    1075             :     }
    1076             : 
    1077       57790 :     return cols;
    1078             : }
    1079             : 
    1080             : /*
    1081             :  * ExpandColumnRefStar()
    1082             :  *      Transforms foo.* into a list of expressions or targetlist entries.
    1083             :  *
    1084             :  * This handles the case where '*' appears as the last or only item in a
    1085             :  * ColumnRef.  The code is shared between the case of foo.* at the top level
    1086             :  * in a SELECT target list (where we want TargetEntry nodes in the result)
    1087             :  * and foo.* in a ROW() or VALUES() construct (where we want just bare
    1088             :  * expressions).
    1089             :  *
    1090             :  * The referenced columns are marked as requiring SELECT access.
    1091             :  */
    1092             : static List *
    1093       30794 : ExpandColumnRefStar(ParseState *pstate, ColumnRef *cref,
    1094             :                     bool make_target_entry)
    1095             : {
    1096       30794 :     List       *fields = cref->fields;
    1097       30794 :     int         numnames = list_length(fields);
    1098             : 
    1099       30794 :     if (numnames == 1)
    1100             :     {
    1101             :         /*
    1102             :          * Target item is a bare '*', expand all tables
    1103             :          *
    1104             :          * (e.g., SELECT * FROM emp, dept)
    1105             :          *
    1106             :          * Since the grammar only accepts bare '*' at top level of SELECT, we
    1107             :          * need not handle the make_target_entry==false case here.
    1108             :          */
    1109             :         Assert(make_target_entry);
    1110       29386 :         return ExpandAllTables(pstate, cref->location);
    1111             :     }
    1112             :     else
    1113             :     {
    1114             :         /*
    1115             :          * Target item is relation.*, expand that table
    1116             :          *
    1117             :          * (e.g., SELECT emp.*, dname FROM emp, dept)
    1118             :          *
    1119             :          * Note: this code is a lot like transformColumnRef; it's tempting to
    1120             :          * call that instead and then replace the resulting whole-row Var with
    1121             :          * a list of Vars.  However, that would leave us with the RTE's
    1122             :          * selectedCols bitmap showing the whole row as needing select
    1123             :          * permission, as well as the individual columns.  That would be
    1124             :          * incorrect (since columns added later shouldn't need select
    1125             :          * permissions).  We could try to remove the whole-row permission bit
    1126             :          * after the fact, but duplicating code is less messy.
    1127             :          */
    1128        1408 :         char       *nspname = NULL;
    1129        1408 :         char       *relname = NULL;
    1130        1408 :         RangeTblEntry *rte = NULL;
    1131             :         int         levels_up;
    1132             :         enum
    1133             :         {
    1134             :             CRSERR_NO_RTE,
    1135             :             CRSERR_WRONG_DB,
    1136             :             CRSERR_TOO_MANY
    1137        1408 :         }           crserr = CRSERR_NO_RTE;
    1138             : 
    1139             :         /*
    1140             :          * Give the PreParseColumnRefHook, if any, first shot.  If it returns
    1141             :          * non-null then we should use that expression.
    1142             :          */
    1143        1408 :         if (pstate->p_pre_columnref_hook != NULL)
    1144             :         {
    1145             :             Node       *node;
    1146             : 
    1147          26 :             node = pstate->p_pre_columnref_hook(pstate, cref);
    1148          26 :             if (node != NULL)
    1149           0 :                 return ExpandRowReference(pstate, node, make_target_entry);
    1150             :         }
    1151             : 
    1152        1408 :         switch (numnames)
    1153             :         {
    1154             :             case 2:
    1155        1408 :                 relname = strVal(linitial(fields));
    1156        1408 :                 rte = refnameRangeTblEntry(pstate, nspname, relname,
    1157             :                                            cref->location,
    1158             :                                            &levels_up);
    1159        1408 :                 break;
    1160             :             case 3:
    1161           0 :                 nspname = strVal(linitial(fields));
    1162           0 :                 relname = strVal(lsecond(fields));
    1163           0 :                 rte = refnameRangeTblEntry(pstate, nspname, relname,
    1164             :                                            cref->location,
    1165             :                                            &levels_up);
    1166           0 :                 break;
    1167             :             case 4:
    1168             :                 {
    1169           0 :                     char       *catname = strVal(linitial(fields));
    1170             : 
    1171             :                     /*
    1172             :                      * We check the catalog name and then ignore it.
    1173             :                      */
    1174           0 :                     if (strcmp(catname, get_database_name(MyDatabaseId)) != 0)
    1175             :                     {
    1176           0 :                         crserr = CRSERR_WRONG_DB;
    1177           0 :                         break;
    1178             :                     }
    1179           0 :                     nspname = strVal(lsecond(fields));
    1180           0 :                     relname = strVal(lthird(fields));
    1181           0 :                     rte = refnameRangeTblEntry(pstate, nspname, relname,
    1182             :                                                cref->location,
    1183             :                                                &levels_up);
    1184           0 :                     break;
    1185             :                 }
    1186             :             default:
    1187           0 :                 crserr = CRSERR_TOO_MANY;
    1188           0 :                 break;
    1189             :         }
    1190             : 
    1191             :         /*
    1192             :          * Now give the PostParseColumnRefHook, if any, a chance. We cheat a
    1193             :          * bit by passing the RangeTblEntry, not a Var, as the planned
    1194             :          * translation.  (A single Var wouldn't be strictly correct anyway.
    1195             :          * This convention allows hooks that really care to know what is
    1196             :          * happening.)
    1197             :          */
    1198        1408 :         if (pstate->p_post_columnref_hook != NULL)
    1199             :         {
    1200             :             Node       *node;
    1201             : 
    1202          54 :             node = pstate->p_post_columnref_hook(pstate, cref,
    1203             :                                                  (Node *) rte);
    1204          54 :             if (node != NULL)
    1205             :             {
    1206          54 :                 if (rte != NULL)
    1207           0 :                     ereport(ERROR,
    1208             :                             (errcode(ERRCODE_AMBIGUOUS_COLUMN),
    1209             :                              errmsg("column reference \"%s\" is ambiguous",
    1210             :                                     NameListToString(cref->fields)),
    1211             :                              parser_errposition(pstate, cref->location)));
    1212          54 :                 return ExpandRowReference(pstate, node, make_target_entry);
    1213             :             }
    1214             :         }
    1215             : 
    1216             :         /*
    1217             :          * Throw error if no translation found.
    1218             :          */
    1219        1354 :         if (rte == NULL)
    1220             :         {
    1221           4 :             switch (crserr)
    1222             :             {
    1223             :                 case CRSERR_NO_RTE:
    1224           4 :                     errorMissingRTE(pstate, makeRangeVar(nspname, relname,
    1225             :                                                          cref->location));
    1226             :                     break;
    1227             :                 case CRSERR_WRONG_DB:
    1228           0 :                     ereport(ERROR,
    1229             :                             (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    1230             :                              errmsg("cross-database references are not implemented: %s",
    1231             :                                     NameListToString(cref->fields)),
    1232             :                              parser_errposition(pstate, cref->location)));
    1233             :                     break;
    1234             :                 case CRSERR_TOO_MANY:
    1235           0 :                     ereport(ERROR,
    1236             :                             (errcode(ERRCODE_SYNTAX_ERROR),
    1237             :                              errmsg("improper qualified name (too many dotted names): %s",
    1238             :                                     NameListToString(cref->fields)),
    1239             :                              parser_errposition(pstate, cref->location)));
    1240             :                     break;
    1241             :             }
    1242             :         }
    1243             : 
    1244             :         /*
    1245             :          * OK, expand the RTE into fields.
    1246             :          */
    1247        1350 :         return ExpandSingleTable(pstate, rte, cref->location, make_target_entry);
    1248             :     }
    1249             : }
    1250             : 
    1251             : /*
    1252             :  * ExpandAllTables()
    1253             :  *      Transforms '*' (in the target list) into a list of targetlist entries.
    1254             :  *
    1255             :  * tlist entries are generated for each relation visible for unqualified
    1256             :  * column name access.  We do not consider qualified-name-only entries because
    1257             :  * that would include input tables of aliasless JOINs, NEW/OLD pseudo-entries,
    1258             :  * etc.
    1259             :  *
    1260             :  * The referenced relations/columns are marked as requiring SELECT access.
    1261             :  */
    1262             : static List *
    1263       29386 : ExpandAllTables(ParseState *pstate, int location)
    1264             : {
    1265       29386 :     List       *target = NIL;
    1266       29386 :     bool        found_table = false;
    1267             :     ListCell   *l;
    1268             : 
    1269       61662 :     foreach(l, pstate->p_namespace)
    1270             :     {
    1271       32276 :         ParseNamespaceItem *nsitem = (ParseNamespaceItem *) lfirst(l);
    1272       32276 :         RangeTblEntry *rte = nsitem->p_rte;
    1273             : 
    1274             :         /* Ignore table-only items */
    1275       32276 :         if (!nsitem->p_cols_visible)
    1276        2228 :             continue;
    1277             :         /* Should not have any lateral-only items when parsing targetlist */
    1278             :         Assert(!nsitem->p_lateral_only);
    1279             :         /* Remember we found a p_cols_visible item */
    1280       30048 :         found_table = true;
    1281             : 
    1282       30048 :         target = list_concat(target,
    1283       30048 :                              expandRelAttrs(pstate,
    1284             :                                             rte,
    1285             :                                             RTERangeTablePosn(pstate, rte,
    1286             :                                                               NULL),
    1287             :                                             0,
    1288             :                                             location));
    1289             :     }
    1290             : 
    1291             :     /*
    1292             :      * Check for "SELECT *;".  We do it this way, rather than checking for
    1293             :      * target == NIL, because we want to allow SELECT * FROM a zero_column
    1294             :      * table.
    1295             :      */
    1296       29386 :     if (!found_table)
    1297           0 :         ereport(ERROR,
    1298             :                 (errcode(ERRCODE_SYNTAX_ERROR),
    1299             :                  errmsg("SELECT * with no tables specified is not valid"),
    1300             :                  parser_errposition(pstate, location)));
    1301             : 
    1302       29386 :     return target;
    1303             : }
    1304             : 
    1305             : /*
    1306             :  * ExpandIndirectionStar()
    1307             :  *      Transforms foo.* into a list of expressions or targetlist entries.
    1308             :  *
    1309             :  * This handles the case where '*' appears as the last item in A_Indirection.
    1310             :  * The code is shared between the case of foo.* at the top level in a SELECT
    1311             :  * target list (where we want TargetEntry nodes in the result) and foo.* in
    1312             :  * a ROW() or VALUES() construct (where we want just bare expressions).
    1313             :  * For robustness, we use a separate "make_target_entry" flag to control
    1314             :  * this rather than relying on exprKind.
    1315             :  */
    1316             : static List *
    1317        2964 : ExpandIndirectionStar(ParseState *pstate, A_Indirection *ind,
    1318             :                       bool make_target_entry, ParseExprKind exprKind)
    1319             : {
    1320             :     Node       *expr;
    1321             : 
    1322             :     /* Strip off the '*' to create a reference to the rowtype object */
    1323        2964 :     ind = copyObject(ind);
    1324        2964 :     ind->indirection = list_truncate(ind->indirection,
    1325        2964 :                                      list_length(ind->indirection) - 1);
    1326             : 
    1327             :     /* And transform that */
    1328        2964 :     expr = transformExpr(pstate, (Node *) ind, exprKind);
    1329             : 
    1330             :     /* Expand the rowtype expression into individual fields */
    1331        2964 :     return ExpandRowReference(pstate, expr, make_target_entry);
    1332             : }
    1333             : 
    1334             : /*
    1335             :  * ExpandSingleTable()
    1336             :  *      Transforms foo.* into a list of expressions or targetlist entries.
    1337             :  *
    1338             :  * This handles the case where foo has been determined to be a simple
    1339             :  * reference to an RTE, so we can just generate Vars for the expressions.
    1340             :  *
    1341             :  * The referenced columns are marked as requiring SELECT access.
    1342             :  */
    1343             : static List *
    1344        1350 : ExpandSingleTable(ParseState *pstate, RangeTblEntry *rte,
    1345             :                   int location, bool make_target_entry)
    1346             : {
    1347             :     int         sublevels_up;
    1348             :     int         rtindex;
    1349             : 
    1350        1350 :     rtindex = RTERangeTablePosn(pstate, rte, &sublevels_up);
    1351             : 
    1352        1350 :     if (make_target_entry)
    1353             :     {
    1354             :         /* expandRelAttrs handles permissions marking */
    1355        1250 :         return expandRelAttrs(pstate, rte, rtindex, sublevels_up,
    1356             :                               location);
    1357             :     }
    1358             :     else
    1359             :     {
    1360             :         List       *vars;
    1361             :         ListCell   *l;
    1362             : 
    1363         100 :         expandRTE(rte, rtindex, sublevels_up, location, false,
    1364             :                   NULL, &vars);
    1365             : 
    1366             :         /*
    1367             :          * Require read access to the table.  This is normally redundant with
    1368             :          * the markVarForSelectPriv calls below, but not if the table has zero
    1369             :          * columns.
    1370             :          */
    1371         100 :         rte->requiredPerms |= ACL_SELECT;
    1372             : 
    1373             :         /* Require read access to each column */
    1374         268 :         foreach(l, vars)
    1375             :         {
    1376         168 :             Var        *var = (Var *) lfirst(l);
    1377             : 
    1378         168 :             markVarForSelectPriv(pstate, var, rte);
    1379             :         }
    1380             : 
    1381         100 :         return vars;
    1382             :     }
    1383             : }
    1384             : 
    1385             : /*
    1386             :  * ExpandRowReference()
    1387             :  *      Transforms foo.* into a list of expressions or targetlist entries.
    1388             :  *
    1389             :  * This handles the case where foo is an arbitrary expression of composite
    1390             :  * type.
    1391             :  */
    1392             : static List *
    1393        3018 : ExpandRowReference(ParseState *pstate, Node *expr,
    1394             :                    bool make_target_entry)
    1395             : {
    1396        3018 :     List       *result = NIL;
    1397             :     TupleDesc   tupleDesc;
    1398             :     int         numAttrs;
    1399             :     int         i;
    1400             : 
    1401             :     /*
    1402             :      * If the rowtype expression is a whole-row Var, we can expand the fields
    1403             :      * as simple Vars.  Note: if the RTE is a relation, this case leaves us
    1404             :      * with the RTE's selectedCols bitmap showing the whole row as needing
    1405             :      * select permission, as well as the individual columns.  However, we can
    1406             :      * only get here for weird notations like (table.*).*, so it's not worth
    1407             :      * trying to clean up --- arguably, the permissions marking is correct
    1408             :      * anyway for such cases.
    1409             :      */
    1410        3052 :     if (IsA(expr, Var) &&
    1411          34 :         ((Var *) expr)->varattno == InvalidAttrNumber)
    1412             :     {
    1413           0 :         Var        *var = (Var *) expr;
    1414             :         RangeTblEntry *rte;
    1415             : 
    1416           0 :         rte = GetRTEByRangeTablePosn(pstate, var->varno, var->varlevelsup);
    1417           0 :         return ExpandSingleTable(pstate, rte, var->location, make_target_entry);
    1418             :     }
    1419             : 
    1420             :     /*
    1421             :      * Otherwise we have to do it the hard way.  Our current implementation is
    1422             :      * to generate multiple copies of the expression and do FieldSelects.
    1423             :      * (This can be pretty inefficient if the expression involves nontrivial
    1424             :      * computation :-(.)
    1425             :      *
    1426             :      * Verify it's a composite type, and get the tupdesc.
    1427             :      * get_expr_result_tupdesc() handles this conveniently.
    1428             :      *
    1429             :      * If it's a Var of type RECORD, we have to work even harder: we have to
    1430             :      * find what the Var refers to, and pass that to get_expr_result_tupdesc.
    1431             :      * That task is handled by expandRecordVariable().
    1432             :      */
    1433        3052 :     if (IsA(expr, Var) &&
    1434          34 :         ((Var *) expr)->vartype == RECORDOID)
    1435           4 :         tupleDesc = expandRecordVariable(pstate, (Var *) expr, 0);
    1436             :     else
    1437        3014 :         tupleDesc = get_expr_result_tupdesc(expr, false);
    1438             :     Assert(tupleDesc);
    1439             : 
    1440             :     /* Generate a list of references to the individual fields */
    1441        3018 :     numAttrs = tupleDesc->natts;
    1442       15022 :     for (i = 0; i < numAttrs; i++)
    1443             :     {
    1444       12004 :         Form_pg_attribute att = TupleDescAttr(tupleDesc, i);
    1445             :         FieldSelect *fselect;
    1446             : 
    1447       12004 :         if (att->attisdropped)
    1448           8 :             continue;
    1449             : 
    1450       11996 :         fselect = makeNode(FieldSelect);
    1451       11996 :         fselect->arg = (Expr *) copyObject(expr);
    1452       11996 :         fselect->fieldnum = i + 1;
    1453       11996 :         fselect->resulttype = att->atttypid;
    1454       11996 :         fselect->resulttypmod = att->atttypmod;
    1455             :         /* save attribute's collation for parse_collate.c */
    1456       11996 :         fselect->resultcollid = att->attcollation;
    1457             : 
    1458       11996 :         if (make_target_entry)
    1459             :         {
    1460             :             /* add TargetEntry decoration */
    1461             :             TargetEntry *te;
    1462             : 
    1463       23760 :             te = makeTargetEntry((Expr *) fselect,
    1464       11880 :                                  (AttrNumber) pstate->p_next_resno++,
    1465       11880 :                                  pstrdup(NameStr(att->attname)),
    1466             :                                  false);
    1467       11880 :             result = lappend(result, te);
    1468             :         }
    1469             :         else
    1470         116 :             result = lappend(result, fselect);
    1471             :     }
    1472             : 
    1473        3018 :     return result;
    1474             : }
    1475             : 
    1476             : /*
    1477             :  * expandRecordVariable
    1478             :  *      Get the tuple descriptor for a Var of type RECORD, if possible.
    1479             :  *
    1480             :  * Since no actual table or view column is allowed to have type RECORD, such
    1481             :  * a Var must refer to a JOIN or FUNCTION RTE or to a subquery output.  We
    1482             :  * drill down to find the ultimate defining expression and attempt to infer
    1483             :  * the tupdesc from it.  We ereport if we can't determine the tupdesc.
    1484             :  *
    1485             :  * levelsup is an extra offset to interpret the Var's varlevelsup correctly.
    1486             :  */
    1487             : TupleDesc
    1488        6130 : expandRecordVariable(ParseState *pstate, Var *var, int levelsup)
    1489             : {
    1490             :     TupleDesc   tupleDesc;
    1491             :     int         netlevelsup;
    1492             :     RangeTblEntry *rte;
    1493             :     AttrNumber  attnum;
    1494             :     Node       *expr;
    1495             : 
    1496             :     /* Check my caller didn't mess up */
    1497             :     Assert(IsA(var, Var));
    1498             :     Assert(var->vartype == RECORDOID);
    1499             : 
    1500        6130 :     netlevelsup = var->varlevelsup + levelsup;
    1501        6130 :     rte = GetRTEByRangeTablePosn(pstate, var->varno, netlevelsup);
    1502        6130 :     attnum = var->varattno;
    1503             : 
    1504        6130 :     if (attnum == InvalidAttrNumber)
    1505             :     {
    1506             :         /* Whole-row reference to an RTE, so expand the known fields */
    1507             :         List       *names,
    1508             :                    *vars;
    1509             :         ListCell   *lname,
    1510             :                    *lvar;
    1511             :         int         i;
    1512             : 
    1513           0 :         expandRTE(rte, var->varno, 0, var->location, false,
    1514             :                   &names, &vars);
    1515             : 
    1516           0 :         tupleDesc = CreateTemplateTupleDesc(list_length(vars));
    1517           0 :         i = 1;
    1518           0 :         forboth(lname, names, lvar, vars)
    1519             :         {
    1520           0 :             char       *label = strVal(lfirst(lname));
    1521           0 :             Node       *varnode = (Node *) lfirst(lvar);
    1522             : 
    1523           0 :             TupleDescInitEntry(tupleDesc, i,
    1524             :                                label,
    1525             :                                exprType(varnode),
    1526             :                                exprTypmod(varnode),
    1527             :                                0);
    1528           0 :             TupleDescInitEntryCollation(tupleDesc, i,
    1529             :                                         exprCollation(varnode));
    1530           0 :             i++;
    1531             :         }
    1532             :         Assert(lname == NULL && lvar == NULL);  /* lists same length? */
    1533             : 
    1534           0 :         return tupleDesc;
    1535             :     }
    1536             : 
    1537        6130 :     expr = (Node *) var;        /* default if we can't drill down */
    1538             : 
    1539        6130 :     switch (rte->rtekind)
    1540             :     {
    1541             :         case RTE_RELATION:
    1542             :         case RTE_VALUES:
    1543             :         case RTE_NAMEDTUPLESTORE:
    1544             :         case RTE_RESULT:
    1545             : 
    1546             :             /*
    1547             :              * This case should not occur: a column of a table, values list,
    1548             :              * or ENR shouldn't have type RECORD.  Fall through and fail (most
    1549             :              * likely) at the bottom.
    1550             :              */
    1551           0 :             break;
    1552             :         case RTE_SUBQUERY:
    1553             :             {
    1554             :                 /* Subselect-in-FROM: examine sub-select's output expr */
    1555        6130 :                 TargetEntry *ste = get_tle_by_resno(rte->subquery->targetList,
    1556             :                                                     attnum);
    1557             : 
    1558        6130 :                 if (ste == NULL || ste->resjunk)
    1559           0 :                     elog(ERROR, "subquery %s does not have attribute %d",
    1560             :                          rte->eref->aliasname, attnum);
    1561        6130 :                 expr = (Node *) ste->expr;
    1562        6130 :                 if (IsA(expr, Var))
    1563             :                 {
    1564             :                     /*
    1565             :                      * Recurse into the sub-select to see what its Var refers
    1566             :                      * to.  We have to build an additional level of ParseState
    1567             :                      * to keep in step with varlevelsup in the subselect.
    1568             :                      */
    1569             :                     ParseState  mypstate;
    1570             : 
    1571           0 :                     MemSet(&mypstate, 0, sizeof(mypstate));
    1572           0 :                     mypstate.parentParseState = pstate;
    1573           0 :                     mypstate.p_rtable = rte->subquery->rtable;
    1574             :                     /* don't bother filling the rest of the fake pstate */
    1575             : 
    1576           0 :                     return expandRecordVariable(&mypstate, (Var *) expr, 0);
    1577             :                 }
    1578             :                 /* else fall through to inspect the expression */
    1579             :             }
    1580        6130 :             break;
    1581             :         case RTE_JOIN:
    1582             :             /* Join RTE --- recursively inspect the alias variable */
    1583             :             Assert(attnum > 0 && attnum <= list_length(rte->joinaliasvars));
    1584           0 :             expr = (Node *) list_nth(rte->joinaliasvars, attnum - 1);
    1585             :             Assert(expr != NULL);
    1586             :             /* We intentionally don't strip implicit coercions here */
    1587           0 :             if (IsA(expr, Var))
    1588           0 :                 return expandRecordVariable(pstate, (Var *) expr, netlevelsup);
    1589             :             /* else fall through to inspect the expression */
    1590           0 :             break;
    1591             :         case RTE_FUNCTION:
    1592             : 
    1593             :             /*
    1594             :              * We couldn't get here unless a function is declared with one of
    1595             :              * its result columns as RECORD, which is not allowed.
    1596             :              */
    1597           0 :             break;
    1598             :         case RTE_TABLEFUNC:
    1599             : 
    1600             :             /*
    1601             :              * Table function cannot have columns with RECORD type.
    1602             :              */
    1603           0 :             break;
    1604             :         case RTE_CTE:
    1605             :             /* CTE reference: examine subquery's output expr */
    1606           0 :             if (!rte->self_reference)
    1607             :             {
    1608           0 :                 CommonTableExpr *cte = GetCTEForRTE(pstate, rte, netlevelsup);
    1609             :                 TargetEntry *ste;
    1610             : 
    1611           0 :                 ste = get_tle_by_resno(GetCTETargetList(cte), attnum);
    1612           0 :                 if (ste == NULL || ste->resjunk)
    1613           0 :                     elog(ERROR, "subquery %s does not have attribute %d",
    1614             :                          rte->eref->aliasname, attnum);
    1615           0 :                 expr = (Node *) ste->expr;
    1616           0 :                 if (IsA(expr, Var))
    1617             :                 {
    1618             :                     /*
    1619             :                      * Recurse into the CTE to see what its Var refers to. We
    1620             :                      * have to build an additional level of ParseState to keep
    1621             :                      * in step with varlevelsup in the CTE; furthermore it
    1622             :                      * could be an outer CTE.
    1623             :                      */
    1624             :                     ParseState  mypstate;
    1625             :                     Index       levelsup;
    1626             : 
    1627           0 :                     MemSet(&mypstate, 0, sizeof(mypstate));
    1628             :                     /* this loop must work, since GetCTEForRTE did */
    1629           0 :                     for (levelsup = 0;
    1630           0 :                          levelsup < rte->ctelevelsup + netlevelsup;
    1631           0 :                          levelsup++)
    1632           0 :                         pstate = pstate->parentParseState;
    1633           0 :                     mypstate.parentParseState = pstate;
    1634           0 :                     mypstate.p_rtable = ((Query *) cte->ctequery)->rtable;
    1635             :                     /* don't bother filling the rest of the fake pstate */
    1636             : 
    1637           0 :                     return expandRecordVariable(&mypstate, (Var *) expr, 0);
    1638             :                 }
    1639             :                 /* else fall through to inspect the expression */
    1640             :             }
    1641           0 :             break;
    1642             :     }
    1643             : 
    1644             :     /*
    1645             :      * We now have an expression we can't expand any more, so see if
    1646             :      * get_expr_result_tupdesc() can do anything with it.
    1647             :      */
    1648        6130 :     return get_expr_result_tupdesc(expr, false);
    1649             : }
    1650             : 
    1651             : 
    1652             : /*
    1653             :  * FigureColname -
    1654             :  *    if the name of the resulting column is not specified in the target
    1655             :  *    list, we have to guess a suitable name.  The SQL spec provides some
    1656             :  *    guidance, but not much...
    1657             :  *
    1658             :  * Note that the argument is the *untransformed* parse tree for the target
    1659             :  * item.  This is a shade easier to work with than the transformed tree.
    1660             :  */
    1661             : char *
    1662      742044 : FigureColname(Node *node)
    1663             : {
    1664      742044 :     char       *name = NULL;
    1665             : 
    1666      742044 :     (void) FigureColnameInternal(node, &name);
    1667      742044 :     if (name != NULL)
    1668      654868 :         return name;
    1669             :     /* default result if we can't guess anything */
    1670       87176 :     return "?column?";
    1671             : }
    1672             : 
    1673             : /*
    1674             :  * FigureIndexColname -
    1675             :  *    choose the name for an expression column in an index
    1676             :  *
    1677             :  * This is actually just like FigureColname, except we return NULL if
    1678             :  * we can't pick a good name.
    1679             :  */
    1680             : char *
    1681         306 : FigureIndexColname(Node *node)
    1682             : {
    1683         306 :     char       *name = NULL;
    1684             : 
    1685         306 :     (void) FigureColnameInternal(node, &name);
    1686         306 :     return name;
    1687             : }
    1688             : 
    1689             : /*
    1690             :  * FigureColnameInternal -
    1691             :  *    internal workhorse for FigureColname
    1692             :  *
    1693             :  * Return value indicates strength of confidence in result:
    1694             :  *      0 - no information
    1695             :  *      1 - second-best name choice
    1696             :  *      2 - good name choice
    1697             :  * The return value is actually only used internally.
    1698             :  * If the result isn't zero, *name is set to the chosen name.
    1699             :  */
    1700             : static int
    1701      778758 : FigureColnameInternal(Node *node, char **name)
    1702             : {
    1703      778758 :     int         strength = 0;
    1704             : 
    1705      778758 :     if (node == NULL)
    1706         324 :         return strength;
    1707             : 
    1708      778434 :     switch (nodeTag(node))
    1709             :     {
    1710             :         case T_ColumnRef:
    1711             :             {
    1712      498958 :                 char       *fname = NULL;
    1713             :                 ListCell   *l;
    1714             : 
    1715             :                 /* find last field name, if any, ignoring "*" */
    1716     1258260 :                 foreach(l, ((ColumnRef *) node)->fields)
    1717             :                 {
    1718      759302 :                     Node       *i = lfirst(l);
    1719             : 
    1720      759302 :                     if (IsA(i, String))
    1721      759270 :                         fname = strVal(i);
    1722             :                 }
    1723      498958 :                 if (fname)
    1724             :                 {
    1725      498958 :                     *name = fname;
    1726      498958 :                     return 2;
    1727             :                 }
    1728             :             }
    1729           0 :             break;
    1730             :         case T_A_Indirection:
    1731             :             {
    1732        2608 :                 A_Indirection *ind = (A_Indirection *) node;
    1733        2608 :                 char       *fname = NULL;
    1734             :                 ListCell   *l;
    1735             : 
    1736             :                 /* find last field name, if any, ignoring "*" and subscripts */
    1737        5368 :                 foreach(l, ind->indirection)
    1738             :                 {
    1739        2760 :                     Node       *i = lfirst(l);
    1740             : 
    1741        2760 :                     if (IsA(i, String))
    1742        1746 :                         fname = strVal(i);
    1743             :                 }
    1744        2608 :                 if (fname)
    1745             :                 {
    1746        1734 :                     *name = fname;
    1747        1734 :                     return 2;
    1748             :                 }
    1749         874 :                 return FigureColnameInternal(ind->arg, name);
    1750             :             }
    1751             :             break;
    1752             :         case T_FuncCall:
    1753      132396 :             *name = strVal(llast(((FuncCall *) node)->funcname));
    1754      132396 :             return 2;
    1755             :         case T_A_Expr:
    1756       19994 :             if (((A_Expr *) node)->kind == AEXPR_NULLIF)
    1757             :             {
    1758             :                 /* make nullif() act like a regular function */
    1759          16 :                 *name = "nullif";
    1760          16 :                 return 2;
    1761             :             }
    1762       19978 :             if (((A_Expr *) node)->kind == AEXPR_PAREN)
    1763             :             {
    1764             :                 /* look through dummy parenthesis node */
    1765           0 :                 return FigureColnameInternal(((A_Expr *) node)->lexpr, name);
    1766             :             }
    1767       19978 :             break;
    1768             :         case T_TypeCast:
    1769       28550 :             strength = FigureColnameInternal(((TypeCast *) node)->arg,
    1770             :                                              name);
    1771       28550 :             if (strength <= 1)
    1772             :             {
    1773       13062 :                 if (((TypeCast *) node)->typeName != NULL)
    1774             :                 {
    1775       13062 :                     *name = strVal(llast(((TypeCast *) node)->typeName->names));
    1776       13062 :                     return 1;
    1777             :                 }
    1778             :             }
    1779       15488 :             break;
    1780             :         case T_CollateClause:
    1781          42 :             return FigureColnameInternal(((CollateClause *) node)->arg, name);
    1782             :         case T_GroupingFunc:
    1783             :             /* make GROUPING() act like a regular function */
    1784         148 :             *name = "grouping";
    1785         148 :             return 2;
    1786             :         case T_SubLink:
    1787        4724 :             switch (((SubLink *) node)->subLinkType)
    1788             :             {
    1789             :                 case EXISTS_SUBLINK:
    1790          30 :                     *name = "exists";
    1791          30 :                     return 2;
    1792             :                 case ARRAY_SUBLINK:
    1793          40 :                     *name = "array";
    1794          40 :                     return 2;
    1795             :                 case EXPR_SUBLINK:
    1796             :                     {
    1797             :                         /* Get column name of the subquery's single target */
    1798        4634 :                         SubLink    *sublink = (SubLink *) node;
    1799        4634 :                         Query      *query = (Query *) sublink->subselect;
    1800             : 
    1801             :                         /*
    1802             :                          * The subquery has probably already been transformed,
    1803             :                          * but let's be careful and check that.  (The reason
    1804             :                          * we can see a transformed subquery here is that
    1805             :                          * transformSubLink is lazy and modifies the SubLink
    1806             :                          * node in-place.)
    1807             :                          */
    1808        4634 :                         if (IsA(query, Query))
    1809             :                         {
    1810        4634 :                             TargetEntry *te = (TargetEntry *) linitial(query->targetList);
    1811             : 
    1812        4634 :                             if (te->resname)
    1813             :                             {
    1814        4634 :                                 *name = te->resname;
    1815        4634 :                                 return 2;
    1816             :                             }
    1817             :                         }
    1818             :                     }
    1819           0 :                     break;
    1820             :                     /* As with other operator-like nodes, these have no names */
    1821             :                 case MULTIEXPR_SUBLINK:
    1822             :                 case ALL_SUBLINK:
    1823             :                 case ANY_SUBLINK:
    1824             :                 case ROWCOMPARE_SUBLINK:
    1825             :                 case CTE_SUBLINK:
    1826          20 :                     break;
    1827             :             }
    1828          20 :             break;
    1829             :         case T_CaseExpr:
    1830        6942 :             strength = FigureColnameInternal((Node *) ((CaseExpr *) node)->defresult,
    1831             :                                              name);
    1832        6942 :             if (strength <= 1)
    1833             :             {
    1834        3480 :                 *name = "case";
    1835        3480 :                 return 1;
    1836             :             }
    1837        3462 :             break;
    1838             :         case T_A_ArrayExpr:
    1839             :             /* make ARRAY[] act like a function */
    1840         336 :             *name = "array";
    1841         336 :             return 2;
    1842             :         case T_RowExpr:
    1843             :             /* make ROW() act like a function */
    1844         292 :             *name = "row";
    1845         292 :             return 2;
    1846             :         case T_CoalesceExpr:
    1847             :             /* make coalesce() act like a regular function */
    1848         148 :             *name = "coalesce";
    1849         148 :             return 2;
    1850             :         case T_MinMaxExpr:
    1851             :             /* make greatest/least act like a regular function */
    1852          66 :             switch (((MinMaxExpr *) node)->op)
    1853             :             {
    1854             :                 case IS_GREATEST:
    1855          16 :                     *name = "greatest";
    1856          16 :                     return 2;
    1857             :                 case IS_LEAST:
    1858          50 :                     *name = "least";
    1859          50 :                     return 2;
    1860             :             }
    1861           0 :             break;
    1862             :         case T_SQLValueFunction:
    1863             :             /* make these act like a function or variable */
    1864          48 :             switch (((SQLValueFunction *) node)->op)
    1865             :             {
    1866             :                 case SVFOP_CURRENT_DATE:
    1867           8 :                     *name = "current_date";
    1868           8 :                     return 2;
    1869             :                 case SVFOP_CURRENT_TIME:
    1870             :                 case SVFOP_CURRENT_TIME_N:
    1871           0 :                     *name = "current_time";
    1872           0 :                     return 2;
    1873             :                 case SVFOP_CURRENT_TIMESTAMP:
    1874             :                 case SVFOP_CURRENT_TIMESTAMP_N:
    1875           0 :                     *name = "current_timestamp";
    1876           0 :                     return 2;
    1877             :                 case SVFOP_LOCALTIME:
    1878             :                 case SVFOP_LOCALTIME_N:
    1879           0 :                     *name = "localtime";
    1880           0 :                     return 2;
    1881             :                 case SVFOP_LOCALTIMESTAMP:
    1882             :                 case SVFOP_LOCALTIMESTAMP_N:
    1883           4 :                     *name = "localtimestamp";
    1884           4 :                     return 2;
    1885             :                 case SVFOP_CURRENT_ROLE:
    1886           0 :                     *name = "current_role";
    1887           0 :                     return 2;
    1888             :                 case SVFOP_CURRENT_USER:
    1889          12 :                     *name = "current_user";
    1890          12 :                     return 2;
    1891             :                 case SVFOP_USER:
    1892           0 :                     *name = "user";
    1893           0 :                     return 2;
    1894             :                 case SVFOP_SESSION_USER:
    1895          12 :                     *name = "session_user";
    1896          12 :                     return 2;
    1897             :                 case SVFOP_CURRENT_CATALOG:
    1898           0 :                     *name = "current_catalog";
    1899           0 :                     return 2;
    1900             :                 case SVFOP_CURRENT_SCHEMA:
    1901          12 :                     *name = "current_schema";
    1902          12 :                     return 2;
    1903             :             }
    1904           0 :             break;
    1905             :         case T_XmlExpr:
    1906             :             /* make SQL/XML functions act like a regular function */
    1907         300 :             switch (((XmlExpr *) node)->op)
    1908             :             {
    1909             :                 case IS_XMLCONCAT:
    1910          32 :                     *name = "xmlconcat";
    1911          32 :                     return 2;
    1912             :                 case IS_XMLELEMENT:
    1913          72 :                     *name = "xmlelement";
    1914          72 :                     return 2;
    1915             :                 case IS_XMLFOREST:
    1916           4 :                     *name = "xmlforest";
    1917           4 :                     return 2;
    1918             :                 case IS_XMLPARSE:
    1919          92 :                     *name = "xmlparse";
    1920          92 :                     return 2;
    1921             :                 case IS_XMLPI:
    1922          52 :                     *name = "xmlpi";
    1923          52 :                     return 2;
    1924             :                 case IS_XMLROOT:
    1925          40 :                     *name = "xmlroot";
    1926          40 :                     return 2;
    1927             :                 case IS_XMLSERIALIZE:
    1928           0 :                     *name = "xmlserialize";
    1929           0 :                     return 2;
    1930             :                 case IS_DOCUMENT:
    1931             :                     /* nothing */
    1932           8 :                     break;
    1933             :             }
    1934           8 :             break;
    1935             :         case T_XmlSerialize:
    1936          20 :             *name = "xmlserialize";
    1937          20 :             return 2;
    1938             :         default:
    1939       82862 :             break;
    1940             :     }
    1941             : 
    1942      121818 :     return strength;
    1943             : }

Generated by: LCOV version 1.13