PostgreSQL Source Code  git master
parse_target.c File Reference
#include "postgres.h"
#include "catalog/pg_type.h"
#include "commands/dbcommands.h"
#include "funcapi.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "parser/parse_coerce.h"
#include "parser/parse_expr.h"
#include "parser/parse_func.h"
#include "parser/parse_relation.h"
#include "parser/parse_target.h"
#include "parser/parse_type.h"
#include "parser/parsetree.h"
#include "utils/builtins.h"
#include "utils/lsyscache.h"
#include "utils/rel.h"
#include "utils/typcache.h"
Include dependency graph for parse_target.c:

Go to the source code of this file.

Functions

static void markTargetListOrigin (ParseState *pstate, TargetEntry *tle, Var *var, int levelsup)
 
static NodetransformAssignmentIndirection (ParseState *pstate, Node *basenode, const char *targetName, bool targetIsSubscripting, Oid targetTypeId, int32 targetTypMod, Oid targetCollation, List *indirection, ListCell *indirection_cell, Node *rhs, int location)
 
static NodetransformAssignmentSubscripts (ParseState *pstate, Node *basenode, const char *targetName, Oid targetTypeId, int32 targetTypMod, Oid targetCollation, List *subscripts, bool isSlice, List *indirection, ListCell *next_indirection, Node *rhs, int location)
 
static ListExpandColumnRefStar (ParseState *pstate, ColumnRef *cref, bool make_target_entry)
 
static ListExpandAllTables (ParseState *pstate, int location)
 
static ListExpandIndirectionStar (ParseState *pstate, A_Indirection *ind, bool make_target_entry, ParseExprKind exprKind)
 
static ListExpandSingleTable (ParseState *pstate, ParseNamespaceItem *nsitem, int sublevels_up, int location, bool make_target_entry)
 
static ListExpandRowReference (ParseState *pstate, Node *expr, bool make_target_entry)
 
static int FigureColnameInternal (Node *node, char **name)
 
TargetEntrytransformTargetEntry (ParseState *pstate, Node *node, Node *expr, ParseExprKind exprKind, char *colname, bool resjunk)
 
ListtransformTargetList (ParseState *pstate, List *targetlist, ParseExprKind exprKind)
 
ListtransformExpressionList (ParseState *pstate, List *exprlist, ParseExprKind exprKind, bool allowDefault)
 
void resolveTargetListUnknowns (ParseState *pstate, List *targetlist)
 
void markTargetListOrigins (ParseState *pstate, List *targetlist)
 
ExprtransformAssignedExpr (ParseState *pstate, Expr *expr, ParseExprKind exprKind, const char *colname, int attrno, List *indirection, int location)
 
void updateTargetListEntry (ParseState *pstate, TargetEntry *tle, char *colname, int attrno, List *indirection, int location)
 
ListcheckInsertTargets (ParseState *pstate, List *cols, List **attrnos)
 
TupleDesc expandRecordVariable (ParseState *pstate, Var *var, int levelsup)
 
char * FigureColname (Node *node)
 
char * FigureIndexColname (Node *node)
 

Function Documentation

◆ checkInsertTargets()

List* checkInsertTargets ( ParseState pstate,
List cols,
List **  attrnos 
)

Definition at line 984 of file parse_target.c.

References attnameAttNum(), bms_add_member(), bms_is_member(), ereport, errcode(), errmsg(), ERROR, i, ResTarget::indirection, InvalidAttrNumber, lappend(), lappend_int(), lfirst, ResTarget::location, makeNode, ResTarget::name, name, NameStr, NIL, ParseState::p_target_relation, parser_errposition(), pstrdup(), RelationData::rd_att, RelationGetNumberOfAttributes, RelationGetRelationName, TupleDescAttr, and ResTarget::val.

Referenced by transformInsertStmt().

