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, RangeTblEntry *rte, 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 988 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().

989 {
990  *attrnos = NIL;
991 
992  if (cols == NIL)
993  {
994  /*
995  * Generate default column list for INSERT.
996  */
997  int numcol = RelationGetNumberOfAttributes(pstate->p_target_relation);
998 
999  int i;
1000 
1001  for (i = 0; i < numcol; i++)
1002  {
1003  ResTarget *col;
1004  Form_pg_attribute attr;
1005 
1006  attr = TupleDescAttr(pstate->p_target_relation->rd_att, i);
1007 
1008  if (attr->attisdropped)
1009  continue;
1010 
1011  col = makeNode(ResTarget);
1012  col->name = pstrdup(NameStr(attr->attname));
1013  col->indirection = NIL;
1014  col->val = NULL;
1015  col->location = -1;
1016  cols = lappend(cols, col);
1017  *attrnos = lappend_int(*attrnos, i + 1);
1018  }
1019  }
1020  else
1021  {
1022  /*
1023  * Do initial validation of user-supplied INSERT column list.
1024  */
1025  Bitmapset *wholecols = NULL;
1026  Bitmapset *partialcols = NULL;
1027  ListCell *tl;
1028 
1029  foreach(tl, cols)
1030  {
1031  ResTarget *col = (ResTarget *) lfirst(tl);
1032  char *name = col->name;
1033  int attrno;
1034 
1035  /* Lookup column name, ereport on failure */
1036  attrno = attnameAttNum(pstate->p_target_relation, name, false);
1037  if (attrno == InvalidAttrNumber)
1038  ereport(ERROR,
1039  (errcode(ERRCODE_UNDEFINED_COLUMN),
1040  errmsg("column \"%s\" of relation \"%s\" does not exist",
1041  name,
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  if (col->indirection == NIL)
1050  {
1051  /* whole column; must not have any other assignment */
1052  if (bms_is_member(attrno, wholecols) ||
1053  bms_is_member(attrno, partialcols))
1054  ereport(ERROR,
1055  (errcode(ERRCODE_DUPLICATE_COLUMN),
1056  errmsg("column \"%s\" specified more than once",
1057  name),
1058  parser_errposition(pstate, col->location)));
1059  wholecols = bms_add_member(wholecols, attrno);
1060  }
1061  else
1062  {
1063  /* partial column; must not have any whole assignment */
1064  if (bms_is_member(attrno, wholecols))
1065  ereport(ERROR,
1066  (errcode(ERRCODE_DUPLICATE_COLUMN),
1067  errmsg("column \"%s\" specified more than once",
1068  name),
1069  parser_errposition(pstate, col->location)));
1070  partialcols = bms_add_member(partialcols, attrno);
1071  }
1072 
1073  *attrnos = lappend_int(*attrnos, attrno);
1074  }
1075  }
1076 
1077  return cols;
1078 }
List * indirection
Definition: parsenodes.h:441
#define NIL
Definition: pg_list.h:65
Node * val
Definition: parsenodes.h:442
char * name
Definition: parsenodes.h:440
#define RelationGetNumberOfAttributes(relation)
Definition: rel.h:429
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
char * pstrdup(const char *in)
Definition: mcxt.c:1186
int errcode(int sqlerrcode)
Definition: elog.c:608
int location
Definition: parsenodes.h:443
#define ERROR
Definition: elog.h:43
#define RelationGetRelationName(relation)
Definition: rel.h:457
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:200
#define ereport(elevel, rest)
Definition: elog.h:141
List * lappend_int(List *list, int datum)
Definition: list.c:340
List * lappend(List *list, void *datum)
Definition: list.c:322
TupleDesc rd_att
Definition: rel.h:84
#define makeNode(_type_)
Definition: nodes.h:573
int attnameAttNum(Relation rd, const char *attname, bool sysColOK)
#define lfirst(lc)
Definition: pg_list.h:190
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:521
#define InvalidAttrNumber
Definition: attnum.h:23
int errmsg(const char *fmt,...)
Definition: elog.c:822
Relation p_target_relation
Definition: parse_node.h:187
int i
#define NameStr(name)
Definition: c.h:610
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 1263 of file parse_target.c.

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

Referenced by ExpandColumnRefStar().

1264 {
1265  List *target = NIL;
1266  bool found_table = false;
1267  ListCell *l;
1268 
1269  foreach(l, pstate->p_namespace)
1270  {
1271  ParseNamespaceItem *nsitem = (ParseNamespaceItem *) lfirst(l);
1272  RangeTblEntry *rte = nsitem->p_rte;
1273 
1274  /* Ignore table-only items */
1275  if (!nsitem->p_cols_visible)
1276  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  found_table = true;
1281 
1282  target = list_concat(target,
1283  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  if (!found_table)
1297  ereport(ERROR,
1298  (errcode(ERRCODE_SYNTAX_ERROR),
1299  errmsg("SELECT * with no tables specified is not valid"),
1300  parser_errposition(pstate, location)));
1301 
1302  return target;
1303 }
#define NIL
Definition: pg_list.h:65
List * list_concat(List *list1, const List *list2)
Definition: list.c:516
int errcode(int sqlerrcode)
Definition: elog.c:608
RangeTblEntry * p_rte
Definition: parse_node.h:251
#define ERROR
Definition: elog.h:43
List * p_namespace
Definition: parse_node.h:181
List * expandRelAttrs(ParseState *pstate, RangeTblEntry *rte, int rtindex, int sublevels_up, int location)
#define ereport(elevel, rest)
Definition: elog.h:141
#define Assert(condition)
Definition: c.h:733
#define lfirst(lc)
Definition: pg_list.h:190
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110
int RTERangeTablePosn(ParseState *pstate, RangeTblEntry *rte, int *sublevels_up)
int errmsg(const char *fmt,...)
Definition: elog.c:822
Definition: pg_list.h:50

◆ ExpandColumnRefStar()

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

Definition at line 1093 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, parser_errposition(), refnameRangeTblEntry(), relname, and strVal.

Referenced by transformExpressionList(), and transformTargetList().

1095 {
1096  List *fields = cref->fields;
1097  int numnames = list_length(fields);
1098 
1099  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  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  char *nspname = NULL;
1129  char *relname = NULL;
1130  RangeTblEntry *rte = NULL;
1131  int levels_up;
1132  enum
1133  {
1134  CRSERR_NO_RTE,
1135  CRSERR_WRONG_DB,
1136  CRSERR_TOO_MANY
1137  } 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  if (pstate->p_pre_columnref_hook != NULL)
1144  {
1145  Node *node;
1146 
1147  node = pstate->p_pre_columnref_hook(pstate, cref);
1148  if (node != NULL)
1149  return ExpandRowReference(pstate, node, make_target_entry);
1150  }
1151 
1152  switch (numnames)
1153  {
1154  case 2:
1155  relname = strVal(linitial(fields));
1156  rte = refnameRangeTblEntry(pstate, nspname, relname,
1157  cref->location,
1158  &levels_up);
1159  break;
1160  case 3:
1161  nspname = strVal(linitial(fields));
1162  relname = strVal(lsecond(fields));
1163  rte = refnameRangeTblEntry(pstate, nspname, relname,
1164  cref->location,
1165  &levels_up);
1166  break;
1167  case 4:
1168  {
1169  char *catname = strVal(linitial(fields));
1170 
1171  /*
1172  * We check the catalog name and then ignore it.
1173  */
1174  if (strcmp(catname, get_database_name(MyDatabaseId)) != 0)
1175  {
1176  crserr = CRSERR_WRONG_DB;
1177  break;
1178  }
1179  nspname = strVal(lsecond(fields));
1180  relname = strVal(lthird(fields));
1181  rte = refnameRangeTblEntry(pstate, nspname, relname,
1182  cref->location,
1183  &levels_up);
1184  break;
1185  }
1186  default:
1187  crserr = CRSERR_TOO_MANY;
1188  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  if (pstate->p_post_columnref_hook != NULL)
1199  {
1200  Node *node;
1201 
1202  node = pstate->p_post_columnref_hook(pstate, cref,
1203  (Node *) rte);
1204  if (node != NULL)
1205  {
1206  if (rte != NULL)
1207  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  return ExpandRowReference(pstate, node, make_target_entry);
1213  }
1214  }
1215 
1216  /*
1217  * Throw error if no translation found.
1218  */
1219  if (rte == NULL)
1220  {
1221  switch (crserr)
1222  {
1223  case CRSERR_NO_RTE:
1224  errorMissingRTE(pstate, makeRangeVar(nspname, relname,
1225  cref->location));
1226  break;
1227  case CRSERR_WRONG_DB:
1228  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  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  return ExpandSingleTable(pstate, rte, cref->location, make_target_entry);
1248  }
1249 }
Definition: nodes.h:525
#define strVal(v)
Definition: value.h:54
static List * ExpandSingleTable(ParseState *pstate, RangeTblEntry *rte, int location, bool make_target_entry)
int errcode(int sqlerrcode)
Definition: elog.c:608
NameData relname
Definition: pg_class.h:35
RangeTblEntry * refnameRangeTblEntry(ParseState *pstate, const char *schemaname, const char *refname, int location, int *sublevels_up)
#define lsecond(l)
Definition: pg_list.h:200
PostParseColumnRefHook p_post_columnref_hook
Definition: parse_node.h:216
int location
Definition: parsenodes.h:236
static List * ExpandRowReference(ParseState *pstate, Node *expr, bool make_target_entry)
#define linitial(l)
Definition: pg_list.h:195
#define ERROR
Definition: elog.h:43
char * get_database_name(Oid dbid)
Definition: dbcommands.c:2131
void errorMissingRTE(ParseState *pstate, RangeVar *relation)
#define ereport(elevel, rest)
Definition: elog.h:141
char * NameListToString(List *names)
Definition: namespace.c:3094
Oid MyDatabaseId
Definition: globals.c:85
#define Assert(condition)
Definition: c.h:733
static int list_length(const List *l)
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:822
static List * ExpandAllTables(ParseState *pstate, int location)
#define lthird(l)
Definition: pg_list.h:205
PreParseColumnRefHook p_pre_columnref_hook
Definition: parse_node.h:215
Definition: pg_list.h:50
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition: makefuncs.c:420
List * fields
Definition: parsenodes.h:235

◆ ExpandIndirectionStar()

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

Definition at line 1317 of file parse_target.c.

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

Referenced by transformExpressionList(), and transformTargetList().

1319 {
1320  Node *expr;
1321 
1322  /* Strip off the '*' to create a reference to the rowtype object */
1323  ind = copyObject(ind);
1325  list_length(ind->indirection) - 1);
1326 
1327  /* And transform that */
1328  expr = transformExpr(pstate, (Node *) ind, exprKind);
1329 
1330  /* Expand the rowtype expression into individual fields */
1331  return ExpandRowReference(pstate, expr, make_target_entry);
1332 }
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:144
List * list_truncate(List *list, int new_size)
Definition: list.c:586
Definition: nodes.h:525
static List * ExpandRowReference(ParseState *pstate, Node *expr, bool make_target_entry)
List * indirection
Definition: parsenodes.h:406
static int list_length(const List *l)
Definition: pg_list.h:169
#define copyObject(obj)
Definition: nodes.h:641

◆ expandRecordVariable()

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

Definition at line 1488 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().

1489 {
1490  TupleDesc tupleDesc;
1491  int netlevelsup;
1492  RangeTblEntry *rte;
1494  Node *expr;
1495 
1496  /* Check my caller didn't mess up */
1497  Assert(IsA(var, Var));
1498  Assert(var->vartype == RECORDOID);
1499 
1500  netlevelsup = var->varlevelsup + levelsup;
1501  rte = GetRTEByRangeTablePosn(pstate, var->varno, netlevelsup);
1502  attnum = var->varattno;
1503 
1504  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  expandRTE(rte, var->varno, 0, var->location, false,
1514  &names, &vars);
1515 
1516  tupleDesc = CreateTemplateTupleDesc(list_length(vars));
1517  i = 1;
1518  forboth(lname, names, lvar, vars)
1519  {
1520  char *label = strVal(lfirst(lname));
1521  Node *varnode = (Node *) lfirst(lvar);
1522 
1523  TupleDescInitEntry(tupleDesc, i,
1524  label,
1525  exprType(varnode),
1526  exprTypmod(varnode),
1527  0);
1528  TupleDescInitEntryCollation(tupleDesc, i,
1529  exprCollation(varnode));
1530  i++;
1531  }
1532  Assert(lname == NULL && lvar == NULL); /* lists same length? */
1533 
1534  return tupleDesc;
1535  }
1536 
1537  expr = (Node *) var; /* default if we can't drill down */
1538 
1539  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  break;
1552  case RTE_SUBQUERY:
1553  {
1554  /* Subselect-in-FROM: examine sub-select's output expr */
1556  attnum);
1557 
1558  if (ste == NULL || ste->resjunk)
1559  elog(ERROR, "subquery %s does not have attribute %d",
1560  rte->eref->aliasname, attnum);
1561  expr = (Node *) ste->expr;
1562  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  MemSet(&mypstate, 0, sizeof(mypstate));
1572  mypstate.parentParseState = pstate;
1573  mypstate.p_rtable = rte->subquery->rtable;
1574  /* don't bother filling the rest of the fake pstate */
1575 
1576  return expandRecordVariable(&mypstate, (Var *) expr, 0);
1577  }
1578  /* else fall through to inspect the expression */
1579  }
1580  break;
1581  case RTE_JOIN:
1582  /* Join RTE --- recursively inspect the alias variable */
1583  Assert(attnum > 0 && attnum <= list_length(rte->joinaliasvars));
1584  expr = (Node *) list_nth(rte->joinaliasvars, attnum - 1);
1585  Assert(expr != NULL);
1586  /* We intentionally don't strip implicit coercions here */
1587  if (IsA(expr, Var))
1588  return expandRecordVariable(pstate, (Var *) expr, netlevelsup);
1589  /* else fall through to inspect the expression */
1590  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  break;
1598  case RTE_TABLEFUNC:
1599 
1600  /*
1601  * Table function cannot have columns with RECORD type.
1602  */
1603  break;
1604  case RTE_CTE:
1605  /* CTE reference: examine subquery's output expr */
1606  if (!rte->self_reference)
1607  {
1608  CommonTableExpr *cte = GetCTEForRTE(pstate, rte, netlevelsup);
1609  TargetEntry *ste;
1610 
1611  ste = get_tle_by_resno(GetCTETargetList(cte), attnum);
1612  if (ste == NULL || ste->resjunk)
1613  elog(ERROR, "subquery %s does not have attribute %d",
1614  rte->eref->aliasname, attnum);
1615  expr = (Node *) ste->expr;
1616  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  MemSet(&mypstate, 0, sizeof(mypstate));
1628  /* this loop must work, since GetCTEForRTE did */
1629  for (levelsup = 0;
1630  levelsup < rte->ctelevelsup + netlevelsup;
1631  levelsup++)
1632  pstate = pstate->parentParseState;
1633  mypstate.parentParseState = pstate;
1634  mypstate.p_rtable = ((Query *) cte->ctequery)->rtable;
1635  /* don't bother filling the rest of the fake pstate */
1636 
1637  return expandRecordVariable(&mypstate, (Var *) expr, 0);
1638  }
1639  /* else fall through to inspect the expression */
1640  }
1641  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  return get_expr_result_tupdesc(expr, false);
1649 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
List * joinaliasvars
Definition: parsenodes.h:1030
Index varlevelsup
Definition: primnodes.h:177
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:419
TupleDesc CreateTemplateTupleDesc(int natts)
Definition: tupdesc.c:44
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:275
CommonTableExpr * GetCTEForRTE(ParseState *pstate, RangeTblEntry *rte, int rtelevelsup)
Definition: nodes.h:525
#define strVal(v)
Definition: value.h:54
#define MemSet(start, val, len)
Definition: c.h:956
AttrNumber varattno
Definition: primnodes.h:172
Definition: primnodes.h:167
List * targetList
Definition: parsenodes.h:140
bool resjunk
Definition: primnodes.h:1400
List * rtable
Definition: parsenodes.h:137
#define ERROR
Definition: elog.h:43
TupleDesc get_expr_result_tupdesc(Node *expr, bool noError)
Definition: funcapi.c:429
static void * list_nth(const List *list, int n)
Definition: pg_list.h:277
Oid vartype
Definition: primnodes.h:174
void TupleDescInitEntryCollation(TupleDesc desc, AttrNumber attributeNumber, Oid collationid)
Definition: tupdesc.c:769
int location
Definition: primnodes.h:182
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:170
void expandRTE(RangeTblEntry *rte, int rtindex, int sublevels_up, int location, bool include_dropped, List **colnames, List **colvars)
struct ParseState * parentParseState
Definition: parse_node.h:175
bool self_reference
Definition: parsenodes.h:1058
static char * label
Definition: pg_basebackup.c:86
RangeTblEntry * GetRTEByRangeTablePosn(ParseState *pstate, int varno, int sublevels_up)
unsigned int Index
Definition: c.h:476
int16 attnum
Definition: pg_attribute.h:79
#define Assert(condition)
Definition: c.h:733
#define lfirst(lc)
Definition: pg_list.h:190
char * aliasname
Definition: primnodes.h:42
Expr * expr
Definition: primnodes.h:1393
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
static int list_length(const List *l)
Definition: pg_list.h:169
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:719
Index ctelevelsup
Definition: parsenodes.h:1057
#define InvalidAttrNumber
Definition: attnum.h:23
RTEKind rtekind
Definition: parsenodes.h:974
Query * subquery
Definition: parsenodes.h:1009
#define elog(elevel,...)
Definition: elog.h:228
int i
TargetEntry * get_tle_by_resno(List *tlist, AttrNumber resno)
Alias * eref
Definition: parsenodes.h:1092
Definition: regcomp.c:224
Definition: pg_list.h:50
#define GetCTETargetList(cte)
Definition: parsenodes.h:1444
int16 AttrNumber
Definition: attnum.h:21
List * p_rtable
Definition: parse_node.h:177

◆ ExpandRowReference()

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

Definition at line 1393 of file parse_target.c.

References FieldSelect::arg, Assert, copyObject, expandRecordVariable(), ExpandSingleTable(), FieldSelect::fieldnum, get_expr_result_tupdesc(), GetRTEByRangeTablePosn(), 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().

1395 {
1396  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  if (IsA(expr, Var) &&
1411  ((Var *) expr)->varattno == InvalidAttrNumber)
1412  {
1413  Var *var = (Var *) expr;
1414  RangeTblEntry *rte;
1415 
1416  rte = GetRTEByRangeTablePosn(pstate, var->varno, var->varlevelsup);
1417  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  if (IsA(expr, Var) &&
1434  ((Var *) expr)->vartype == RECORDOID)
1435  tupleDesc = expandRecordVariable(pstate, (Var *) expr, 0);
1436  else
1437  tupleDesc = get_expr_result_tupdesc(expr, false);
1438  Assert(tupleDesc);
1439 
1440  /* Generate a list of references to the individual fields */
1441  numAttrs = tupleDesc->natts;
1442  for (i = 0; i < numAttrs; i++)
1443  {
1444  Form_pg_attribute att = TupleDescAttr(tupleDesc, i);
1445  FieldSelect *fselect;
1446 
1447  if (att->attisdropped)
1448  continue;
1449 
1450  fselect = makeNode(FieldSelect);
1451  fselect->arg = (Expr *) copyObject(expr);
1452  fselect->fieldnum = i + 1;
1453  fselect->resulttype = att->atttypid;
1454  fselect->resulttypmod = att->atttypmod;
1455  /* save attribute's collation for parse_collate.c */
1456  fselect->resultcollid = att->attcollation;
1457 
1458  if (make_target_entry)
1459  {
1460  /* add TargetEntry decoration */
1461  TargetEntry *te;
1462 
1463  te = makeTargetEntry((Expr *) fselect,
1464  (AttrNumber) pstate->p_next_resno++,
1465  pstrdup(NameStr(att->attname)),
1466  false);
1467  result = lappend(result, te);
1468  }
1469  else
1470  result = lappend(result, fselect);
1471  }
1472 
1473  return result;
1474 }
#define NIL
Definition: pg_list.h:65
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
Index varlevelsup
Definition: primnodes.h:177
Oid resulttype
Definition: primnodes.h:750
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
char * pstrdup(const char *in)
Definition: mcxt.c:1186
static List * ExpandSingleTable(ParseState *pstate, RangeTblEntry *rte, int location, bool make_target_entry)
Expr * arg
Definition: primnodes.h:748
Definition: primnodes.h:167
TupleDesc get_expr_result_tupdesc(Node *expr, bool noError)
Definition: funcapi.c:429
Oid resultcollid
Definition: primnodes.h:753
int location
Definition: primnodes.h:182
int p_next_resno
Definition: parse_node.h:192
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:200
TupleDesc expandRecordVariable(ParseState *pstate, Var *var, int levelsup)
TargetEntry * makeTargetEntry(Expr *expr, AttrNumber resno, char *resname, bool resjunk)
Definition: makefuncs.c:236
List * lappend(List *list, void *datum)
Definition: list.c:322
Index varno
Definition: primnodes.h:170
RangeTblEntry * GetRTEByRangeTablePosn(ParseState *pstate, int varno, int sublevels_up)
#define makeNode(_type_)
Definition: nodes.h:573
#define Assert(condition)
Definition: c.h:733
#define InvalidAttrNumber
Definition: attnum.h:23
int i
#define NameStr(name)
Definition: c.h:610
#define copyObject(obj)
Definition: nodes.h:641
Definition: pg_list.h:50
int16 AttrNumber
Definition: attnum.h:21
int32 resulttypmod
Definition: primnodes.h:752
AttrNumber fieldnum
Definition: primnodes.h:749

◆ ExpandSingleTable()

static List * ExpandSingleTable ( ParseState pstate,
RangeTblEntry rte,
int  location,
bool  make_target_entry 
)
static

Definition at line 1344 of file parse_target.c.

References ACL_SELECT, expandRelAttrs(), expandRTE(), lfirst, markVarForSelectPriv(), RangeTblEntry::requiredPerms, and RTERangeTablePosn().

Referenced by ExpandColumnRefStar(), and ExpandRowReference().

1346 {
1347  int sublevels_up;
1348  int rtindex;
1349 
1350  rtindex = RTERangeTablePosn(pstate, rte, &sublevels_up);
1351 
1352  if (make_target_entry)
1353  {
1354  /* expandRelAttrs handles permissions marking */
1355  return expandRelAttrs(pstate, rte, rtindex, sublevels_up,
1356  location);
1357  }
1358  else
1359  {
1360  List *vars;
1361  ListCell *l;
1362 
1363  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  rte->requiredPerms |= ACL_SELECT;
1372 
1373  /* Require read access to each column */
1374  foreach(l, vars)
1375  {
1376  Var *var = (Var *) lfirst(l);
1377 
1378  markVarForSelectPriv(pstate, var, rte);
1379  }
1380 
1381  return vars;
1382  }
1383 }
void markVarForSelectPriv(ParseState *pstate, Var *var, RangeTblEntry *rte)
AclMode requiredPerms
Definition: parsenodes.h:1096
Definition: primnodes.h:167
List * expandRelAttrs(ParseState *pstate, RangeTblEntry *rte, int rtindex, int sublevels_up, int location)
void expandRTE(RangeTblEntry *rte, int rtindex, int sublevels_up, int location, bool include_dropped, List **colnames, List **colvars)
#define ACL_SELECT
Definition: parsenodes.h:75
#define lfirst(lc)
Definition: pg_list.h:190
int RTERangeTablePosn(ParseState *pstate, RangeTblEntry *rte, int *sublevels_up)
Definition: regcomp.c:224
Definition: pg_list.h:50

◆ FigureColname()

char* FigureColname ( Node node)

Definition at line 1662 of file parse_target.c.

References FigureColnameInternal(), and name.

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

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

◆ FigureColnameInternal()

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

Definition at line 1701 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().

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

◆ FigureIndexColname()

char* FigureIndexColname ( Node node)

Definition at line 1681 of file parse_target.c.

References FigureColnameInternal(), and name.

Referenced by transformIndexStmt().

1682 {
1683  char *name = NULL;
1684 
1685  (void) FigureColnameInternal(node, &name);
1686  return name;
1687 }
static int FigureColnameInternal(Node *node, char **name)
const char * name
Definition: encode.c:521

◆ markTargetListOrigin()

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

Definition at line 352 of file parse_target.c.

References Alias::aliasname, Assert, attnum, elog, RangeTblEntry::eref, ERROR, get_tle_by_resno(), GetCTEForRTE(), GetCTETargetList, GetRTEByRangeTablePosn(), InvalidAttrNumber, IsA, RangeTblEntry::joinaliasvars, list_length(), list_nth(), 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().

354 {
355  int netlevelsup;
356  RangeTblEntry *rte;
358 
359  if (var == NULL || !IsA(var, Var))
360  return;
361  netlevelsup = var->varlevelsup + levelsup;
362  rte = GetRTEByRangeTablePosn(pstate, var->varno, netlevelsup);
363  attnum = var->varattno;
364 
365  switch (rte->rtekind)
366  {
367  case RTE_RELATION:
368  /* It's a table or view, report it */
369  tle->resorigtbl = rte->relid;
370  tle->resorigcol = attnum;
371  break;
372  case RTE_SUBQUERY:
373  /* Subselect-in-FROM: copy up from the subselect */
374  if (attnum != InvalidAttrNumber)
375  {
377  attnum);
378 
379  if (ste == NULL || ste->resjunk)
380  elog(ERROR, "subquery %s does not have attribute %d",
381  rte->eref->aliasname, attnum);
382  tle->resorigtbl = ste->resorigtbl;
383  tle->resorigcol = ste->resorigcol;
384  }
385  break;
386  case RTE_JOIN:
387  /* Join RTE --- recursively inspect the alias variable */
388  if (attnum != InvalidAttrNumber)
389  {
390  Var *aliasvar;
391 
392  Assert(attnum > 0 && attnum <= list_length(rte->joinaliasvars));
393  aliasvar = (Var *) list_nth(rte->joinaliasvars, attnum - 1);
394  /* We intentionally don't strip implicit coercions here */
395  markTargetListOrigin(pstate, tle, aliasvar, netlevelsup);
396  }
397  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  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  if (attnum != InvalidAttrNumber && !rte->self_reference)
416  {
417  CommonTableExpr *cte = GetCTEForRTE(pstate, rte, netlevelsup);
418  TargetEntry *ste;
419 
420  ste = get_tle_by_resno(GetCTETargetList(cte), attnum);
421  if (ste == NULL || ste->resjunk)
422  elog(ERROR, "subquery %s does not have attribute %d",
423  rte->eref->aliasname, attnum);
424  tle->resorigtbl = ste->resorigtbl;
425  tle->resorigcol = ste->resorigcol;
426  }
427  break;
428  }
429 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
List * joinaliasvars
Definition: parsenodes.h:1030
Index varlevelsup
Definition: primnodes.h:177
CommonTableExpr * GetCTEForRTE(ParseState *pstate, RangeTblEntry *rte, int rtelevelsup)
Oid resorigtbl
Definition: primnodes.h:1398
AttrNumber varattno
Definition: primnodes.h:172
Definition: primnodes.h:167
List * targetList
Definition: parsenodes.h:140
bool resjunk
Definition: primnodes.h:1400
#define ERROR
Definition: elog.h:43
static void * list_nth(const List *list, int n)
Definition: pg_list.h:277
Index varno
Definition: primnodes.h:170
bool self_reference
Definition: parsenodes.h:1058
RangeTblEntry * GetRTEByRangeTablePosn(ParseState *pstate, int varno, int sublevels_up)
int16 attnum
Definition: pg_attribute.h:79
#define Assert(condition)
Definition: c.h:733
char * aliasname
Definition: primnodes.h:42
static int list_length(const List *l)
Definition: pg_list.h:169
#define InvalidAttrNumber
Definition: attnum.h:23
RTEKind rtekind
Definition: parsenodes.h:974
static void markTargetListOrigin(ParseState *pstate, TargetEntry *tle, Var *var, int levelsup)
Definition: parse_target.c:352
AttrNumber resorigcol
Definition: primnodes.h:1399
Query * subquery
Definition: parsenodes.h:1009
#define elog(elevel,...)
Definition: elog.h:228
TargetEntry * get_tle_by_resno(List *tlist, AttrNumber resno)
Alias * eref
Definition: parsenodes.h:1092
#define GetCTETargetList(cte)
Definition: parsenodes.h:1444
int16 AttrNumber
Definition: attnum.h:21

◆ markTargetListOrigins()

void markTargetListOrigins ( ParseState pstate,
List targetlist 
)

Definition at line 330 of file parse_target.c.

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

Referenced by transformReturningList(), and transformSelectStmt().

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

◆ resolveTargetListUnknowns()

void resolveTargetListUnknowns ( ParseState pstate,
List targetlist 
)

Definition at line 300 of file parse_target.c.

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

Referenced by transformReturningList(), and transformSelectStmt().

301 {
302  ListCell *l;
303 
304  foreach(l, targetlist)
305  {
306  TargetEntry *tle = (TargetEntry *) lfirst(l);
307  Oid restype = exprType((Node *) tle->expr);
308 
309  if (restype == UNKNOWNOID)
310  {
311  tle->expr = (Expr *) coerce_type(pstate, (Node *) tle->expr,
312  restype, TEXTOID, -1,
315  -1);
316  }
317  }
318 }
Node * coerce_type(ParseState *pstate, Node *node, Oid inputTypeId, Oid targetTypeId, int32 targetTypeMod, CoercionContext ccontext, CoercionForm cformat, int location)
Definition: parse_coerce.c:156
Definition: nodes.h:525
unsigned int Oid
Definition: postgres_ext.h:31
#define lfirst(lc)
Definition: pg_list.h:190
Expr * expr
Definition: primnodes.h:1393
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 457 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(), make_var(), makeNullConst(), ParseState::p_expr_kind, ParseState::p_is_insert, ParseState::p_target_rangetblentry, ParseState::p_target_relation, parser_errposition(), RelationData::rd_att, transformAssignmentIndirection(), TupleDescAttr, SetToDefault::typeId, and SetToDefault::typeMod.

Referenced by transformInsertRow(), and updateTargetListEntry().

464 {
465  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  sv_expr_kind = pstate->p_expr_kind;
479  pstate->p_expr_kind = exprKind;
480 
481  Assert(rd != NULL);
482  if (attrno <= 0)
483  ereport(ERROR,
484  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
485  errmsg("cannot assign to system column \"%s\"",
486  colname),
487  parser_errposition(pstate, location)));
488  attrtype = attnumTypeId(rd, attrno);
489  attrtypmod = TupleDescAttr(rd->rd_att, attrno - 1)->atttypmod;
490  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  if (expr && IsA(expr, SetToDefault))
502  {
503  SetToDefault *def = (SetToDefault *) expr;
504 
505  def->typeId = attrtype;
506  def->typeMod = attrtypmod;
507  def->collation = attrcollation;
508  if (indirection)
509  {
510  if (IsA(linitial(indirection), A_Indices))
511  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  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  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  if (indirection)
533  {
534  Node *colVar;
535 
536  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  colVar = (Node *) makeNullConst(attrtype, attrtypmod,
544  attrcollation);
545  }
546  else
547  {
548  /*
549  * Build a Var for the column to be updated.
550  */
551  colVar = (Node *) make_var(pstate,
552  pstate->p_target_rangetblentry,
553  attrno,
554  location);
555  }
556 
557  expr = (Expr *)
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  Node *orig_expr = (Node *) expr;
577 
578  expr = (Expr *)
579  coerce_to_target_type(pstate,
580  orig_expr, type_id,
581  attrtype, attrtypmod,
584  -1);
585  if (expr == NULL)
586  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  pstate->p_expr_kind = sv_expr_kind;
598 
599  return expr;
600 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
int errhint(const char *fmt,...)
Definition: elog.c:1071
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1191
#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:680
Definition: nodes.h:525
int errcode(int sqlerrcode)
Definition: elog.c:608
char * format_type_be(Oid type_oid)
Definition: format_type.c:326
unsigned int Oid
Definition: postgres_ext.h:31
ParseExprKind
Definition: parse_node.h:33
signed int int32
Definition: c.h:347
Const * makeNullConst(Oid consttype, int32 consttypmod, Oid constcollid)
Definition: makefuncs.c:335
#define linitial(l)
Definition: pg_list.h:195
#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:78
int32 typeMod
Definition: primnodes.h:1282
Oid attnumTypeId(Relation rd, int attid)
static ListCell * list_head(const List *l)
Definition: pg_list.h:125
#define ereport(elevel, rest)
Definition: elog.h:141
RangeTblEntry * p_target_rangetblentry
Definition: parse_node.h:188
ParseExprKind p_expr_kind
Definition: parse_node.h:191
TupleDesc rd_att
Definition: rel.h:84
Var * make_var(ParseState *pstate, RangeTblEntry *rte, int attrno, int location)
Definition: parse_node.c:188
#define Assert(condition)
Definition: c.h:733
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:822
Relation p_target_relation
Definition: parse_node.h:187
bool p_is_insert
Definition: parse_node.h:189

◆ 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 680 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().

691 {
692  Node *result;
693  List *subscripts = NIL;
694  bool isSlice = false;
695  ListCell *i;
696 
697  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  */
707 
708  ctest->typeId = targetTypeId;
709  ctest->typeMod = targetTypMod;
710  ctest->collation = targetCollation;
711  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  for_each_cell(i, indirection, indirection_cell)
720  {
721  Node *n = lfirst(i);
722 
723  if (IsA(n, A_Indices))
724  {
725  subscripts = lappend(subscripts, n);
726  if (((A_Indices *) n)->is_slice)
727  isSlice = true;
728  }
729  else if (IsA(n, A_Star))
730  {
731  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;
743  Oid fieldTypeId;
744  int32 fieldTypMod;
745  Oid fieldCollation;
746 
747  Assert(IsA(n, String));
748 
749  /* process subscripts before this field selection */
750  if (subscripts)
751  {
752  /* recurse, and then return because we're done */
753  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  baseTypeMod = targetTypMod;
774  baseTypeId = getBaseTypeAndTypmod(targetTypeId, &baseTypeMod);
775 
776  typrelid = typeidTypeRelid(baseTypeId);
777  if (!typrelid)
778  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  attnum = get_attnum(typrelid, strVal(n));
786  if (attnum == InvalidAttrNumber)
787  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  if (attnum < 0)
794  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  get_atttypetypmodcoll(typrelid, attnum,
801  &fieldTypeId, &fieldTypMod, &fieldCollation);
802 
803  /* recurse to create appropriate RHS for field assign */
804  rhs = transformAssignmentIndirection(pstate,
805  NULL,
806  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  fstore = makeNode(FieldStore);
818  fstore->arg = (Expr *) basenode;
819  fstore->newvals = list_make1(rhs);
820  fstore->fieldnums = list_make1_int(attnum);
821  fstore->resulttype = baseTypeId;
822 
823  /* If target is a domain, apply constraints */
824  if (baseTypeId != targetTypeId)
825  return coerce_to_domain((Node *) fstore,
826  baseTypeId, baseTypeMod,
827  targetTypeId,
830  location,
831  false);
832 
833  return (Node *) fstore;
834  }
835  }
836 
837  /* process trailing subscripts, if any */
838  if (subscripts)
839  {
840  /* recurse, and then return because we're done */
841  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  result = coerce_to_target_type(pstate,
858  rhs, exprType(rhs),
859  targetTypeId, targetTypMod,
862  -1);
863  if (result == NULL)
864  {
865  if (targetIsSubscripting)
866  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  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  return result;
888 }
#define NIL
Definition: pg_list.h:65
Oid getBaseTypeAndTypmod(Oid typid, int32 *typmod)
Definition: lsyscache.c:2316
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
Expr * arg
Definition: primnodes.h:777
int errhint(const char *fmt,...)
Definition: elog.c:1071
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:321
#define for_each_cell(cell, lst, initcell)
Definition: pg_list.h:390
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:680
Definition: nodes.h:525
#define strVal(v)
Definition: value.h:54
int errcode(int sqlerrcode)
Definition: elog.c:608
char * format_type_be(Oid type_oid)
Definition: format_type.c:326
Oid typeidTypeRelid(Oid type_id)
Definition: parse_type.c:666
unsigned int Oid
Definition: postgres_ext.h:31
int32 typeMod
Definition: primnodes.h:959
signed int int32
Definition: c.h:347
#define list_make1(x1)
Definition: pg_list.h:227
#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:78
Node * coerce_to_domain(Node *arg, Oid baseTypeId, int32 baseTypeMod, Oid typeId, CoercionContext ccontext, CoercionForm cformat, int location, bool hideInputCoercion)
Definition: parse_coerce.c:663
AttrNumber get_attnum(Oid relid, const char *attname)
Definition: lsyscache.c:806
Oid resulttype
Definition: primnodes.h:780
#define list_make1_int(x1)
Definition: pg_list.h:238
#define ereport(elevel, rest)
Definition: elog.h:141
List * newvals
Definition: primnodes.h:778
List * lappend(List *list, void *datum)
Definition: list.c:322
int16 attnum
Definition: pg_attribute.h:79
#define makeNode(_type_)
Definition: nodes.h:573
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:894
#define Assert(condition)
Definition: c.h:733
#define lfirst(lc)
Definition: pg_list.h:190
void get_atttypetypmodcoll(Oid relid, AttrNumber attnum, Oid *typid, int32 *typmod, Oid *collid)
Definition: lsyscache.c:891
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:822
List * fieldnums
Definition: primnodes.h:779
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 894 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().

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  containerType = targetTypeId;
918  containerTypMod = targetTypMod;
919  elementTypeId = transformContainerType(&containerType, &containerTypMod);
920 
921  /* Identify type that RHS must provide */
922  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  if (containerType == targetTypeId)
930  collationNeeded = targetCollation;
931  else
932  collationNeeded = get_typcollation(containerType);
933 
934  /* recurse to create appropriate RHS for container assign */
935  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  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  if (containerType != targetTypeId)
958  {
959  Oid resulttype = exprType(result);
960 
961  result = coerce_to_target_type(pstate,
962  result, resulttype,
963  targetTypeId, targetTypMod,
966  -1);
967  /* can fail if we had int2vector/oidvector, but not for true domains */
968  if (result == NULL)
969  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  return result;
978 }
#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:680
Definition: nodes.h:525
int errcode(int sqlerrcode)
Definition: elog.c:608
char * format_type_be(Oid type_oid)
Definition: format_type.c:326
unsigned int Oid
Definition: postgres_ext.h:31
signed int int32
Definition: c.h:347
#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:78
#define ereport(elevel, rest)
Definition: elog.h:141
SubscriptingRef * transformContainerSubscripts(ParseState *pstate, Node *containerBase, Oid containerType, Oid elementType, int32 containerTypMod, List *indirection, Node *assignFrom)
Definition: parse_node.c:297
Oid get_typcollation(Oid typid)
Definition: lsyscache.c:2823
#define Assert(condition)
Definition: c.h:733
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:822
Oid transformContainerType(Oid *containerType, int32 *containerTypmod)
Definition: parse_node.c:216

◆ transformExpressionList()

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

Definition at line 229 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().

231 {
232  List *result = NIL;
233  ListCell *lc;
234 
235  foreach(lc, exprlist)
236  {
237  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  if (IsA(e, ColumnRef))
245  {
246  ColumnRef *cref = (ColumnRef *) e;
247 
248  if (IsA(llast(cref->fields), A_Star))
249  {
250  /* It is something.*, expand into multiple items */
251  result = list_concat(result,
252  ExpandColumnRefStar(pstate, cref,
253  false));
254  continue;
255  }
256  }
257  else if (IsA(e, A_Indirection))
258  {
260 
261  if (IsA(llast(ind->indirection), A_Star))
262  {
263  /* It is something.*, expand into multiple items */
264  result = list_concat(result,
265  ExpandIndirectionStar(pstate, ind,
266  false, exprKind));
267  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  if (allowDefault && IsA(e, SetToDefault))
278  /* do nothing */ ;
279  else
280  e = transformExpr(pstate, e, exprKind);
281 
282  result = lappend(result, e);
283  }
284 
285  /* Shouldn't have any multiassign items here */
286  Assert(pstate->p_multiassign_exprs == NIL);
287 
288  return result;
289 }
#define NIL
Definition: pg_list.h:65
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:144
#define llast(l)
Definition: pg_list.h:215
Definition: nodes.h:525
List * list_concat(List *list1, const List *list2)
Definition: list.c:516
List * p_multiassign_exprs
Definition: parse_node.h:193
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:322
#define Assert(condition)
Definition: c.h:733
#define lfirst(lc)
Definition: pg_list.h:190
List * indirection
Definition: parsenodes.h:406
e
Definition: preproc-init.c:82
Definition: pg_list.h:50
List * fields
Definition: parsenodes.h:235

◆ transformTargetEntry()

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

Definition at line 86 of file parse_target.c.

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

Referenced by findTargetlistEntrySQL99(), and transformTargetList().

92 {
93  /* Transform the node if caller didn't do it already */
94  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  if (exprKind == EXPR_KIND_UPDATE_SOURCE && IsA(node, SetToDefault))
102  expr = node;
103  else
104  expr = transformExpr(pstate, node, exprKind);
105  }
106 
107  if (colname == NULL && !resjunk)
108  {
109  /*
110  * Generate a suitable column name for a column without any explicit
111  * 'AS ColumnName' clause.
112  */
113  colname = FigureColname(node);
114  }
115 
116  return makeTargetEntry((Expr *) expr,
117  (AttrNumber) pstate->p_next_resno++,
118  colname,
119  resjunk);
120 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:144
char * FigureColname(Node *node)
int p_next_resno
Definition: parse_node.h:192
TargetEntry * makeTargetEntry(Expr *expr, AttrNumber resno, char *resname, bool resjunk)
Definition: makefuncs.c:236
int16 AttrNumber
Definition: attnum.h:21

◆ transformTargetList()

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

Definition at line 132 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().

134 {
135  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  expand_star = (exprKind != EXPR_KIND_UPDATE_SOURCE);
144 
145  foreach(o_target, targetlist)
146  {
147  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  if (expand_star)
155  {
156  if (IsA(res->val, ColumnRef))
157  {
158  ColumnRef *cref = (ColumnRef *) res->val;
159 
160  if (IsA(llast(cref->fields), A_Star))
161  {
162  /* It is something.*, expand into multiple items */
163  p_target = list_concat(p_target,
164  ExpandColumnRefStar(pstate,
165  cref,
166  true));
167  continue;
168  }
169  }
170  else if (IsA(res->val, A_Indirection))
171  {
172  A_Indirection *ind = (A_Indirection *) res->val;
173 
174  if (IsA(llast(ind->indirection), A_Star))
175  {
176  /* It is something.*, expand into multiple items */
177  p_target = list_concat(p_target,
178  ExpandIndirectionStar(pstate,
179  ind,
180  true,
181  exprKind));
182  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  p_target = lappend(p_target,
192  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  if (pstate->p_multiassign_exprs)
207  {
208  Assert(exprKind == EXPR_KIND_UPDATE_SOURCE);
209  p_target = list_concat(p_target, pstate->p_multiassign_exprs);
210  pstate->p_multiassign_exprs = NIL;
211  }
212 
213  return p_target;
214 }
#define NIL
Definition: pg_list.h:65
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
Node * val
Definition: parsenodes.h:442
char * name
Definition: parsenodes.h:440
#define llast(l)
Definition: pg_list.h:215
List * list_concat(List *list1, const List *list2)
Definition: list.c:516
List * p_multiassign_exprs
Definition: parse_node.h:193
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:322
#define Assert(condition)
Definition: c.h:733
#define lfirst(lc)
Definition: pg_list.h:190
List * indirection
Definition: parsenodes.h:406
TargetEntry * transformTargetEntry(ParseState *pstate, Node *node, Node *expr, ParseExprKind exprKind, char *colname, bool resjunk)
Definition: parse_target.c:86
Definition: pg_list.h:50
List * fields
Definition: parsenodes.h:235

◆ updateTargetListEntry()

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

Definition at line 620 of file parse_target.c.

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

Referenced by transformUpdateTargetList().

626 {
627  /* Fix up expression as needed */
628  tle->expr = transformAssignedExpr(pstate,
629  tle->expr,
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  tle->resno = (AttrNumber) attrno;
643  tle->resname = colname;
644 }
Expr * transformAssignedExpr(ParseState *pstate, Expr *expr, ParseExprKind exprKind, const char *colname, int attrno, List *indirection, int location)
Definition: parse_target.c:457
char * resname
Definition: primnodes.h:1395
AttrNumber resno
Definition: primnodes.h:1394
Expr * expr
Definition: primnodes.h:1393
int16 AttrNumber
Definition: attnum.h:21