985 {
986  *attrnos = NIL;
987 
988  if (cols == NIL)
989  {
990  /*
991  * Generate default column list for INSERT.
992  */
993  int numcol = RelationGetNumberOfAttributes(pstate->p_target_relation);
994 
995  int i;
996 
997  for (i = 0; i < numcol; i++)
998  {
999  ResTarget *col;
1000  Form_pg_attribute attr;
1001 
1002  attr = TupleDescAttr(pstate->p_target_relation->rd_att, i);
1003 
1004  if (attr->attisdropped)
1005  continue;
1006 
1007  col = makeNode(ResTarget);
1008  col->name = pstrdup(NameStr(attr->attname));
1009  col->indirection = NIL;
1010  col->val = NULL;
1011  col->location = -1;
1012  cols = lappend(cols, col);
1013  *attrnos = lappend_int(*attrnos, i + 1);
1014  }
1015  }
1016  else
1017  {
1018  /*
1019  * Do initial validation of user-supplied INSERT column list.
1020  */
1021  Bitmapset *wholecols = NULL;
1022  Bitmapset *partialcols = NULL;
1023  ListCell *tl;
1024 
1025  foreach(tl, cols)
1026  {
1027  ResTarget *col = (ResTarget *) lfirst(tl);
1028  char *name = col->name;
1029  int attrno;
1030 
1031  /* Lookup column name, ereport on failure */
1032  attrno = attnameAttNum(pstate->p_target_relation, name, false);
1033  if (attrno == InvalidAttrNumber)
1034  ereport(ERROR,
1035  (errcode(ERRCODE_UNDEFINED_COLUMN),
1036  errmsg("column \"%s\" of relation \"%s\" does not exist",
1037  name,
1039  parser_errposition(pstate, col->location)));
1040 
1041  /*
1042  * Check for duplicates, but only of whole columns --- we allow
1043  * INSERT INTO foo (col.subcol1, col.subcol2)
1044  */
1045  if (col->indirection == NIL)
1046  {
1047  /* whole column; must not have any other assignment */
1048  if (bms_is_member(attrno, wholecols) ||
1049  bms_is_member(attrno, partialcols))
1050  ereport(ERROR,
1051  (errcode(ERRCODE_DUPLICATE_COLUMN),
1052  errmsg("column \"%s\" specified more than once",
1053  name),
1054  parser_errposition(pstate, col->location)));
1055  wholecols = bms_add_member(wholecols, attrno);
1056  }
1057  else
1058  {
1059  /* partial column; must not have any whole assignment */
1060  if (bms_is_member(attrno, wholecols))
1061  ereport(ERROR,
1062  (errcode(ERRCODE_DUPLICATE_COLUMN),
1063  errmsg("column \"%s\" specified more than once",
1064  name),
1065  parser_errposition(pstate, col->location)));
1066  partialcols = bms_add_member(partialcols, attrno);
1067  }
1068 
1069  *attrnos = lappend_int(*attrnos, attrno);
1070  }
1071  }
1072 
1073  return cols;
1074 }
List * indirection
Definition: parsenodes.h:443
#define NIL
Definition: pg_list.h:65
Node * val
Definition: parsenodes.h:444
char * name
Definition: parsenodes.h:442
#define RelationGetNumberOfAttributes(relation)
Definition: rel.h:462
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
char * pstrdup(const char *in)
Definition: mcxt.c:1187
int errcode(int sqlerrcode)
Definition: elog.c:610
int location
Definition: parsenodes.h:445
#define ERROR
Definition: elog.h:43
#define RelationGetRelationName(relation)
Definition: rel.h:490
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:193
List * lappend_int(List *list, int datum)
Definition: list.c:339
List * lappend(List *list, void *datum)
Definition: list.c:321
TupleDesc rd_att
Definition: rel.h:110
#define ereport(elevel,...)
Definition: elog.h:144
#define makeNode(_type_)
Definition: nodes.h:576
int attnameAttNum(Relation rd, const char *attname, bool sysColOK)
#define lfirst(lc)
Definition: pg_list.h:169
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:736
const char * name
Definition: encode.c:561
#define InvalidAttrNumber
Definition: attnum.h:23
int errmsg(const char *fmt,...)
Definition: elog.c:821
Relation p_target_relation
Definition: parse_node.h:190
int i
#define NameStr(name)
Definition: c.h:623
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:427

◆ ExpandAllTables()

static List * ExpandAllTables ( ParseState pstate,
int  location 
)
static

Definition at line 1262 of file parse_target.c.

References Assert, ereport, errcode(), errmsg(), ERROR, expandNSItemAttrs(), lfirst, list_concat(), NIL, ParseNamespaceItem::p_cols_visible, ParseNamespaceItem::p_lateral_only, ParseState::p_namespace, and parser_errposition().

Referenced by ExpandColumnRefStar().

1263 {
1264  List *target = NIL;
1265  bool found_table = false;
1266  ListCell *l;
1267 
1268  foreach(l, pstate->p_namespace)
1269  {
1270  ParseNamespaceItem *nsitem = (ParseNamespaceItem *) lfirst(l);
1271 
1272  /* Ignore table-only items */
1273  if (!nsitem->p_cols_visible)
1274  continue;
1275  /* Should not have any lateral-only items when parsing targetlist */
1276  Assert(!nsitem->p_lateral_only);
1277  /* Remember we found a p_cols_visible item */
1278  found_table = true;
1279 
1280  target = list_concat(target,
1281  expandNSItemAttrs(pstate,
1282  nsitem,
1283  0,
1284  location));
1285  }
1286 
1287  /*
1288  * Check for "SELECT *;". We do it this way, rather than checking for
1289  * target == NIL, because we want to allow SELECT * FROM a zero_column
1290  * table.
1291  */
1292  if (!found_table)
1293  ereport(ERROR,
1294  (errcode(ERRCODE_SYNTAX_ERROR),
1295  errmsg("SELECT * with no tables specified is not valid"),
1296  parser_errposition(pstate, location)));
1297 
1298  return target;
1299 }
#define NIL
Definition: pg_list.h:65
List * list_concat(List *list1, const List *list2)
Definition: list.c:515
int errcode(int sqlerrcode)
Definition: elog.c:610
#define ERROR
Definition: elog.h:43
List * p_namespace
Definition: parse_node.h:184
#define ereport(elevel,...)
Definition: elog.h:144
#define Assert(condition)
Definition: c.h:746
#define lfirst(lc)
Definition: pg_list.h:169
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110
int errmsg(const char *fmt,...)
Definition: elog.c:821
List * expandNSItemAttrs(ParseState *pstate, ParseNamespaceItem *nsitem, int sublevels_up, int location)
Definition: pg_list.h:50

◆ ExpandColumnRefStar()

static List * ExpandColumnRefStar ( ParseState pstate,
ColumnRef cref,
bool  make_target_entry 
)
static

Definition at line 1089 of file parse_target.c.

References Assert, ereport, errcode(), errmsg(), ERROR, errorMissingRTE(), ExpandAllTables(), ExpandRowReference(), ExpandSingleTable(), ColumnRef::fields, get_database_name(), linitial, list_length(), ColumnRef::location, lsecond, lthird, makeRangeVar(), MyDatabaseId, NameListToString(), ParseState::p_post_columnref_hook, ParseState::p_pre_columnref_hook, ParseNamespaceItem::p_rte, parser_errposition(), refnameNamespaceItem(), relname, and strVal.

Referenced by transformExpressionList(), and transformTargetList().

1091 {
1092  List *fields = cref->fields;
1093  int numnames = list_length(fields);
1094 
1095  if (numnames == 1)
1096  {
1097  /*
1098  * Target item is a bare '*', expand all tables
1099  *
1100  * (e.g., SELECT * FROM emp, dept)
1101  *
1102  * Since the grammar only accepts bare '*' at top level of SELECT, we
1103  * need not handle the make_target_entry==false case here.
1104  */
1105  Assert(make_target_entry);
1106  return ExpandAllTables(pstate, cref->location);
1107  }
1108  else
1109  {
1110  /*
1111  * Target item is relation.*, expand that table
1112  *
1113  * (e.g., SELECT emp.*, dname FROM emp, dept)
1114  *
1115  * Note: this code is a lot like transformColumnRef; it's tempting to
1116  * call that instead and then replace the resulting whole-row Var with
1117  * a list of Vars. However, that would leave us with the RTE's
1118  * selectedCols bitmap showing the whole row as needing select
1119  * permission, as well as the individual columns. That would be
1120  * incorrect (since columns added later shouldn't need select
1121  * permissions). We could try to remove the whole-row permission bit
1122  * after the fact, but duplicating code is less messy.
1123  */
1124  char *nspname = NULL;
1125  char *relname = NULL;
1126  ParseNamespaceItem *nsitem = NULL;
1127  int levels_up;
1128  enum
1129  {
1130  CRSERR_NO_RTE,
1131  CRSERR_WRONG_DB,
1132  CRSERR_TOO_MANY
1133  } crserr = CRSERR_NO_RTE;
1134 
1135  /*
1136  * Give the PreParseColumnRefHook, if any, first shot. If it returns
1137  * non-null then we should use that expression.
1138  */
1139  if (pstate->p_pre_columnref_hook != NULL)
1140  {
1141  Node *node;
1142 
1143  node = pstate->p_pre_columnref_hook(pstate, cref);
1144  if (node != NULL)
1145  return ExpandRowReference(pstate, node, make_target_entry);
1146  }
1147 
1148  switch (numnames)
1149  {
1150  case 2:
1151  relname = strVal(linitial(fields));
1152  nsitem = refnameNamespaceItem(pstate, nspname, relname,
1153  cref->location,
1154  &levels_up);
1155  break;
1156  case 3:
1157  nspname = strVal(linitial(fields));
1158  relname = strVal(lsecond(fields));
1159  nsitem = refnameNamespaceItem(pstate, nspname, relname,
1160  cref->location,
1161  &levels_up);
1162  break;
1163  case 4:
1164  {
1165  char *catname = strVal(linitial(fields));
1166 
1167  /*
1168  * We check the catalog name and then ignore it.
1169  */
1170  if (strcmp(catname, get_database_name(MyDatabaseId)) != 0)
1171  {
1172  crserr = CRSERR_WRONG_DB;
1173  break;
1174  }
1175  nspname = strVal(lsecond(fields));
1176  relname = strVal(lthird(fields));
1177  nsitem = refnameNamespaceItem(pstate, nspname, relname,
1178  cref->location,
1179  &levels_up);
1180  break;
1181  }
1182  default:
1183  crserr = CRSERR_TOO_MANY;
1184  break;
1185  }
1186 
1187  /*
1188  * Now give the PostParseColumnRefHook, if any, a chance. We cheat a
1189  * bit by passing the RangeTblEntry, not a Var, as the planned
1190  * translation. (A single Var wouldn't be strictly correct anyway.
1191  * This convention allows hooks that really care to know what is
1192  * happening. It might be better to pass the nsitem, but we'd have to
1193  * promote that struct to a full-fledged Node type so that callees
1194  * could identify its type.)
1195  */
1196  if (pstate->p_post_columnref_hook != NULL)
1197  {
1198  Node *node;
1199 
1200  node = pstate->p_post_columnref_hook(pstate, cref,
1201  (Node *) (nsitem ? nsitem->p_rte : NULL));
1202  if (node != NULL)
1203  {
1204  if (nsitem != NULL)
1205  ereport(ERROR,
1206  (errcode(ERRCODE_AMBIGUOUS_COLUMN),
1207  errmsg("column reference \"%s\" is ambiguous",
1208  NameListToString(cref->fields)),
1209  parser_errposition(pstate, cref->location)));
1210  return ExpandRowReference(pstate, node, make_target_entry);
1211  }
1212  }
1213 
1214  /*
1215  * Throw error if no translation found.
1216  */
1217  if (nsitem == NULL)
1218  {
1219  switch (crserr)
1220  {
1221  case CRSERR_NO_RTE:
1222  errorMissingRTE(pstate, makeRangeVar(nspname, relname,
1223  cref->location));
1224  break;
1225  case CRSERR_WRONG_DB:
1226  ereport(ERROR,
1227  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1228  errmsg("cross-database references are not implemented: %s",
1229  NameListToString(cref->fields)),
1230  parser_errposition(pstate, cref->location)));
1231  break;
1232  case CRSERR_TOO_MANY:
1233  ereport(ERROR,
1234  (errcode(ERRCODE_SYNTAX_ERROR),
1235  errmsg("improper qualified name (too many dotted names): %s",
1236  NameListToString(cref->fields)),
1237  parser_errposition(pstate, cref->location)));
1238  break;
1239  }
1240  }
1241 
1242  /*
1243  * OK, expand the nsitem into fields.
1244  */
1245  return ExpandSingleTable(pstate, nsitem, levels_up, cref->location,
1246  make_target_entry);
1247  }
1248 }
static List * ExpandSingleTable(ParseState *pstate, ParseNamespaceItem *nsitem, int sublevels_up, int location, bool make_target_entry)
Definition: nodes.h:528
#define strVal(v)
Definition: value.h:54
int errcode(int sqlerrcode)
Definition: elog.c:610
NameData relname
Definition: pg_class.h:38
#define lsecond(l)
Definition: pg_list.h:179
PostParseColumnRefHook p_post_columnref_hook
Definition: parse_node.h:219
int location
Definition: parsenodes.h:237
static List * ExpandRowReference(ParseState *pstate, Node *expr, bool make_target_entry)
RangeTblEntry * p_rte
Definition: parse_node.h:257
#define linitial(l)
Definition: pg_list.h:174
#define ERROR
Definition: elog.h:43
char * get_database_name(Oid dbid)
Definition: dbcommands.c:2155
void errorMissingRTE(ParseState *pstate, RangeVar *relation)
char * NameListToString(List *names)
Definition: namespace.c:3101
Oid MyDatabaseId
Definition: globals.c:85
#define ereport(elevel,...)
Definition: elog.h:144
ParseNamespaceItem * refnameNamespaceItem(ParseState *pstate, const char *schemaname, const char *refname, int location, int *sublevels_up)
#define Assert(condition)
Definition: c.h:746
static int list_length(const List *l)
Definition: pg_list.h:149
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110
int errmsg(const char *fmt,...)
Definition: elog.c:821
static List * ExpandAllTables(ParseState *pstate, int location)
#define lthird(l)
Definition: pg_list.h:184
PreParseColumnRefHook p_pre_columnref_hook
Definition: parse_node.h:218
Definition: pg_list.h:50
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition: makefuncs.c:422
List * fields
Definition: parsenodes.h:236

◆ ExpandIndirectionStar()

static List * ExpandIndirectionStar ( ParseState pstate,
A_Indirection ind,
bool  make_target_entry,
ParseExprKind  exprKind 
)
static

Definition at line 1313 of file parse_target.c.

References copyObject, ExpandRowReference(), A_Indirection::indirection, list_length(), list_truncate(), and transformExpr().

Referenced by transformExpressionList(), and transformTargetList().

1315 {
1316  Node *expr;
1317 
1318  /* Strip off the '*' to create a reference to the rowtype object */
1319  ind = copyObject(ind);
1321  list_length(ind->indirection) - 1);
1322 
1323  /* And transform that */
1324  expr = transformExpr(pstate, (Node *) ind, exprKind);
1325 
1326  /* Expand the rowtype expression into individual fields */
1327  return ExpandRowReference(pstate, expr, make_target_entry);
1328 }
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:145
List * list_truncate(List *list, int new_size)
Definition: list.c:585
Definition: nodes.h:528
static List * ExpandRowReference(ParseState *pstate, Node *expr, bool make_target_entry)
List * indirection
Definition: parsenodes.h:408
static int list_length(const List *l)
Definition: pg_list.h:149
#define copyObject(obj)
Definition: nodes.h:644

◆ expandRecordVariable()

TupleDesc expandRecordVariable ( ParseState pstate,
Var var,
int  levelsup 
)

Definition at line 1478 of file parse_target.c.

References Alias::aliasname, Assert, attnum, CreateTemplateTupleDesc(), RangeTblEntry::ctelevelsup, CommonTableExpr::ctequery, elog, RangeTblEntry::eref, ERROR, expandRecordVariable(), expandRTE(), TargetEntry::expr, exprCollation(), exprType(), exprTypmod(), forboth, get_expr_result_tupdesc(), get_tle_by_resno(), GetCTEForRTE(), GetCTETargetList, GetRTEByRangeTablePosn(), i, InvalidAttrNumber, IsA, RangeTblEntry::joinaliasvars, label, lfirst, list_length(), list_nth(), Var::location, MemSet, ParseState::p_rtable, ParseState::parentParseState, TargetEntry::resjunk, Query::rtable, RTE_CTE, RTE_FUNCTION, RTE_JOIN, RTE_NAMEDTUPLESTORE, RTE_RELATION, RTE_RESULT, RTE_SUBQUERY, RTE_TABLEFUNC, RTE_VALUES, RangeTblEntry::rtekind, RangeTblEntry::self_reference, strVal, RangeTblEntry::subquery, Query::targetList, TupleDescInitEntry(), TupleDescInitEntryCollation(), Var::varattno, Var::varlevelsup, Var::varno, and Var::vartype.

Referenced by expandRecordVariable(), ExpandRowReference(), and ParseComplexProjection().

1479 {
1480  TupleDesc tupleDesc;
1481  int netlevelsup;
1482  RangeTblEntry *rte;
1484  Node *expr;
1485 
1486  /* Check my caller didn't mess up */
1487  Assert(IsA(var, Var));
1488  Assert(var->vartype == RECORDOID);
1489 
1490  /*
1491  * Note: it's tempting to use GetNSItemByRangeTablePosn here so that we
1492  * can use expandNSItemVars instead of expandRTE; but that does not work
1493  * for some of the recursion cases below, where we have consed up a
1494  * ParseState that lacks p_namespace data.
1495  */
1496  netlevelsup = var->varlevelsup + levelsup;
1497  rte = GetRTEByRangeTablePosn(pstate, var->varno, netlevelsup);
1498  attnum = var->varattno;
1499 
1500  if (attnum == InvalidAttrNumber)
1501  {
1502  /* Whole-row reference to an RTE, so expand the known fields */
1503  List *names,
1504  *vars;
1505  ListCell *lname,
1506  *lvar;
1507  int i;
1508 
1509  expandRTE(rte, var->varno, 0, var->location, false,
1510  &names, &vars);
1511 
1512  tupleDesc = CreateTemplateTupleDesc(list_length(vars));
1513  i = 1;
1514  forboth(lname, names, lvar, vars)
1515  {
1516  char *label = strVal(lfirst(lname));
1517  Node *varnode = (Node *) lfirst(lvar);
1518 
1519  TupleDescInitEntry(tupleDesc, i,
1520  label,
1521  exprType(varnode),
1522  exprTypmod(varnode),
1523  0);
1524  TupleDescInitEntryCollation(tupleDesc, i,
1525  exprCollation(varnode));
1526  i++;
1527  }
1528  Assert(lname == NULL && lvar == NULL); /* lists same length? */
1529 
1530  return tupleDesc;
1531  }
1532 
1533  expr = (Node *) var; /* default if we can't drill down */
1534 
1535  switch (rte->rtekind)
1536  {
1537  case RTE_RELATION:
1538  case RTE_VALUES:
1539  case RTE_NAMEDTUPLESTORE:
1540  case RTE_RESULT:
1541 
1542  /*
1543  * This case should not occur: a column of a table, values list,
1544  * or ENR shouldn't have type RECORD. Fall through and fail (most
1545  * likely) at the bottom.
1546  */
1547  break;
1548  case RTE_SUBQUERY:
1549  {
1550  /* Subselect-in-FROM: examine sub-select's output expr */
1552  attnum);
1553 
1554  if (ste == NULL || ste->resjunk)
1555  elog(ERROR, "subquery %s does not have attribute %d",
1556  rte->eref->aliasname, attnum);
1557  expr = (Node *) ste->expr;
1558  if (IsA(expr, Var))
1559  {
1560  /*
1561  * Recurse into the sub-select to see what its Var refers
1562  * to. We have to build an additional level of ParseState
1563  * to keep in step with varlevelsup in the subselect.
1564  */
1565  ParseState mypstate;
1566 
1567  MemSet(&mypstate, 0, sizeof(mypstate));
1568  mypstate.parentParseState = pstate;
1569  mypstate.p_rtable = rte->subquery->rtable;
1570  /* don't bother filling the rest of the fake pstate */
1571 
1572  return expandRecordVariable(&mypstate, (Var *) expr, 0);
1573  }
1574  /* else fall through to inspect the expression */
1575  }
1576  break;
1577  case RTE_JOIN:
1578  /* Join RTE --- recursively inspect the alias variable */
1579  Assert(attnum > 0 && attnum <= list_length(rte->joinaliasvars));
1580  expr = (Node *) list_nth(rte->joinaliasvars, attnum - 1);
1581  Assert(expr != NULL);
1582  /* We intentionally don't strip implicit coercions here */
1583  if (IsA(expr, Var))
1584  return expandRecordVariable(pstate, (Var *) expr, netlevelsup);
1585  /* else fall through to inspect the expression */
1586  break;
1587  case RTE_FUNCTION:
1588 
1589  /*
1590  * We couldn't get here unless a function is declared with one of
1591  * its result columns as RECORD, which is not allowed.
1592  */
1593  break;
1594  case RTE_TABLEFUNC:
1595 
1596  /*
1597  * Table function cannot have columns with RECORD type.
1598  */
1599  break;
1600  case RTE_CTE:
1601  /* CTE reference: examine subquery's output expr */
1602  if (!rte->self_reference)
1603  {
1604  CommonTableExpr *cte = GetCTEForRTE(pstate, rte, netlevelsup);
1605  TargetEntry *ste;
1606 
1607  ste = get_tle_by_resno(GetCTETargetList(cte), attnum);
1608  if (ste == NULL || ste->resjunk)
1609  elog(ERROR, "CTE %s does not have attribute %d",
1610  rte->eref->aliasname, attnum);
1611  expr = (Node *) ste->expr;
1612  if (IsA(expr, Var))
1613  {
1614  /*
1615  * Recurse into the CTE to see what its Var refers to. We
1616  * have to build an additional level of ParseState to keep
1617  * in step with varlevelsup in the CTE; furthermore it
1618  * could be an outer CTE.
1619  */
1620  ParseState mypstate;
1621  Index levelsup;
1622 
1623  MemSet(&mypstate, 0, sizeof(mypstate));
1624  /* this loop must work, since GetCTEForRTE did */
1625  for (levelsup = 0;
1626  levelsup < rte->ctelevelsup + netlevelsup;
1627  levelsup++)
1628  pstate = pstate->parentParseState;
1629  mypstate.parentParseState = pstate;
1630  mypstate.p_rtable = ((Query *) cte->ctequery)->rtable;
1631  /* don't bother filling the rest of the fake pstate */
1632 
1633  return expandRecordVariable(&mypstate, (Var *) expr, 0);
1634  }
1635  /* else fall through to inspect the expression */
1636  }
1637  break;
1638  }
1639 
1640  /*
1641  * We now have an expression we can't expand any more, so see if
1642  * get_expr_result_tupdesc() can do anything with it.
1643  */
1644  return get_expr_result_tupdesc(expr, false);
1645 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:579
List * joinaliasvars
Definition: parsenodes.h:1052
Index varlevelsup
Definition: primnodes.h:191
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:434
TupleDesc CreateTemplateTupleDesc(int natts)
Definition: tupdesc.c:44
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:275
ParseState * parentParseState
Definition: parse_node.h:178
CommonTableExpr * GetCTEForRTE(ParseState *pstate, RangeTblEntry *rte, int rtelevelsup)
Definition: nodes.h:528
#define strVal(v)
Definition: value.h:54
#define MemSet(start, val, len)
Definition: c.h:950
AttrNumber varattno
Definition: primnodes.h:186
Definition: primnodes.h:181
List * targetList
Definition: parsenodes.h:140
bool resjunk
Definition: primnodes.h:1417
List * rtable
Definition: parsenodes.h:137
#define ERROR
Definition: elog.h:43
TupleDesc get_expr_result_tupdesc(Node *expr, bool noError)
Definition: funcapi.c:438
static void * list_nth(const List *list, int n)
Definition: pg_list.h:266
Oid vartype
Definition: primnodes.h:188
void TupleDescInitEntryCollation(TupleDesc desc, AttrNumber attributeNumber, Oid collationid)
Definition: tupdesc.c:769
int location
Definition: primnodes.h:196
TupleDesc expandRecordVariable(ParseState *pstate, Var *var, int levelsup)
void TupleDescInitEntry(TupleDesc desc, AttrNumber attributeNumber, const char *attributeName, Oid oidtypeid, int32 typmod, int attdim)
Definition: tupdesc.c:603
Index varno
Definition: primnodes.h:184
void expandRTE(RangeTblEntry *rte, int rtindex, int sublevels_up, int location, bool include_dropped, List **colnames, List **colvars)
bool self_reference
Definition: parsenodes.h:1082
static char * label
RangeTblEntry * GetRTEByRangeTablePosn(ParseState *pstate, int varno, int sublevels_up)
unsigned int Index
Definition: c.h:483
int16 attnum
Definition: pg_attribute.h:79
#define Assert(condition)
Definition: c.h:746
#define lfirst(lc)
Definition: pg_list.h:169
char * aliasname
Definition: primnodes.h:42
Expr * expr
Definition: primnodes.h:1410
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
static int list_length(const List *l)
Definition: pg_list.h:149
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:768
Index ctelevelsup
Definition: parsenodes.h:1081
#define InvalidAttrNumber
Definition: attnum.h:23
RTEKind rtekind
Definition: parsenodes.h:977
Query * subquery
Definition: parsenodes.h:1012
#define elog(elevel,...)
Definition: elog.h:214
int i
TargetEntry * get_tle_by_resno(List *tlist, AttrNumber resno)
Alias * eref
Definition: parsenodes.h:1116
Definition: regcomp.c:224
Definition: pg_list.h:50
#define GetCTETargetList(cte)
Definition: parsenodes.h:1468
int16 AttrNumber
Definition: attnum.h:21
List * p_rtable
Definition: parse_node.h:180

◆ ExpandRowReference()

static List * ExpandRowReference ( ParseState pstate,
Node expr,
bool  make_target_entry 
)
static

Definition at line 1383 of file parse_target.c.

References FieldSelect::arg, Assert, copyObject, expandRecordVariable(), ExpandSingleTable(), FieldSelect::fieldnum, get_expr_result_tupdesc(), GetNSItemByRangeTablePosn(), i, InvalidAttrNumber, IsA, lappend(), Var::location, makeNode, makeTargetEntry(), NameStr, TupleDescData::natts, NIL, ParseState::p_next_resno, pstrdup(), FieldSelect::resultcollid, FieldSelect::resulttype, FieldSelect::resulttypmod, TupleDescAttr, Var::varlevelsup, and Var::varno.

Referenced by ExpandColumnRefStar(), and ExpandIndirectionStar().

1385 {
1386  List *result = NIL;
1387  TupleDesc tupleDesc;
1388  int numAttrs;
1389  int i;
1390 
1391  /*
1392  * If the rowtype expression is a whole-row Var, we can expand the fields
1393  * as simple Vars. Note: if the RTE is a relation, this case leaves us
1394  * with the RTE's selectedCols bitmap showing the whole row as needing
1395  * select permission, as well as the individual columns. However, we can
1396  * only get here for weird notations like (table.*).*, so it's not worth
1397  * trying to clean up --- arguably, the permissions marking is correct
1398  * anyway for such cases.
1399  */
1400  if (IsA(expr, Var) &&
1401  ((Var *) expr)->varattno == InvalidAttrNumber)
1402  {
1403  Var *var = (Var *) expr;
1404  ParseNamespaceItem *nsitem;
1405 
1406  nsitem = GetNSItemByRangeTablePosn(pstate, var->varno, var->varlevelsup);
1407  return ExpandSingleTable(pstate, nsitem, var->varlevelsup, var->location, make_target_entry);
1408  }
1409 
1410  /*
1411  * Otherwise we have to do it the hard way. Our current implementation is
1412  * to generate multiple copies of the expression and do FieldSelects.
1413  * (This can be pretty inefficient if the expression involves nontrivial
1414  * computation :-(.)
1415  *
1416  * Verify it's a composite type, and get the tupdesc.
1417  * get_expr_result_tupdesc() handles this conveniently.
1418  *
1419  * If it's a Var of type RECORD, we have to work even harder: we have to
1420  * find what the Var refers to, and pass that to get_expr_result_tupdesc.
1421  * That task is handled by expandRecordVariable().
1422  */
1423  if (IsA(expr, Var) &&
1424  ((Var *) expr)->vartype == RECORDOID)
1425  tupleDesc = expandRecordVariable(pstate, (Var *) expr, 0);
1426  else
1427  tupleDesc = get_expr_result_tupdesc(expr, false);
1428  Assert(tupleDesc);
1429 
1430  /* Generate a list of references to the individual fields */
1431  numAttrs = tupleDesc->natts;
1432  for (i = 0; i < numAttrs; i++)
1433  {
1434  Form_pg_attribute att = TupleDescAttr(tupleDesc, i);
1435  FieldSelect *fselect;
1436 
1437  if (att->attisdropped)
1438  continue;
1439 
1440  fselect = makeNode(FieldSelect);
1441  fselect->arg = (Expr *) copyObject(expr);
1442  fselect->fieldnum = i + 1;
1443  fselect->resulttype = att->atttypid;
1444  fselect->resulttypmod = att->atttypmod;
1445  /* save attribute's collation for parse_collate.c */
1446  fselect->resultcollid = att->attcollation;
1447 
1448  if (make_target_entry)
1449  {
1450  /* add TargetEntry decoration */
1451  TargetEntry *te;
1452 
1453  te = makeTargetEntry((Expr *) fselect,
1454  (AttrNumber) pstate->p_next_resno++,
1455  pstrdup(NameStr(att->attname)),
1456  false);
1457  result = lappend(result, te);
1458  }
1459  else
1460  result = lappend(result, fselect);
1461  }
1462 
1463  return result;
1464 }
#define NIL
Definition: pg_list.h:65
#define IsA(nodeptr, _type_)
Definition: nodes.h:579
Index varlevelsup
Definition: primnodes.h:191
Oid resulttype
Definition: primnodes.h:767
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
char * pstrdup(const char *in)
Definition: mcxt.c:1187
static List * ExpandSingleTable(ParseState *pstate, ParseNamespaceItem *nsitem, int sublevels_up, int location, bool make_target_entry)
Expr * arg
Definition: primnodes.h:765
Definition: primnodes.h:181
TupleDesc get_expr_result_tupdesc(Node *expr, bool noError)
Definition: funcapi.c:438
Oid resultcollid
Definition: primnodes.h:770
int location
Definition: primnodes.h:196
int p_next_resno
Definition: parse_node.h:195
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:193
TupleDesc expandRecordVariable(ParseState *pstate, Var *var, int levelsup)
TargetEntry * makeTargetEntry(Expr *expr, AttrNumber resno, char *resname, bool resjunk)
Definition: makefuncs.c:238
List * lappend(List *list, void *datum)
Definition: list.c:321
Index varno
Definition: primnodes.h:184
#define makeNode(_type_)
Definition: nodes.h:576
#define Assert(condition)
Definition: c.h:746
#define InvalidAttrNumber
Definition: attnum.h:23
ParseNamespaceItem * GetNSItemByRangeTablePosn(ParseState *pstate, int varno, int sublevels_up)
int i
#define NameStr(name)
Definition: c.h:623
#define copyObject(obj)
Definition: nodes.h:644
Definition: pg_list.h:50
int16 AttrNumber
Definition: attnum.h:21
int32 resulttypmod
Definition: primnodes.h:769
AttrNumber fieldnum
Definition: primnodes.h:766

◆ ExpandSingleTable()

static List * ExpandSingleTable ( ParseState pstate,
ParseNamespaceItem nsitem,
int  sublevels_up,
int  location,
bool  make_target_entry 
)
static

Definition at line 1340 of file parse_target.c.

References ACL_SELECT, expandNSItemAttrs(), expandNSItemVars(), lfirst, markVarForSelectPriv(), ParseNamespaceItem::p_rte, and RangeTblEntry::requiredPerms.

Referenced by ExpandColumnRefStar(), and ExpandRowReference().

1342 {
1343  if (make_target_entry)
1344  {
1345  /* expandNSItemAttrs handles permissions marking */
1346  return expandNSItemAttrs(pstate, nsitem, sublevels_up, location);
1347  }
1348  else
1349  {
1350  RangeTblEntry *rte = nsitem->p_rte;
1351  List *vars;
1352  ListCell *l;
1353 
1354  vars = expandNSItemVars(nsitem, sublevels_up, location, NULL);
1355 
1356  /*
1357  * Require read access to the table. This is normally redundant with
1358  * the markVarForSelectPriv calls below, but not if the table has zero
1359  * columns.
1360  */
1361  rte->requiredPerms |= ACL_SELECT;
1362 
1363  /* Require read access to each column */
1364  foreach(l, vars)
1365  {
1366  Var *var = (Var *) lfirst(l);
1367 
1368  markVarForSelectPriv(pstate, var, rte);
1369  }
1370 
1371  return vars;
1372  }
1373 }
void markVarForSelectPriv(ParseState *pstate, Var *var, RangeTblEntry *rte)
AclMode requiredPerms
Definition: parsenodes.h:1120
Definition: primnodes.h:181
RangeTblEntry * p_rte
Definition: parse_node.h:257
#define ACL_SELECT
Definition: parsenodes.h:75
#define lfirst(lc)
Definition: pg_list.h:169
List * expandNSItemVars(ParseNamespaceItem *nsitem, int sublevels_up, int location, List **colnames)
List * expandNSItemAttrs(ParseState *pstate, ParseNamespaceItem *nsitem, int sublevels_up, int location)
Definition: regcomp.c:224
Definition: pg_list.h:50

◆ FigureColname()

char* FigureColname ( Node node)

Definition at line 1658 of file parse_target.c.

References FigureColnameInternal(), and name.

Referenced by transformRangeFunction(), transformTargetEntry(), and transformXmlExpr().

1659 {
1660  char *name = NULL;
1661 
1662  (void) FigureColnameInternal(node, &name);
1663  if (name != NULL)
1664  return name;
1665  /* default result if we can't guess anything */
1666  return "?column?";
1667 }
static int FigureColnameInternal(Node *node, char **name)
const char * name
Definition: encode.c:561

◆ FigureColnameInternal()

static int FigureColnameInternal ( Node node,
char **  name 
)
static

Definition at line 1697 of file parse_target.c.

References AEXPR_NULLIF, AEXPR_PAREN, ALL_SUBLINK, ANY_SUBLINK, arg, A_Indirection::arg, ARRAY_SUBLINK, CTE_SUBLINK, EXISTS_SUBLINK, EXPR_SUBLINK, i, A_Indirection::indirection, IS_DOCUMENT, IS_GREATEST, IS_LEAST, IS_XMLCONCAT, IS_XMLELEMENT, IS_XMLFOREST, IS_XMLPARSE, IS_XMLPI, IS_XMLROOT, IS_XMLSERIALIZE, IsA, lfirst, linitial, llast, MULTIEXPR_SUBLINK, nodeTag, TargetEntry::resname, ROWCOMPARE_SUBLINK, strVal, SubLink::subselect, SVFOP_CURRENT_CATALOG, SVFOP_CURRENT_DATE, SVFOP_CURRENT_ROLE, SVFOP_CURRENT_SCHEMA, SVFOP_CURRENT_TIME, SVFOP_CURRENT_TIME_N, SVFOP_CURRENT_TIMESTAMP, SVFOP_CURRENT_TIMESTAMP_N, SVFOP_CURRENT_USER, SVFOP_LOCALTIME, SVFOP_LOCALTIME_N, SVFOP_LOCALTIMESTAMP, SVFOP_LOCALTIMESTAMP_N, SVFOP_SESSION_USER, SVFOP_USER, T_A_ArrayExpr, T_A_Expr, T_A_Indirection, T_CaseExpr, T_CoalesceExpr, T_CollateClause, T_ColumnRef, T_FuncCall, T_GroupingFunc, T_MinMaxExpr, T_RowExpr, T_SQLValueFunction, T_SubLink, T_TypeCast, T_XmlExpr, T_XmlSerialize, and Query::targetList.

Referenced by FigureColname(), and FigureIndexColname().

1698 {
1699  int strength = 0;
1700 
1701  if (node == NULL)
1702  return strength;
1703 
1704  switch (nodeTag(node))
1705  {
1706  case T_ColumnRef:
1707  {
1708  char *fname = NULL;
1709  ListCell *l;
1710 
1711  /* find last field name, if any, ignoring "*" */
1712  foreach(l, ((ColumnRef *) node)->fields)
1713  {
1714  Node *i = lfirst(l);
1715 
1716  if (IsA(i, String))
1717  fname = strVal(i);
1718  }
1719  if (fname)
1720  {
1721  *name = fname;
1722  return 2;
1723  }
1724  }
1725  break;
1726  case T_A_Indirection:
1727  {
1728  A_Indirection *ind = (A_Indirection *) node;
1729  char *fname = NULL;
1730  ListCell *l;
1731 
1732  /* find last field name, if any, ignoring "*" and subscripts */
1733  foreach(l, ind->indirection)
1734  {
1735  Node *i = lfirst(l);
1736 
1737  if (IsA(i, String))
1738  fname = strVal(i);
1739  }
1740  if (fname)
1741  {
1742  *name = fname;
1743  return 2;
1744  }
1745  return FigureColnameInternal(ind->arg, name);
1746  }
1747  break;
1748  case T_FuncCall:
1749  *name = strVal(llast(((FuncCall *) node)->funcname));
1750  return 2;
1751  case T_A_Expr:
1752  if (((A_Expr *) node)->kind == AEXPR_NULLIF)
1753  {
1754  /* make nullif() act like a regular function */
1755  *name = "nullif";
1756  return 2;
1757  }
1758  if (((A_Expr *) node)->kind == AEXPR_PAREN)
1759  {
1760  /* look through dummy parenthesis node */
1761  return FigureColnameInternal(((A_Expr *) node)->lexpr, name);
1762  }
1763  break;
1764  case T_TypeCast:
1765  strength = FigureColnameInternal(((TypeCast *) node)->arg,
1766  name);
1767  if (strength <= 1)
1768  {
1769  if (((TypeCast *) node)->typeName != NULL)
1770  {
1771  *name = strVal(llast(((TypeCast *) node)->typeName->names));
1772  return 1;
1773  }
1774  }
1775  break;
1776  case T_CollateClause:
1777  return FigureColnameInternal(((CollateClause *) node)->arg, name);
1778  case T_GroupingFunc:
1779  /* make GROUPING() act like a regular function */
1780  *name = "grouping";
1781  return 2;
1782  case T_SubLink:
1783  switch (((SubLink *) node)->subLinkType)
1784  {
1785  case EXISTS_SUBLINK:
1786  *name = "exists";
1787  return 2;
1788  case ARRAY_SUBLINK:
1789  *name = "array";
1790  return 2;
1791  case EXPR_SUBLINK:
1792  {
1793  /* Get column name of the subquery's single target */
1794  SubLink *sublink = (SubLink *) node;
1795  Query *query = (Query *) sublink->subselect;
1796 
1797  /*
1798  * The subquery has probably already been transformed,
1799  * but let's be careful and check that. (The reason
1800  * we can see a transformed subquery here is that
1801  * transformSubLink is lazy and modifies the SubLink
1802  * node in-place.)
1803  */
1804  if (IsA(query, Query))
1805  {
1806  TargetEntry *te = (TargetEntry *) linitial(query->targetList);
1807 
1808  if (te->resname)
1809  {
1810  *name = te->resname;
1811  return 2;
1812  }
1813  }
1814  }
1815  break;
1816  /* As with other operator-like nodes, these have no names */
1817  case MULTIEXPR_SUBLINK:
1818  case ALL_SUBLINK:
1819  case ANY_SUBLINK:
1820  case ROWCOMPARE_SUBLINK:
1821  case CTE_SUBLINK:
1822  break;
1823  }
1824  break;
1825  case T_CaseExpr:
1826  strength = FigureColnameInternal((Node *) ((CaseExpr *) node)->defresult,
1827  name);
1828  if (strength <= 1)
1829  {
1830  *name = "case";
1831  return 1;
1832  }
1833  break;
1834  case T_A_ArrayExpr:
1835  /* make ARRAY[] act like a function */
1836  *name = "array";
1837  return 2;
1838  case T_RowExpr:
1839  /* make ROW() act like a function */
1840  *name = "row";
1841  return 2;
1842  case T_CoalesceExpr:
1843  /* make coalesce() act like a regular function */
1844  *name = "coalesce";
1845  return 2;
1846  case T_MinMaxExpr:
1847  /* make greatest/least act like a regular function */
1848  switch (((MinMaxExpr *) node)->op)
1849  {
1850  case IS_GREATEST:
1851  *name = "greatest";
1852  return 2;
1853  case IS_LEAST:
1854  *name = "least";
1855  return 2;
1856  }
1857  break;
1858  case T_SQLValueFunction:
1859  /* make these act like a function or variable */
1860  switch (((SQLValueFunction *) node)->op)
1861  {
1862  case SVFOP_CURRENT_DATE:
1863  *name = "current_date";
1864  return 2;
1865  case SVFOP_CURRENT_TIME:
1866  case SVFOP_CURRENT_TIME_N:
1867  *name = "current_time";
1868  return 2;
1871  *name = "current_timestamp";
1872  return 2;
1873  case SVFOP_LOCALTIME:
1874  case SVFOP_LOCALTIME_N:
1875  *name = "localtime";
1876  return 2;
1877  case SVFOP_LOCALTIMESTAMP:
1879  *name = "localtimestamp";
1880  return 2;
1881  case SVFOP_CURRENT_ROLE:
1882  *name = "current_role";
1883  return 2;
1884  case SVFOP_CURRENT_USER:
1885  *name = "current_user";
1886  return 2;
1887  case SVFOP_USER:
1888  *name = "user";
1889  return 2;
1890  case SVFOP_SESSION_USER:
1891  *name = "session_user";
1892  return 2;
1893  case SVFOP_CURRENT_CATALOG:
1894  *name = "current_catalog";
1895  return 2;
1896  case SVFOP_CURRENT_SCHEMA:
1897  *name = "current_schema";
1898  return 2;
1899  }
1900  break;
1901  case T_XmlExpr:
1902  /* make SQL/XML functions act like a regular function */
1903  switch (((XmlExpr *) node)->op)
1904  {
1905  case IS_XMLCONCAT:
1906  *name = "xmlconcat";
1907  return 2;
1908  case IS_XMLELEMENT:
1909  *name = "xmlelement";
1910  return 2;
1911  case IS_XMLFOREST:
1912  *name = "xmlforest";
1913  return 2;
1914  case IS_XMLPARSE:
1915  *name = "xmlparse";
1916  return 2;
1917  case IS_XMLPI:
1918  *name = "xmlpi";
1919  return 2;
1920  case IS_XMLROOT:
1921  *name = "xmlroot";
1922  return 2;
1923  case IS_XMLSERIALIZE:
1924  *name = "xmlserialize";
1925  return 2;
1926  case IS_DOCUMENT:
1927  /* nothing */
1928  break;
1929  }
1930  break;
1931  case T_XmlSerialize:
1932  *name = "xmlserialize";
1933  return 2;
1934  default:
1935  break;
1936  }
1937 
1938  return strength;
1939 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:579
#define llast(l)
Definition: pg_list.h:194
Definition: nodes.h:528
#define strVal(v)
Definition: value.h:54
char * resname
Definition: primnodes.h:1412
List * targetList
Definition: parsenodes.h:140
#define linitial(l)
Definition: pg_list.h:174
#define lfirst(lc)
Definition: pg_list.h:169
List * indirection
Definition: parsenodes.h:408
static int FigureColnameInternal(Node *node, char **name)
const char * name
Definition: encode.c:561
#define nodeTag(nodeptr)
Definition: nodes.h:533
int i
void * arg

◆ FigureIndexColname()

char* FigureIndexColname ( Node node)

Definition at line 1677 of file parse_target.c.

References FigureColnameInternal(), and name.

Referenced by transformIndexStmt().

1678 {
1679  char *name = NULL;
1680 
1681  (void) FigureColnameInternal(node, &name);
1682  return name;
1683 }
static int FigureColnameInternal(Node *node, char **name)
const char * name
Definition: encode.c:561

◆ markTargetListOrigin()

static void markTargetListOrigin ( ParseState pstate,
TargetEntry tle,
Var var,
int  levelsup 
)
static

Definition at line 356 of file parse_target.c.

References Alias::aliasname, attnum, elog, RangeTblEntry::eref, ERROR, get_tle_by_resno(), GetCTEForRTE(), GetCTETargetList, GetRTEByRangeTablePosn(), InvalidAttrNumber, IsA, RangeTblEntry::relid, TargetEntry::resjunk, TargetEntry::resorigcol, TargetEntry::resorigtbl, RTE_CTE, RTE_FUNCTION, RTE_JOIN, RTE_NAMEDTUPLESTORE, RTE_RELATION, RTE_RESULT, RTE_SUBQUERY, RTE_TABLEFUNC, RTE_VALUES, RangeTblEntry::rtekind, RangeTblEntry::self_reference, RangeTblEntry::subquery, Query::targetList, Var::varattno, Var::varlevelsup, and Var::varno.

Referenced by markTargetListOrigins().

358 {
359  int netlevelsup;
360  RangeTblEntry *rte;
362 
363  if (var == NULL || !IsA(var, Var))
364  return;
365  netlevelsup = var->varlevelsup + levelsup;
366  rte = GetRTEByRangeTablePosn(pstate, var->varno, netlevelsup);
367  attnum = var->varattno;
368 
369  switch (rte->rtekind)
370  {
371  case RTE_RELATION:
372  /* It's a table or view, report it */
373  tle->resorigtbl = rte->relid;
374  tle->resorigcol = attnum;
375  break;
376  case RTE_SUBQUERY:
377  /* Subselect-in-FROM: copy up from the subselect */
378  if (attnum != InvalidAttrNumber)
379  {
381  attnum);
382 
383  if (ste == NULL || ste->resjunk)
384  elog(ERROR, "subquery %s does not have attribute %d",
385  rte->eref->aliasname, attnum);
386  tle->resorigtbl = ste->resorigtbl;
387  tle->resorigcol = ste->resorigcol;
388  }
389  break;
390  case RTE_JOIN:
391  case RTE_FUNCTION:
392  case RTE_VALUES:
393  case RTE_TABLEFUNC:
394  case RTE_NAMEDTUPLESTORE:
395  case RTE_RESULT:
396  /* not a simple relation, leave it unmarked */
397  break;
398  case RTE_CTE:
399 
400  /*
401  * CTE reference: copy up from the subquery, if possible. If the
402  * RTE is a recursive self-reference then we can't do anything
403  * because we haven't finished analyzing it yet. However, it's no
404  * big loss because we must be down inside the recursive term of a
405  * recursive CTE, and so any markings on the current targetlist
406  * are not going to affect the results anyway.
407  */
408  if (attnum != InvalidAttrNumber && !rte->self_reference)
409  {
410  CommonTableExpr *cte = GetCTEForRTE(pstate, rte, netlevelsup);
411  TargetEntry *ste;
412 
413  ste = get_tle_by_resno(GetCTETargetList(cte), attnum);
414  if (ste == NULL || ste->resjunk)
415  elog(ERROR, "CTE %s does not have attribute %d",
416  rte->eref->aliasname, attnum);
417  tle->resorigtbl = ste->resorigtbl;
418  tle->resorigcol = ste->resorigcol;
419  }
420  break;
421  }
422 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:579
Index varlevelsup
Definition: primnodes.h:191
CommonTableExpr * GetCTEForRTE(ParseState *pstate, RangeTblEntry *rte, int rtelevelsup)
Oid resorigtbl
Definition: primnodes.h:1415
AttrNumber varattno
Definition: primnodes.h:186
Definition: primnodes.h:181
List * targetList
Definition: parsenodes.h:140
bool resjunk
Definition: primnodes.h:1417
#define ERROR
Definition: elog.h:43
Index varno
Definition: primnodes.h:184
bool self_reference
Definition: parsenodes.h:1082
RangeTblEntry * GetRTEByRangeTablePosn(ParseState *pstate, int varno, int sublevels_up)
int16 attnum
Definition: pg_attribute.h:79
char * aliasname
Definition: primnodes.h:42
#define InvalidAttrNumber
Definition: attnum.h:23
RTEKind rtekind
Definition: parsenodes.h:977
AttrNumber resorigcol
Definition: primnodes.h:1416
Query * subquery
Definition: parsenodes.h:1012
#define elog(elevel,...)
Definition: elog.h:214
TargetEntry * get_tle_by_resno(List *tlist, AttrNumber resno)
Alias * eref
Definition: parsenodes.h:1116
#define GetCTETargetList(cte)
Definition: parsenodes.h:1468
int16 AttrNumber
Definition: attnum.h:21

◆ markTargetListOrigins()

void markTargetListOrigins ( ParseState pstate,
List targetlist 
)

Definition at line 331 of file parse_target.c.

References TargetEntry::expr, lfirst, and markTargetListOrigin().

Referenced by transformReturningList(), and transformSelectStmt().

332 {
333  ListCell *l;
334 
335  foreach(l, targetlist)
336  {
337  TargetEntry *tle = (TargetEntry *) lfirst(l);
338 
339  markTargetListOrigin(pstate, tle, (Var *) tle->expr, 0);
340  }
341 }
Definition: primnodes.h:181
#define lfirst(lc)
Definition: pg_list.h:169
Expr * expr
Definition: primnodes.h:1410
static void markTargetListOrigin(ParseState *pstate, TargetEntry *tle, Var *var, int levelsup)
Definition: parse_target.c:356

◆ resolveTargetListUnknowns()

void resolveTargetListUnknowns ( ParseState pstate,
List targetlist 
)

Definition at line 301 of file parse_target.c.

References COERCE_IMPLICIT_CAST, coerce_type(), COERCION_IMPLICIT, TargetEntry::expr, exprType(), and lfirst.

Referenced by transformReturningList(), and transformSelectStmt().

302 {
303  ListCell *l;
304 
305  foreach(l, targetlist)
306  {
307  TargetEntry *tle = (TargetEntry *) lfirst(l);
308  Oid restype = exprType((Node *) tle->expr);
309 
310  if (restype == UNKNOWNOID)
311  {
312  tle->expr = (Expr *) coerce_type(pstate, (Node *) tle->expr,
313  restype, TEXTOID, -1,
316  -1);
317  }
318  }
319 }
Node * coerce_type(ParseState *pstate, Node *node, Oid inputTypeId, Oid targetTypeId, int32 targetTypeMod, CoercionContext ccontext, CoercionForm cformat, int location)
Definition: parse_coerce.c:155
Definition: nodes.h:528
unsigned int Oid
Definition: postgres_ext.h:31
#define lfirst(lc)
Definition: pg_list.h:169
Expr * expr
Definition: primnodes.h:1410
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41

◆ transformAssignedExpr()

Expr* transformAssignedExpr ( ParseState pstate,
Expr expr,
ParseExprKind  exprKind,
const char *  colname,
int  attrno,
List indirection,
int  location 
)

Definition at line 450 of file parse_target.c.

References Assert, attnumTypeId(), COERCE_IMPLICIT_CAST, coerce_to_target_type(), COERCION_ASSIGNMENT, SetToDefault::collation, ereport, errcode(), errhint(), errmsg(), ERROR, EXPR_KIND_NONE, exprLocation(), exprType(), format_type_be(), IsA, linitial, list_head(), Var::location, makeNullConst(), makeVar(), ParseState::p_expr_kind, ParseState::p_is_insert, ParseNamespaceItem::p_rtindex, ParseState::p_target_nsitem, ParseState::p_target_relation, parser_errposition(), RelationData::rd_att, transformAssignmentIndirection(), TupleDescAttr, SetToDefault::typeId, and SetToDefault::typeMod.

Referenced by transformInsertRow(), and updateTargetListEntry().

457 {
458  Relation rd = pstate->p_target_relation;
459  Oid type_id; /* type of value provided */
460  Oid attrtype; /* type of target column */
461  int32 attrtypmod;
462  Oid attrcollation; /* collation of target column */
463  ParseExprKind sv_expr_kind;
464 
465  /*
466  * Save and restore identity of expression type we're parsing. We must
467  * set p_expr_kind here because we can parse subscripts without going
468  * through transformExpr().
469  */
470  Assert(exprKind != EXPR_KIND_NONE);
471  sv_expr_kind = pstate->p_expr_kind;
472  pstate->p_expr_kind = exprKind;
473 
474  Assert(rd != NULL);
475  if (attrno <= 0)
476  ereport(ERROR,
477  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
478  errmsg("cannot assign to system column \"%s\"",
479  colname),
480  parser_errposition(pstate, location)));
481  attrtype = attnumTypeId(rd, attrno);
482  attrtypmod = TupleDescAttr(rd->rd_att, attrno - 1)->atttypmod;
483  attrcollation = TupleDescAttr(rd->rd_att, attrno - 1)->attcollation;
484 
485  /*
486  * If the expression is a DEFAULT placeholder, insert the attribute's
487  * type/typmod/collation into it so that exprType etc will report the
488  * right things. (We expect that the eventually substituted default
489  * expression will in fact have this type and typmod. The collation
490  * likely doesn't matter, but let's set it correctly anyway.) Also,
491  * reject trying to update a subfield or array element with DEFAULT, since
492  * there can't be any default for portions of a column.
493  */
494  if (expr && IsA(expr, SetToDefault))
495  {
496  SetToDefault *def = (SetToDefault *) expr;
497 
498  def->typeId = attrtype;
499  def->typeMod = attrtypmod;
500  def->collation = attrcollation;
501  if (indirection)
502  {
503  if (IsA(linitial(indirection), A_Indices))
504  ereport(ERROR,
505  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
506  errmsg("cannot set an array element to DEFAULT"),
507  parser_errposition(pstate, location)));
508  else
509  ereport(ERROR,
510  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
511  errmsg("cannot set a subfield to DEFAULT"),
512  parser_errposition(pstate, location)));
513  }
514  }
515 
516  /* Now we can use exprType() safely. */
517  type_id = exprType((Node *) expr);
518 
519  /*
520  * If there is indirection on the target column, prepare an array or
521  * subfield assignment expression. This will generate a new column value
522  * that the source value has been inserted into, which can then be placed
523  * in the new tuple constructed by INSERT or UPDATE.
524  */
525  if (indirection)
526  {
527  Node *colVar;
528 
529  if (pstate->p_is_insert)
530  {
531  /*
532  * The command is INSERT INTO table (col.something) ... so there
533  * is not really a source value to work with. Insert a NULL
534  * constant as the source value.
535  */
536  colVar = (Node *) makeNullConst(attrtype, attrtypmod,
537  attrcollation);
538  }
539  else
540  {
541  /*
542  * Build a Var for the column to be updated.
543  */
544  Var *var;
545 
546  var = makeVar(pstate->p_target_nsitem->p_rtindex, attrno,
547  attrtype, attrtypmod, attrcollation, 0);
548  var->location = location;
549 
550  colVar = (Node *) var;
551  }
552 
553  expr = (Expr *)
555  colVar,
556  colname,
557  false,
558  attrtype,
559  attrtypmod,
560  attrcollation,
561  indirection,
562  list_head(indirection),
563  (Node *) expr,
564  location);
565  }
566  else
567  {
568  /*
569  * For normal non-qualified target column, do type checking and
570  * coercion.
571  */
572  Node *orig_expr = (Node *) expr;
573 
574  expr = (Expr *)
575  coerce_to_target_type(pstate,
576  orig_expr, type_id,
577  attrtype, attrtypmod,
580  -1);
581  if (expr == NULL)
582  ereport(ERROR,
583  (errcode(ERRCODE_DATATYPE_MISMATCH),
584  errmsg("column \"%s\" is of type %s"
585  " but expression is of type %s",
586  colname,
587  format_type_be(attrtype),
588  format_type_be(type_id)),
589  errhint("You will need to rewrite or cast the expression."),
590  parser_errposition(pstate, exprLocation(orig_expr))));
591  }
592 
593  pstate->p_expr_kind = sv_expr_kind;
594 
595  return expr;
596 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:579
int errhint(const char *fmt,...)
Definition: elog.c:1068
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1240
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
static Node * transformAssignmentIndirection(ParseState *pstate, Node *basenode, const char *targetName, bool targetIsSubscripting, Oid targetTypeId, int32 targetTypMod, Oid targetCollation, List *indirection, ListCell *indirection_cell, Node *rhs, int location)
Definition: parse_target.c:676
Definition: nodes.h:528
int errcode(int sqlerrcode)
Definition: elog.c:610
char * format_type_be(Oid type_oid)
Definition: format_type.c:339
ParseNamespaceItem * p_target_nsitem
Definition: parse_node.h:191
unsigned int Oid
Definition: postgres_ext.h:31
Definition: primnodes.h:181
ParseExprKind
Definition: parse_node.h:38
signed int int32
Definition: c.h:363
Const * makeNullConst(Oid consttype, int32 consttypmod, Oid constcollid)
Definition: makefuncs.c:337
#define linitial(l)
Definition: pg_list.h:174
#define ERROR
Definition: elog.h:43
Node * coerce_to_target_type(ParseState *pstate, Node *expr, Oid exprtype, Oid targettype, int32 targettypmod, CoercionContext ccontext, CoercionForm cformat, int location)
Definition: parse_coerce.c:77
int location
Definition: primnodes.h:196
int32 typeMod
Definition: primnodes.h:1299
Oid attnumTypeId(Relation rd, int attid)
static ListCell * list_head(const List *l)
Definition: pg_list.h:125
Var * makeVar(Index varno, AttrNumber varattno, Oid vartype, int32 vartypmod, Oid varcollid, Index varlevelsup)
Definition: makefuncs.c:66
ParseExprKind p_expr_kind
Definition: parse_node.h:194
TupleDesc rd_att
Definition: rel.h:110
#define ereport(elevel,...)
Definition: elog.h:144
#define Assert(condition)
Definition: c.h:746
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110
int errmsg(const char *fmt,...)
Definition: elog.c:821
Relation p_target_relation
Definition: parse_node.h:190
bool p_is_insert
Definition: parse_node.h:192

◆ transformAssignmentIndirection()

static Node * transformAssignmentIndirection ( ParseState pstate,
Node basenode,
const char *  targetName,
bool  targetIsSubscripting,
Oid  targetTypeId,
int32  targetTypMod,
Oid  targetCollation,
List indirection,
ListCell indirection_cell,
Node rhs,
int  location 
)
static

Definition at line 676 of file parse_target.c.

References FieldStore::arg, Assert, attnum, COERCE_IMPLICIT_CAST, coerce_to_domain(), coerce_to_target_type(), COERCION_ASSIGNMENT, COERCION_IMPLICIT, CaseTestExpr::collation, ereport, errcode(), errhint(), errmsg(), ERROR, exprType(), FieldStore::fieldnums, for_each_cell, format_type_be(), get_attnum(), get_atttypetypmodcoll(), getBaseTypeAndTypmod(), i, InvalidAttrNumber, IsA, lappend(), lfirst, list_make1, list_make1_int, lnext(), makeNode, FieldStore::newvals, NIL, parser_errposition(), FieldStore::resulttype, strVal, transformAssignmentSubscripts(), CaseTestExpr::typeId, typeidTypeRelid(), and CaseTestExpr::typeMod.

Referenced by transformAssignedExpr(), and transformAssignmentSubscripts().

687 {
688  Node *result;
689  List *subscripts = NIL;
690  bool isSlice = false;
691  ListCell *i;
692 
693  if (indirection_cell && !basenode)
694  {
695  /*
696  * Set up a substitution. We abuse CaseTestExpr for this. It's safe
697  * to do so because the only nodes that will be above the CaseTestExpr
698  * in the finished expression will be FieldStore and SubscriptingRef
699  * nodes. (There could be other stuff in the tree, but it will be
700  * within other child fields of those node types.)
701  */
703 
704  ctest->typeId = targetTypeId;
705  ctest->typeMod = targetTypMod;
706  ctest->collation = targetCollation;
707  basenode = (Node *) ctest;
708  }
709 
710  /*
711  * We have to split any field-selection operations apart from
712  * subscripting. Adjacent A_Indices nodes have to be treated as a single
713  * multidimensional subscript operation.
714  */
715  for_each_cell(i, indirection, indirection_cell)
716  {
717  Node *n = lfirst(i);
718 
719  if (IsA(n, A_Indices))
720  {
721  subscripts = lappend(subscripts, n);
722  if (((A_Indices *) n)->is_slice)
723  isSlice = true;
724  }
725  else if (IsA(n, A_Star))
726  {
727  ereport(ERROR,
728  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
729  errmsg("row expansion via \"*\" is not supported here"),
730  parser_errposition(pstate, location)));
731  }
732  else
733  {
734  FieldStore *fstore;
735  Oid baseTypeId;
736  int32 baseTypeMod;
737  Oid typrelid;
739  Oid fieldTypeId;
740  int32 fieldTypMod;
741  Oid fieldCollation;
742 
743  Assert(IsA(n, String));
744 
745  /* process subscripts before this field selection */
746  if (subscripts)
747  {
748  /* recurse, and then return because we're done */
749  return transformAssignmentSubscripts(pstate,
750  basenode,
751  targetName,
752  targetTypeId,
753  targetTypMod,
754  targetCollation,
755  subscripts,
756  isSlice,
757  indirection,
758  i,
759  rhs,
760  location);
761  }
762 
763  /* No subscripts, so can process field selection here */
764 
765  /*
766  * Look up the composite type, accounting for possibility that
767  * what we are given is a domain over composite.
768  */
769  baseTypeMod = targetTypMod;
770  baseTypeId = getBaseTypeAndTypmod(targetTypeId, &baseTypeMod);
771 
772  typrelid = typeidTypeRelid(baseTypeId);
773  if (!typrelid)
774  ereport(ERROR,
775  (errcode(ERRCODE_DATATYPE_MISMATCH),
776  errmsg("cannot assign to field \"%s\" of column \"%s\" because its type %s is not a composite type",
777  strVal(n), targetName,
778  format_type_be(targetTypeId)),
779  parser_errposition(pstate, location)));
780 
781  attnum = get_attnum(typrelid, strVal(n));
782  if (attnum == InvalidAttrNumber)
783  ereport(ERROR,
784  (errcode(ERRCODE_UNDEFINED_COLUMN),
785  errmsg("cannot assign to field \"%s\" of column \"%s\" because there is no such column in data type %s",
786  strVal(n), targetName,
787  format_type_be(targetTypeId)),
788  parser_errposition(pstate, location)));
789  if (attnum < 0)
790  ereport(ERROR,
791  (errcode(ERRCODE_UNDEFINED_COLUMN),
792  errmsg("cannot assign to system column \"%s\"",
793  strVal(n)),
794  parser_errposition(pstate, location)));
795 
796  get_atttypetypmodcoll(typrelid, attnum,
797  &fieldTypeId, &fieldTypMod, &fieldCollation);
798 
799  /* recurse to create appropriate RHS for field assign */
800  rhs = transformAssignmentIndirection(pstate,
801  NULL,
802  strVal(n),
803  false,
804  fieldTypeId,
805  fieldTypMod,
806  fieldCollation,
807  indirection,
808  lnext(indirection, i),
809  rhs,
810  location);
811 
812  /* and build a FieldStore node */
813  fstore = makeNode(FieldStore);
814  fstore->arg = (Expr *) basenode;
815  fstore->newvals = list_make1(rhs);
816  fstore->fieldnums = list_make1_int(attnum);
817  fstore->resulttype = baseTypeId;
818 
819  /* If target is a domain, apply constraints */
820  if (baseTypeId != targetTypeId)
821  return coerce_to_domain((Node *) fstore,
822  baseTypeId, baseTypeMod,
823  targetTypeId,
826  location,
827  false);
828 
829  return (Node *) fstore;
830  }
831  }
832 
833  /* process trailing subscripts, if any */
834  if (subscripts)
835  {
836  /* recurse, and then return because we're done */
837  return transformAssignmentSubscripts(pstate,
838  basenode,
839  targetName,
840  targetTypeId,
841  targetTypMod,
842  targetCollation,
843  subscripts,
844  isSlice,
845  indirection,
846  NULL,
847  rhs,
848  location);
849  }
850 
851  /* base case: just coerce RHS to match target type ID */
852 
853  result = coerce_to_target_type(pstate,
854  rhs, exprType(rhs),
855  targetTypeId, targetTypMod,
858  -1);
859  if (result == NULL)
860  {
861  if (targetIsSubscripting)
862  ereport(ERROR,
863  (errcode(ERRCODE_DATATYPE_MISMATCH),
864  errmsg("array assignment to \"%s\" requires type %s"
865  " but expression is of type %s",
866  targetName,
867  format_type_be(targetTypeId),
868  format_type_be(exprType(rhs))),
869  errhint("You will need to rewrite or cast the expression."),
870  parser_errposition(pstate, location)));
871  else
872  ereport(ERROR,
873  (errcode(ERRCODE_DATATYPE_MISMATCH),
874  errmsg("subfield \"%s\" is of type %s"
875  " but expression is of type %s",
876  targetName,
877  format_type_be(targetTypeId),
878  format_type_be(exprType(rhs))),
879  errhint("You will need to rewrite or cast the expression."),
880  parser_errposition(pstate, location)));
881  }
882 
883  return result;
884 }
#define NIL
Definition: pg_list.h:65
Oid getBaseTypeAndTypmod(Oid typid, int32 *typmod)
Definition: lsyscache.c:2426
#define IsA(nodeptr, _type_)
Definition: nodes.h:579
Expr * arg
Definition: primnodes.h:794
int errhint(const char *fmt,...)
Definition: elog.c:1068
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:310
#define for_each_cell(cell, lst, initcell)
Definition: pg_list.h:405
static Node * transformAssignmentIndirection(ParseState *pstate, Node *basenode, const char *targetName, bool targetIsSubscripting, Oid targetTypeId, int32 targetTypMod, Oid targetCollation, List *indirection, ListCell *indirection_cell, Node *rhs, int location)
Definition: parse_target.c:676
Definition: nodes.h:528
#define strVal(v)
Definition: value.h:54
int errcode(int sqlerrcode)
Definition: elog.c:610
char * format_type_be(Oid type_oid)
Definition: format_type.c:339
Oid typeidTypeRelid(Oid type_id)
Definition: parse_type.c:666
unsigned int Oid
Definition: postgres_ext.h:31
int32 typeMod
Definition: primnodes.h:976
signed int int32
Definition: c.h:363
#define list_make1(x1)
Definition: pg_list.h:206
#define ERROR
Definition: elog.h:43
Node * coerce_to_target_type(ParseState *pstate, Node *expr, Oid exprtype, Oid targettype, int32 targettypmod, CoercionContext ccontext, CoercionForm cformat, int location)
Definition: parse_coerce.c:77
Node * coerce_to_domain(Node *arg, Oid baseTypeId, int32 baseTypeMod, Oid typeId, CoercionContext ccontext, CoercionForm cformat, int location, bool hideInputCoercion)
Definition: parse_coerce.c:666
AttrNumber get_attnum(Oid relid, const char *attname)
Definition: lsyscache.c:856
Oid resulttype
Definition: primnodes.h:797
#define list_make1_int(x1)
Definition: pg_list.h:217
List * newvals
Definition: primnodes.h:795
List * lappend(List *list, void *datum)
Definition: list.c:321
int16 attnum
Definition: pg_attribute.h:79
#define ereport(elevel,...)
Definition: elog.h:144
#define makeNode(_type_)
Definition: nodes.h:576
static Node * transformAssignmentSubscripts(ParseState *pstate, Node *basenode, const char *targetName, Oid targetTypeId, int32 targetTypMod, Oid targetCollation, List *subscripts, bool isSlice, List *indirection, ListCell *next_indirection, Node *rhs, int location)
Definition: parse_target.c:890
#define Assert(condition)
Definition: c.h:746
#define lfirst(lc)
Definition: pg_list.h:169
void get_atttypetypmodcoll(Oid relid, AttrNumber attnum, Oid *typid, int32 *typmod, Oid *collid)
Definition: lsyscache.c:941
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110
#define InvalidAttrNumber
Definition: attnum.h:23
int errmsg(const char *fmt,...)
Definition: elog.c:821
List * fieldnums
Definition: primnodes.h:796
int i
Definition: pg_list.h:50
int16 AttrNumber
Definition: attnum.h:21

◆ transformAssignmentSubscripts()

static Node * transformAssignmentSubscripts ( ParseState pstate,
Node basenode,
const char *  targetName,
Oid  targetTypeId,
int32  targetTypMod,
Oid  targetCollation,
List subscripts,
bool  isSlice,
List indirection,
ListCell next_indirection,
Node rhs,
int  location 
)
static

Definition at line 890 of file parse_target.c.

References Assert, COERCE_IMPLICIT_CAST, coerce_to_target_type(), COERCION_ASSIGNMENT, ereport, errcode(), errmsg(), ERROR, exprType(), format_type_be(), get_typcollation(), NIL, parser_errposition(), transformAssignmentIndirection(), transformContainerSubscripts(), and transformContainerType().

Referenced by transformAssignmentIndirection().

902 {
903  Node *result;
904  Oid containerType;
905  int32 containerTypMod;
906  Oid elementTypeId;
907  Oid typeNeeded;
908  Oid collationNeeded;
909 
910  Assert(subscripts != NIL);
911 
912  /* Identify the actual array type and element type involved */
913  containerType = targetTypeId;
914  containerTypMod = targetTypMod;
915  elementTypeId = transformContainerType(&containerType, &containerTypMod);
916 
917  /* Identify type that RHS must provide */
918  typeNeeded = isSlice ? containerType : elementTypeId;
919 
920  /*
921  * container normally has same collation as elements, but there's an
922  * exception: we might be subscripting a domain over a container type. In
923  * that case use collation of the base type.
924  */
925  if (containerType == targetTypeId)
926  collationNeeded = targetCollation;
927  else
928  collationNeeded = get_typcollation(containerType);
929 
930  /* recurse to create appropriate RHS for container assign */
931  rhs = transformAssignmentIndirection(pstate,
932  NULL,
933  targetName,
934  true,
935  typeNeeded,
936  containerTypMod,
937  collationNeeded,
938  indirection,
939  next_indirection,
940  rhs,
941  location);
942 
943  /* process subscripts */
944  result = (Node *) transformContainerSubscripts(pstate,
945  basenode,
946  containerType,
947  elementTypeId,
948  containerTypMod,
949  subscripts,
950  rhs);
951 
952  /* If target was a domain over container, need to coerce up to the domain */
953  if (containerType != targetTypeId)
954  {
955  Oid resulttype = exprType(result);
956 
957  result = coerce_to_target_type(pstate,
958  result, resulttype,
959  targetTypeId, targetTypMod,
962  -1);
963  /* can fail if we had int2vector/oidvector, but not for true domains */
964  if (result == NULL)
965  ereport(ERROR,
966  (errcode(ERRCODE_CANNOT_COERCE),
967  errmsg("cannot cast type %s to %s",
968  format_type_be(resulttype),
969  format_type_be(targetTypeId)),
970  parser_errposition(pstate, location)));
971  }
972 
973  return result;
974 }
#define NIL
Definition: pg_list.h:65
static Node * transformAssignmentIndirection(ParseState *pstate, Node *basenode, const char *targetName, bool targetIsSubscripting, Oid targetTypeId, int32 targetTypMod, Oid targetCollation, List *indirection, ListCell *indirection_cell, Node *rhs, int location)
Definition: parse_target.c:676
Definition: nodes.h:528
int errcode(int sqlerrcode)
Definition: elog.c:610
char * format_type_be(Oid type_oid)
Definition: format_type.c:339
unsigned int Oid
Definition: postgres_ext.h:31
signed int int32
Definition: c.h:363
#define ERROR
Definition: elog.h:43
Node * coerce_to_target_type(ParseState *pstate, Node *expr, Oid exprtype, Oid targettype, int32 targettypmod, CoercionContext ccontext, CoercionForm cformat, int location)
Definition: parse_coerce.c:77
SubscriptingRef * transformContainerSubscripts(ParseState *pstate, Node *containerBase, Oid containerType, Oid elementType, int32 containerTypMod, List *indirection, Node *assignFrom)
Definition: parse_node.c:276
#define ereport(elevel,...)
Definition: elog.h:144
Oid get_typcollation(Oid typid)
Definition: lsyscache.c:2933
#define Assert(condition)
Definition: c.h:746
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110
int errmsg(const char *fmt,...)
Definition: elog.c:821
Oid transformContainerType(Oid *containerType, int32 *containerTypmod)
Definition: parse_node.c:195

◆ transformExpressionList()

List* transformExpressionList ( ParseState pstate,
List exprlist,
ParseExprKind  exprKind,
bool  allowDefault 
)

Definition at line 230 of file parse_target.c.

References Assert, ExpandColumnRefStar(), ExpandIndirectionStar(), ColumnRef::fields, A_Indirection::indirection, IsA, lappend(), lfirst, list_concat(), llast, NIL, ParseState::p_multiassign_exprs, and transformExpr().

Referenced by transformInsertStmt(), transformRowExpr(), and transformValuesClause().

232 {
233  List *result = NIL;
234  ListCell *lc;
235 
236  foreach(lc, exprlist)
237  {
238  Node *e = (Node *) lfirst(lc);
239 
240  /*
241  * Check for "something.*". Depending on the complexity of the
242  * "something", the star could appear as the last field in ColumnRef,
243  * or as the last indirection item in A_Indirection.
244  */
245  if (IsA(e, ColumnRef))
246  {
247  ColumnRef *cref = (ColumnRef *) e;
248 
249  if (IsA(llast(cref->fields), A_Star))
250  {
251  /* It is something.*, expand into multiple items */
252  result = list_concat(result,
253  ExpandColumnRefStar(pstate, cref,
254  false));
255  continue;
256  }
257  }
258  else if (IsA(e, A_Indirection))
259  {
261 
262  if (IsA(llast(ind->indirection), A_Star))
263  {
264  /* It is something.*, expand into multiple items */
265  result = list_concat(result,
266  ExpandIndirectionStar(pstate, ind,
267  false, exprKind));
268  continue;
269  }
270  }
271 
272  /*
273  * Not "something.*", so transform as a single expression. If it's a
274  * SetToDefault node and we should allow that, pass it through
275  * unmodified. (transformExpr will throw the appropriate error if
276  * we're disallowing it.)
277  */
278  if (allowDefault && IsA(e, SetToDefault))
279  /* do nothing */ ;
280  else
281  e = transformExpr(pstate, e, exprKind);
282 
283  result = lappend(result, e);
284  }
285 
286  /* Shouldn't have any multiassign items here */
287  Assert(pstate->p_multiassign_exprs == NIL);
288 
289  return result;
290 }
#define NIL
Definition: pg_list.h:65
#define IsA(nodeptr, _type_)
Definition: nodes.h:579
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:145
#define llast(l)
Definition: pg_list.h:194
Definition: nodes.h:528
List * list_concat(List *list1, const List *list2)
Definition: list.c:515
List * p_multiassign_exprs
Definition: parse_node.h:196
static List * ExpandColumnRefStar(ParseState *pstate, ColumnRef *cref, bool make_target_entry)
struct A_Star A_Star
static List * ExpandIndirectionStar(ParseState *pstate, A_Indirection *ind, bool make_target_entry, ParseExprKind exprKind)
List * lappend(List *list, void *datum)
Definition: list.c:321
#define Assert(condition)
Definition: c.h:746
#define lfirst(lc)
Definition: pg_list.h:169
List * indirection
Definition: parsenodes.h:408
e
Definition: preproc-init.c:82
Definition: pg_list.h:50
List * fields
Definition: parsenodes.h:236

◆ transformTargetEntry()

TargetEntry* transformTargetEntry ( ParseState pstate,
Node node,
Node expr,
ParseExprKind  exprKind,
char *  colname,
bool  resjunk 
)

Definition at line 87 of file parse_target.c.

References EXPR_KIND_UPDATE_SOURCE, FigureColname(), IsA, makeTargetEntry(), ParseState::p_next_resno, and transformExpr().

Referenced by findTargetlistEntrySQL99(), and transformTargetList().

93 {
94  /* Transform the node if caller didn't do it already */
95  if (expr == NULL)
96  {
97  /*
98  * If it's a SetToDefault node and we should allow that, pass it
99  * through unmodified. (transformExpr will throw the appropriate
100  * error if we're disallowing it.)
101  */
102  if (exprKind == EXPR_KIND_UPDATE_SOURCE && IsA(node, SetToDefault))
103  expr = node;
104  else
105  expr = transformExpr(pstate, node, exprKind);
106  }
107 
108  if (colname == NULL && !resjunk)
109  {
110  /*
111  * Generate a suitable column name for a column without any explicit
112  * 'AS ColumnName' clause.
113  */
114  colname = FigureColname(node);
115  }
116 
117  return makeTargetEntry((Expr *) expr,
118  (AttrNumber) pstate->p_next_resno++,
119  colname,
120  resjunk);
121 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:579
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:145
char * FigureColname(Node *node)
int p_next_resno
Definition: parse_node.h:195
TargetEntry * makeTargetEntry(Expr *expr, AttrNumber resno, char *resname, bool resjunk)
Definition: makefuncs.c:238
int16 AttrNumber
Definition: attnum.h:21

◆ transformTargetList()

List* transformTargetList ( ParseState pstate,
List targetlist,
ParseExprKind  exprKind 
)

Definition at line 133 of file parse_target.c.

References Assert, ExpandColumnRefStar(), ExpandIndirectionStar(), EXPR_KIND_UPDATE_SOURCE, ColumnRef::fields, A_Indirection::indirection, IsA, lappend(), lfirst, list_concat(), llast, ResTarget::name, NIL, ParseState::p_multiassign_exprs, transformTargetEntry(), and ResTarget::val.

Referenced by transformReturningList(), transformSelectStmt(), and transformUpdateTargetList().

135 {
136  List *p_target = NIL;
137  bool expand_star;
138  ListCell *o_target;
139 
140  /* Shouldn't have any leftover multiassign items at start */
141  Assert(pstate->p_multiassign_exprs == NIL);
142 
143  /* Expand "something.*" in SELECT and RETURNING, but not UPDATE */
144  expand_star = (exprKind != EXPR_KIND_UPDATE_SOURCE);
145 
146  foreach(o_target, targetlist)
147  {
148  ResTarget *res = (ResTarget *) lfirst(o_target);
149 
150  /*
151  * Check for "something.*". Depending on the complexity of the
152  * "something", the star could appear as the last field in ColumnRef,
153  * or as the last indirection item in A_Indirection.
154  */
155  if (expand_star)
156  {
157  if (IsA(res->val, ColumnRef))
158  {
159  ColumnRef *cref = (ColumnRef *) res->val;
160 
161  if (IsA(llast(cref->fields), A_Star))
162  {
163  /* It is something.*, expand into multiple items */
164  p_target = list_concat(p_target,
165  ExpandColumnRefStar(pstate,
166  cref,
167  true));
168  continue;
169  }
170  }
171  else if (IsA(res->val, A_Indirection))
172  {
173  A_Indirection *ind = (A_Indirection *) res->val;
174 
175  if (IsA(llast(ind->indirection), A_Star))
176  {
177  /* It is something.*, expand into multiple items */
178  p_target = list_concat(p_target,
179  ExpandIndirectionStar(pstate,
180  ind,
181  true,
182  exprKind));
183  continue;
184  }
185  }
186  }
187 
188  /*
189  * Not "something.*", or we want to treat that as a plain whole-row
190  * variable, so transform as a single expression
191  */
192  p_target = lappend(p_target,
193  transformTargetEntry(pstate,
194  res->val,
195  NULL,
196  exprKind,
197  res->name,
198  false));
199  }
200 
201  /*
202  * If any multiassign resjunk items were created, attach them to the end
203  * of the targetlist. This should only happen in an UPDATE tlist. We
204  * don't need to worry about numbering of these items; transformUpdateStmt
205  * will set their resnos.
206  */
207  if (pstate->p_multiassign_exprs)
208  {
209  Assert(exprKind == EXPR_KIND_UPDATE_SOURCE);
210  p_target = list_concat(p_target, pstate->p_multiassign_exprs);
211  pstate->p_multiassign_exprs = NIL;
212  }
213 
214  return p_target;
215 }
#define NIL
Definition: pg_list.h:65
#define IsA(nodeptr, _type_)
Definition: nodes.h:579
Node * val
Definition: parsenodes.h:444
char * name
Definition: parsenodes.h:442
#define llast(l)
Definition: pg_list.h:194
List * list_concat(List *list1, const List *list2)
Definition: list.c:515
List * p_multiassign_exprs
Definition: parse_node.h:196
static List * ExpandColumnRefStar(ParseState *pstate, ColumnRef *cref, bool make_target_entry)
struct A_Star A_Star
static List * ExpandIndirectionStar(ParseState *pstate, A_Indirection *ind, bool make_target_entry, ParseExprKind exprKind)
List * lappend(List *list, void *datum)
Definition: list.c:321
#define Assert(condition)
Definition: c.h:746
#define lfirst(lc)
Definition: pg_list.h:169
List * indirection
Definition: parsenodes.h:408
TargetEntry * transformTargetEntry(ParseState *pstate, Node *node, Node *expr, ParseExprKind exprKind, char *colname, bool resjunk)
Definition: parse_target.c:87
Definition: pg_list.h:50
List * fields
Definition: parsenodes.h:236

◆ updateTargetListEntry()

void updateTargetListEntry ( ParseState pstate,
TargetEntry tle,
char *  colname,
int  attrno,
List indirection,
int  location 
)

Definition at line 616 of file parse_target.c.

References TargetEntry::expr, EXPR_KIND_UPDATE_TARGET, TargetEntry::resname, TargetEntry::resno, and transformAssignedExpr().

Referenced by transformUpdateTargetList().

622 {
623  /* Fix up expression as needed */
624  tle->expr = transformAssignedExpr(pstate,
625  tle->expr,
627  colname,
628  attrno,
629  indirection,
630  location);
631 
632  /*
633  * Set the resno to identify the target column --- the rewriter and
634  * planner depend on this. We also set the resname to identify the target
635  * column, but this is only for debugging purposes; it should not be
636  * relied on. (In particular, it might be out of date in a stored rule.)
637  */
638  tle->resno = (AttrNumber) attrno;
639  tle->resname = colname;
640 }
Expr * transformAssignedExpr(ParseState *pstate, Expr *expr, ParseExprKind exprKind, const char *colname, int attrno, List *indirection, int location)
Definition: parse_target.c:450
char * resname
Definition: primnodes.h:1412
AttrNumber resno
Definition: primnodes.h:1411
Expr * expr
Definition: primnodes.h:1410
int16 AttrNumber
Definition: attnum.h:21