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/parsetree.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 "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 targetIsArray, Oid targetTypeId, int32 targetTypMod, Oid targetCollation, ListCell *indirection, Node *rhs, int location)
 
static NodetransformAssignmentSubscripts (ParseState *pstate, Node *basenode, const char *targetName, Oid targetTypeId, int32 targetTypMod, Oid targetCollation, List *subscripts, bool isSlice, 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 972 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().

973 {
974  *attrnos = NIL;
975 
976  if (cols == NIL)
977  {
978  /*
979  * Generate default column list for INSERT.
980  */
981  int numcol = RelationGetNumberOfAttributes(pstate->p_target_relation);
982 
983  int i;
984 
985  for (i = 0; i < numcol; i++)
986  {
987  ResTarget *col;
988  Form_pg_attribute attr;
989 
990  attr = TupleDescAttr(pstate->p_target_relation->rd_att, i);
991 
992  if (attr->attisdropped)
993  continue;
994 
995  col = makeNode(ResTarget);
996  col->name = pstrdup(NameStr(attr->attname));
997  col->indirection = NIL;
998  col->val = NULL;
999  col->location = -1;
1000  cols = lappend(cols, col);
1001  *attrnos = lappend_int(*attrnos, i + 1);
1002  }
1003  }
1004  else
1005  {
1006  /*
1007  * Do initial validation of user-supplied INSERT column list.
1008  */
1009  Bitmapset *wholecols = NULL;
1010  Bitmapset *partialcols = NULL;
1011  ListCell *tl;
1012 
1013  foreach(tl, cols)
1014  {
1015  ResTarget *col = (ResTarget *) lfirst(tl);
1016  char *name = col->name;
1017  int attrno;
1018 
1019  /* Lookup column name, ereport on failure */
1020  attrno = attnameAttNum(pstate->p_target_relation, name, false);
1021  if (attrno == InvalidAttrNumber)
1022  ereport(ERROR,
1023  (errcode(ERRCODE_UNDEFINED_COLUMN),
1024  errmsg("column \"%s\" of relation \"%s\" does not exist",
1025  name,
1027  parser_errposition(pstate, col->location)));
1028 
1029  /*
1030  * Check for duplicates, but only of whole columns --- we allow
1031  * INSERT INTO foo (col.subcol1, col.subcol2)
1032  */
1033  if (col->indirection == NIL)
1034  {
1035  /* whole column; must not have any other assignment */
1036  if (bms_is_member(attrno, wholecols) ||
1037  bms_is_member(attrno, partialcols))
1038  ereport(ERROR,
1039  (errcode(ERRCODE_DUPLICATE_COLUMN),
1040  errmsg("column \"%s\" specified more than once",
1041  name),
1042  parser_errposition(pstate, col->location)));
1043  wholecols = bms_add_member(wholecols, attrno);
1044  }
1045  else
1046  {
1047  /* partial column; must not have any whole assignment */
1048  if (bms_is_member(attrno, wholecols))
1049  ereport(ERROR,
1050  (errcode(ERRCODE_DUPLICATE_COLUMN),
1051  errmsg("column \"%s\" specified more than once",
1052  name),
1053  parser_errposition(pstate, col->location)));
1054  partialcols = bms_add_member(partialcols, attrno);
1055  }
1056 
1057  *attrnos = lappend_int(*attrnos, attrno);
1058  }
1059  }
1060 
1061  return cols;
1062 }
List * indirection
Definition: parsenodes.h:442
#define NIL
Definition: pg_list.h:69
Node * val
Definition: parsenodes.h:443
char * name
Definition: parsenodes.h:441
#define RelationGetNumberOfAttributes(relation)
Definition: rel.h:413
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:93
char * pstrdup(const char *in)
Definition: mcxt.c:1161
int errcode(int sqlerrcode)
Definition: elog.c:575
int location
Definition: parsenodes.h:444
#define ERROR
Definition: elog.h:43
#define RelationGetRelationName(relation)
Definition: rel.h:441
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:197
#define ereport(elevel, rest)
Definition: elog.h:122
List * lappend_int(List *list, int datum)
Definition: list.c:146
List * lappend(List *list, void *datum)
Definition: list.c:128
TupleDesc rd_att
Definition: rel.h:85
#define makeNode(_type_)
Definition: nodes.h:565
int attnameAttNum(Relation rd, const char *attname, bool sysColOK)
#define lfirst(lc)
Definition: pg_list.h:106
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:764
const char * name
Definition: encode.c:521
#define InvalidAttrNumber
Definition: attnum.h:23
int errmsg(const char *fmt,...)
Definition: elog.c:797
Relation p_target_relation
Definition: parse_node.h:184
int i
#define NameStr(name)
Definition: c.h:576
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:486

◆ ExpandAllTables()

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

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

1248 {
1249  List *target = NIL;
1250  bool found_table = false;
1251  ListCell *l;
1252 
1253  foreach(l, pstate->p_namespace)
1254  {
1255  ParseNamespaceItem *nsitem = (ParseNamespaceItem *) lfirst(l);
1256  RangeTblEntry *rte = nsitem->p_rte;
1257 
1258  /* Ignore table-only items */
1259  if (!nsitem->p_cols_visible)
1260  continue;
1261  /* Should not have any lateral-only items when parsing targetlist */
1262  Assert(!nsitem->p_lateral_only);
1263  /* Remember we found a p_cols_visible item */
1264  found_table = true;
1265 
1266  target = list_concat(target,
1267  expandRelAttrs(pstate,
1268  rte,
1269  RTERangeTablePosn(pstate, rte,
1270  NULL),
1271  0,
1272  location));
1273  }
1274 
1275  /*
1276  * Check for "SELECT *;". We do it this way, rather than checking for
1277  * target == NIL, because we want to allow SELECT * FROM a zero_column
1278  * table.
1279  */
1280  if (!found_table)
1281  ereport(ERROR,
1282  (errcode(ERRCODE_SYNTAX_ERROR),
1283  errmsg("SELECT * with no tables specified is not valid"),
1284  parser_errposition(pstate, location)));
1285 
1286  return target;
1287 }
#define NIL
Definition: pg_list.h:69
int errcode(int sqlerrcode)
Definition: elog.c:575
List * list_concat(List *list1, List *list2)
Definition: list.c:321
RangeTblEntry * p_rte
Definition: parse_node.h:248
#define ERROR
Definition: elog.h:43
List * p_namespace
Definition: parse_node.h:178
List * expandRelAttrs(ParseState *pstate, RangeTblEntry *rte, int rtindex, int sublevels_up, int location)
#define ereport(elevel, rest)
Definition: elog.h:122
#define Assert(condition)
Definition: c.h:699
#define lfirst(lc)
Definition: pg_list.h:106
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
int RTERangeTablePosn(ParseState *pstate, RangeTblEntry *rte, int *sublevels_up)
int errmsg(const char *fmt,...)
Definition: elog.c:797
Definition: pg_list.h:45

◆ ExpandColumnRefStar()

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

Definition at line 1077 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(), and strVal.

Referenced by transformExpressionList(), and transformTargetList().

1079 {
1080  List *fields = cref->fields;
1081  int numnames = list_length(fields);
1082 
1083  if (numnames == 1)
1084  {
1085  /*
1086  * Target item is a bare '*', expand all tables
1087  *
1088  * (e.g., SELECT * FROM emp, dept)
1089  *
1090  * Since the grammar only accepts bare '*' at top level of SELECT, we
1091  * need not handle the make_target_entry==false case here.
1092  */
1093  Assert(make_target_entry);
1094  return ExpandAllTables(pstate, cref->location);
1095  }
1096  else
1097  {
1098  /*
1099  * Target item is relation.*, expand that table
1100  *
1101  * (e.g., SELECT emp.*, dname FROM emp, dept)
1102  *
1103  * Note: this code is a lot like transformColumnRef; it's tempting to
1104  * call that instead and then replace the resulting whole-row Var with
1105  * a list of Vars. However, that would leave us with the RTE's
1106  * selectedCols bitmap showing the whole row as needing select
1107  * permission, as well as the individual columns. That would be
1108  * incorrect (since columns added later shouldn't need select
1109  * permissions). We could try to remove the whole-row permission bit
1110  * after the fact, but duplicating code is less messy.
1111  */
1112  char *nspname = NULL;
1113  char *relname = NULL;
1114  RangeTblEntry *rte = NULL;
1115  int levels_up;
1116  enum
1117  {
1118  CRSERR_NO_RTE,
1119  CRSERR_WRONG_DB,
1120  CRSERR_TOO_MANY
1121  } crserr = CRSERR_NO_RTE;
1122 
1123  /*
1124  * Give the PreParseColumnRefHook, if any, first shot. If it returns
1125  * non-null then we should use that expression.
1126  */
1127  if (pstate->p_pre_columnref_hook != NULL)
1128  {
1129  Node *node;
1130 
1131  node = pstate->p_pre_columnref_hook(pstate, cref);
1132  if (node != NULL)
1133  return ExpandRowReference(pstate, node, make_target_entry);
1134  }
1135 
1136  switch (numnames)
1137  {
1138  case 2:
1139  relname = strVal(linitial(fields));
1140  rte = refnameRangeTblEntry(pstate, nspname, relname,
1141  cref->location,
1142  &levels_up);
1143  break;
1144  case 3:
1145  nspname = strVal(linitial(fields));
1146  relname = strVal(lsecond(fields));
1147  rte = refnameRangeTblEntry(pstate, nspname, relname,
1148  cref->location,
1149  &levels_up);
1150  break;
1151  case 4:
1152  {
1153  char *catname = strVal(linitial(fields));
1154 
1155  /*
1156  * We check the catalog name and then ignore it.
1157  */
1158  if (strcmp(catname, get_database_name(MyDatabaseId)) != 0)
1159  {
1160  crserr = CRSERR_WRONG_DB;
1161  break;
1162  }
1163  nspname = strVal(lsecond(fields));
1164  relname = strVal(lthird(fields));
1165  rte = refnameRangeTblEntry(pstate, nspname, relname,
1166  cref->location,
1167  &levels_up);
1168  break;
1169  }
1170  default:
1171  crserr = CRSERR_TOO_MANY;
1172  break;
1173  }
1174 
1175  /*
1176  * Now give the PostParseColumnRefHook, if any, a chance. We cheat a
1177  * bit by passing the RangeTblEntry, not a Var, as the planned
1178  * translation. (A single Var wouldn't be strictly correct anyway.
1179  * This convention allows hooks that really care to know what is
1180  * happening.)
1181  */
1182  if (pstate->p_post_columnref_hook != NULL)
1183  {
1184  Node *node;
1185 
1186  node = pstate->p_post_columnref_hook(pstate, cref,
1187  (Node *) rte);
1188  if (node != NULL)
1189  {
1190  if (rte != NULL)
1191  ereport(ERROR,
1192  (errcode(ERRCODE_AMBIGUOUS_COLUMN),
1193  errmsg("column reference \"%s\" is ambiguous",
1194  NameListToString(cref->fields)),
1195  parser_errposition(pstate, cref->location)));
1196  return ExpandRowReference(pstate, node, make_target_entry);
1197  }
1198  }
1199 
1200  /*
1201  * Throw error if no translation found.
1202  */
1203  if (rte == NULL)
1204  {
1205  switch (crserr)
1206  {
1207  case CRSERR_NO_RTE:
1208  errorMissingRTE(pstate, makeRangeVar(nspname, relname,
1209  cref->location));
1210  break;
1211  case CRSERR_WRONG_DB:
1212  ereport(ERROR,
1213  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1214  errmsg("cross-database references are not implemented: %s",
1215  NameListToString(cref->fields)),
1216  parser_errposition(pstate, cref->location)));
1217  break;
1218  case CRSERR_TOO_MANY:
1219  ereport(ERROR,
1220  (errcode(ERRCODE_SYNTAX_ERROR),
1221  errmsg("improper qualified name (too many dotted names): %s",
1222  NameListToString(cref->fields)),
1223  parser_errposition(pstate, cref->location)));
1224  break;
1225  }
1226  }
1227 
1228  /*
1229  * OK, expand the RTE into fields.
1230  */
1231  return ExpandSingleTable(pstate, rte, cref->location, make_target_entry);
1232  }
1233 }
Definition: nodes.h:517
#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:575
RangeTblEntry * refnameRangeTblEntry(ParseState *pstate, const char *schemaname, const char *refname, int location, int *sublevels_up)
#define lsecond(l)
Definition: pg_list.h:116
PostParseColumnRefHook p_post_columnref_hook
Definition: parse_node.h:213
int location
Definition: parsenodes.h:237
static List * ExpandRowReference(ParseState *pstate, Node *expr, bool make_target_entry)
#define linitial(l)
Definition: pg_list.h:111
#define ERROR
Definition: elog.h:43
char * get_database_name(Oid dbid)
Definition: dbcommands.c:2056
void errorMissingRTE(ParseState *pstate, RangeVar *relation)
#define ereport(elevel, rest)
Definition: elog.h:122
char * NameListToString(List *names)
Definition: namespace.c:3082
Oid MyDatabaseId
Definition: globals.c:84
#define Assert(condition)
Definition: c.h:699
static int list_length(const List *l)
Definition: pg_list.h:89
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
int errmsg(const char *fmt,...)
Definition: elog.c:797
static List * ExpandAllTables(ParseState *pstate, int location)
#define lthird(l)
Definition: pg_list.h:121
PreParseColumnRefHook p_pre_columnref_hook
Definition: parse_node.h:212
Definition: pg_list.h:45
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition: makefuncs.c:421
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 1301 of file parse_target.c.

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

Referenced by transformExpressionList(), and transformTargetList().

1303 {
1304  Node *expr;
1305 
1306  /* Strip off the '*' to create a reference to the rowtype object */
1307  ind = copyObject(ind);
1309  list_length(ind->indirection) - 1);
1310 
1311  /* And transform that */
1312  expr = transformExpr(pstate, (Node *) ind, exprKind);
1313 
1314  /* Expand the rowtype expression into individual fields */
1315  return ExpandRowReference(pstate, expr, make_target_entry);
1316 }
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:146
List * list_truncate(List *list, int new_size)
Definition: list.c:350
Definition: nodes.h:517
static List * ExpandRowReference(ParseState *pstate, Node *expr, bool make_target_entry)
List * indirection
Definition: parsenodes.h:407
static int list_length(const List *l)
Definition: pg_list.h:89
#define copyObject(obj)
Definition: nodes.h:630

◆ expandRecordVariable()

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

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

1473 {
1475  int netlevelsup;
1476  RangeTblEntry *rte;
1478  Node *expr;
1479 
1480  /* Check my caller didn't mess up */
1481  Assert(IsA(var, Var));
1482  Assert(var->vartype == RECORDOID);
1483 
1484  netlevelsup = var->varlevelsup + levelsup;
1485  rte = GetRTEByRangeTablePosn(pstate, var->varno, netlevelsup);
1486  attnum = var->varattno;
1487 
1488  if (attnum == InvalidAttrNumber)
1489  {
1490  /* Whole-row reference to an RTE, so expand the known fields */
1491  List *names,
1492  *vars;
1493  ListCell *lname,
1494  *lvar;
1495  int i;
1496 
1497  expandRTE(rte, var->varno, 0, var->location, false,
1498  &names, &vars);
1499 
1500  tupleDesc = CreateTemplateTupleDesc(list_length(vars), false);
1501  i = 1;
1502  forboth(lname, names, lvar, vars)
1503  {
1504  char *label = strVal(lfirst(lname));
1505  Node *varnode = (Node *) lfirst(lvar);
1506 
1507  TupleDescInitEntry(tupleDesc, i,
1508  label,
1509  exprType(varnode),
1510  exprTypmod(varnode),
1511  0);
1512  TupleDescInitEntryCollation(tupleDesc, i,
1513  exprCollation(varnode));
1514  i++;
1515  }
1516  Assert(lname == NULL && lvar == NULL); /* lists same length? */
1517 
1518  return tupleDesc;
1519  }
1520 
1521  expr = (Node *) var; /* default if we can't drill down */
1522 
1523  switch (rte->rtekind)
1524  {
1525  case RTE_RELATION:
1526  case RTE_VALUES:
1527  case RTE_NAMEDTUPLESTORE:
1528 
1529  /*
1530  * This case should not occur: a column of a table, values list,
1531  * or ENR shouldn't have type RECORD. Fall through and fail (most
1532  * likely) at the bottom.
1533  */
1534  break;
1535  case RTE_SUBQUERY:
1536  {
1537  /* Subselect-in-FROM: examine sub-select's output expr */
1539  attnum);
1540 
1541  if (ste == NULL || ste->resjunk)
1542  elog(ERROR, "subquery %s does not have attribute %d",
1543  rte->eref->aliasname, attnum);
1544  expr = (Node *) ste->expr;
1545  if (IsA(expr, Var))
1546  {
1547  /*
1548  * Recurse into the sub-select to see what its Var refers
1549  * to. We have to build an additional level of ParseState
1550  * to keep in step with varlevelsup in the subselect.
1551  */
1552  ParseState mypstate;
1553 
1554  MemSet(&mypstate, 0, sizeof(mypstate));
1555  mypstate.parentParseState = pstate;
1556  mypstate.p_rtable = rte->subquery->rtable;
1557  /* don't bother filling the rest of the fake pstate */
1558 
1559  return expandRecordVariable(&mypstate, (Var *) expr, 0);
1560  }
1561  /* else fall through to inspect the expression */
1562  }
1563  break;
1564  case RTE_JOIN:
1565  /* Join RTE --- recursively inspect the alias variable */
1566  Assert(attnum > 0 && attnum <= list_length(rte->joinaliasvars));
1567  expr = (Node *) list_nth(rte->joinaliasvars, attnum - 1);
1568  Assert(expr != NULL);
1569  /* We intentionally don't strip implicit coercions here */
1570  if (IsA(expr, Var))
1571  return expandRecordVariable(pstate, (Var *) expr, netlevelsup);
1572  /* else fall through to inspect the expression */
1573  break;
1574  case RTE_FUNCTION:
1575 
1576  /*
1577  * We couldn't get here unless a function is declared with one of
1578  * its result columns as RECORD, which is not allowed.
1579  */
1580  break;
1581  case RTE_TABLEFUNC:
1582 
1583  /*
1584  * Table function cannot have columns with RECORD type.
1585  */
1586  break;
1587  case RTE_CTE:
1588  /* CTE reference: examine subquery's output expr */
1589  if (!rte->self_reference)
1590  {
1591  CommonTableExpr *cte = GetCTEForRTE(pstate, rte, netlevelsup);
1592  TargetEntry *ste;
1593 
1594  ste = get_tle_by_resno(GetCTETargetList(cte), attnum);
1595  if (ste == NULL || ste->resjunk)
1596  elog(ERROR, "subquery %s does not have attribute %d",
1597  rte->eref->aliasname, attnum);
1598  expr = (Node *) ste->expr;
1599  if (IsA(expr, Var))
1600  {
1601  /*
1602  * Recurse into the CTE to see what its Var refers to. We
1603  * have to build an additional level of ParseState to keep
1604  * in step with varlevelsup in the CTE; furthermore it
1605  * could be an outer CTE.
1606  */
1607  ParseState mypstate;
1608  Index levelsup;
1609 
1610  MemSet(&mypstate, 0, sizeof(mypstate));
1611  /* this loop must work, since GetCTEForRTE did */
1612  for (levelsup = 0;
1613  levelsup < rte->ctelevelsup + netlevelsup;
1614  levelsup++)
1615  pstate = pstate->parentParseState;
1616  mypstate.parentParseState = pstate;
1617  mypstate.p_rtable = ((Query *) cte->ctequery)->rtable;
1618  /* don't bother filling the rest of the fake pstate */
1619 
1620  return expandRecordVariable(&mypstate, (Var *) expr, 0);
1621  }
1622  /* else fall through to inspect the expression */
1623  }
1624  break;
1625  }
1626 
1627  /*
1628  * We now have an expression we can't expand any more, so see if
1629  * get_expr_result_tupdesc() can do anything with it.
1630  */
1631  return get_expr_result_tupdesc(expr, false);
1632 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:568
List * joinaliasvars
Definition: parsenodes.h:1006
Index varlevelsup
Definition: primnodes.h:174
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:180
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:276
CommonTableExpr * GetCTEForRTE(ParseState *pstate, RangeTblEntry *rte, int rtelevelsup)
Definition: nodes.h:517
#define strVal(v)
Definition: value.h:54
#define MemSet(start, val, len)
Definition: c.h:908
AttrNumber varattno
Definition: primnodes.h:169
Definition: primnodes.h:164
List * targetList
Definition: parsenodes.h:140
bool resjunk
Definition: primnodes.h:1383
List * rtable
Definition: parsenodes.h:137
#define ERROR
Definition: elog.h:43
TupleDesc get_expr_result_tupdesc(Node *expr, bool noError)
Definition: funcapi.c:412
Oid vartype
Definition: primnodes.h:171
void TupleDescInitEntryCollation(TupleDesc desc, AttrNumber attributeNumber, Oid collationid)
Definition: tupdesc.c:761
int location
Definition: primnodes.h:179
void * list_nth(const List *list, int n)
Definition: list.c:410
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:600
Index varno
Definition: primnodes.h:167
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:172
bool self_reference
Definition: parsenodes.h:1034
static char * label
Definition: pg_basebackup.c:84
RangeTblEntry * GetRTEByRangeTablePosn(ParseState *pstate, int varno, int sublevels_up)
unsigned int Index
Definition: c.h:442
int16 attnum
Definition: pg_attribute.h:79
#define Assert(condition)
Definition: c.h:699
#define lfirst(lc)
Definition: pg_list.h:106
char * aliasname
Definition: primnodes.h:43
Expr * expr
Definition: primnodes.h:1376
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
static int list_length(const List *l)
Definition: pg_list.h:89
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:720
Index ctelevelsup
Definition: parsenodes.h:1033
TupleDesc CreateTemplateTupleDesc(int natts, bool hasoid)
Definition: tupdesc.c:45
#define InvalidAttrNumber
Definition: attnum.h:23
RTEKind rtekind
Definition: parsenodes.h:962
Query * subquery
Definition: parsenodes.h:985
int i
TargetEntry * get_tle_by_resno(List *tlist, AttrNumber resno)
#define elog
Definition: elog.h:219
Alias * eref
Definition: parsenodes.h:1066
Definition: regcomp.c:224
Definition: pg_list.h:45
#define GetCTETargetList(cte)
Definition: parsenodes.h:1409
int16 AttrNumber
Definition: attnum.h:21
List * p_rtable
Definition: parse_node.h:174

◆ ExpandRowReference()

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

Definition at line 1377 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, tupleDesc::natts, NIL, ParseState::p_next_resno, pstrdup(), FieldSelect::resultcollid, FieldSelect::resulttype, FieldSelect::resulttypmod, TupleDescAttr, Var::varlevelsup, and Var::varno.

Referenced by ExpandColumnRefStar(), and ExpandIndirectionStar().

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

◆ ExpandSingleTable()

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

Definition at line 1328 of file parse_target.c.

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

Referenced by ExpandColumnRefStar(), and ExpandRowReference().

1330 {
1331  int sublevels_up;
1332  int rtindex;
1333 
1334  rtindex = RTERangeTablePosn(pstate, rte, &sublevels_up);
1335 
1336  if (make_target_entry)
1337  {
1338  /* expandRelAttrs handles permissions marking */
1339  return expandRelAttrs(pstate, rte, rtindex, sublevels_up,
1340  location);
1341  }
1342  else
1343  {
1344  List *vars;
1345  ListCell *l;
1346 
1347  expandRTE(rte, rtindex, sublevels_up, location, false,
1348  NULL, &vars);
1349 
1350  /*
1351  * Require read access to the table. This is normally redundant with
1352  * the markVarForSelectPriv calls below, but not if the table has zero
1353  * columns.
1354  */
1355  rte->requiredPerms |= ACL_SELECT;
1356 
1357  /* Require read access to each column */
1358  foreach(l, vars)
1359  {
1360  Var *var = (Var *) lfirst(l);
1361 
1362  markVarForSelectPriv(pstate, var, rte);
1363  }
1364 
1365  return vars;
1366  }
1367 }
void markVarForSelectPriv(ParseState *pstate, Var *var, RangeTblEntry *rte)
AclMode requiredPerms
Definition: parsenodes.h:1070
Definition: primnodes.h:164
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:106
int RTERangeTablePosn(ParseState *pstate, RangeTblEntry *rte, int *sublevels_up)
Definition: regcomp.c:224
Definition: pg_list.h:45

◆ FigureColname()

char* FigureColname ( Node node)

Definition at line 1645 of file parse_target.c.

References FigureColnameInternal(), and name.

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

1646 {
1647  char *name = NULL;
1648 
1649  (void) FigureColnameInternal(node, &name);
1650  if (name != NULL)
1651  return name;
1652  /* default result if we can't guess anything */
1653  return "?column?";
1654 }
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 1684 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().

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

◆ FigureIndexColname()

char* FigureIndexColname ( Node node)

Definition at line 1664 of file parse_target.c.

References FigureColnameInternal(), and name.

Referenced by transformIndexStmt().

1665 {
1666  char *name = NULL;
1667 
1668  (void) FigureColnameInternal(node, &name);
1669  return name;
1670 }
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 351 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_SUBQUERY, RTE_TABLEFUNC, RTE_VALUES, RangeTblEntry::rtekind, RangeTblEntry::self_reference, RangeTblEntry::subquery, Query::targetList, Var::varattno, Var::varlevelsup, and Var::varno.

Referenced by markTargetListOrigins().

353 {
354  int netlevelsup;
355  RangeTblEntry *rte;
357 
358  if (var == NULL || !IsA(var, Var))
359  return;
360  netlevelsup = var->varlevelsup + levelsup;
361  rte = GetRTEByRangeTablePosn(pstate, var->varno, netlevelsup);
362  attnum = var->varattno;
363 
364  switch (rte->rtekind)
365  {
366  case RTE_RELATION:
367  /* It's a table or view, report it */
368  tle->resorigtbl = rte->relid;
369  tle->resorigcol = attnum;
370  break;
371  case RTE_SUBQUERY:
372  /* Subselect-in-FROM: copy up from the subselect */
373  if (attnum != InvalidAttrNumber)
374  {
376  attnum);
377 
378  if (ste == NULL || ste->resjunk)
379  elog(ERROR, "subquery %s does not have attribute %d",
380  rte->eref->aliasname, attnum);
381  tle->resorigtbl = ste->resorigtbl;
382  tle->resorigcol = ste->resorigcol;
383  }
384  break;
385  case RTE_JOIN:
386  /* Join RTE --- recursively inspect the alias variable */
387  if (attnum != InvalidAttrNumber)
388  {
389  Var *aliasvar;
390 
391  Assert(attnum > 0 && attnum <= list_length(rte->joinaliasvars));
392  aliasvar = (Var *) list_nth(rte->joinaliasvars, attnum - 1);
393  /* We intentionally don't strip implicit coercions here */
394  markTargetListOrigin(pstate, tle, aliasvar, netlevelsup);
395  }
396  break;
397  case RTE_FUNCTION:
398  case RTE_VALUES:
399  case RTE_TABLEFUNC:
400  case RTE_NAMEDTUPLESTORE:
401  /* not a simple relation, leave it unmarked */
402  break;
403  case RTE_CTE:
404 
405  /*
406  * CTE reference: copy up from the subquery, if possible. If the
407  * RTE is a recursive self-reference then we can't do anything
408  * because we haven't finished analyzing it yet. However, it's no
409  * big loss because we must be down inside the recursive term of a
410  * recursive CTE, and so any markings on the current targetlist
411  * are not going to affect the results anyway.
412  */
413  if (attnum != InvalidAttrNumber && !rte->self_reference)
414  {
415  CommonTableExpr *cte = GetCTEForRTE(pstate, rte, netlevelsup);
416  TargetEntry *ste;
417 
418  ste = get_tle_by_resno(GetCTETargetList(cte), attnum);
419  if (ste == NULL || ste->resjunk)
420  elog(ERROR, "subquery %s does not have attribute %d",
421  rte->eref->aliasname, attnum);
422  tle->resorigtbl = ste->resorigtbl;
423  tle->resorigcol = ste->resorigcol;
424  }
425  break;
426  }
427 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:568
List * joinaliasvars
Definition: parsenodes.h:1006
Index varlevelsup
Definition: primnodes.h:174
CommonTableExpr * GetCTEForRTE(ParseState *pstate, RangeTblEntry *rte, int rtelevelsup)
Oid resorigtbl
Definition: primnodes.h:1381
AttrNumber varattno
Definition: primnodes.h:169
Definition: primnodes.h:164
List * targetList
Definition: parsenodes.h:140
bool resjunk
Definition: primnodes.h:1383
#define ERROR
Definition: elog.h:43
void * list_nth(const List *list, int n)
Definition: list.c:410
Index varno
Definition: primnodes.h:167
bool self_reference
Definition: parsenodes.h:1034
RangeTblEntry * GetRTEByRangeTablePosn(ParseState *pstate, int varno, int sublevels_up)
int16 attnum
Definition: pg_attribute.h:79
#define Assert(condition)
Definition: c.h:699
char * aliasname
Definition: primnodes.h:43
static int list_length(const List *l)
Definition: pg_list.h:89
#define InvalidAttrNumber
Definition: attnum.h:23
RTEKind rtekind
Definition: parsenodes.h:962
static void markTargetListOrigin(ParseState *pstate, TargetEntry *tle, Var *var, int levelsup)
Definition: parse_target.c:351
AttrNumber resorigcol
Definition: primnodes.h:1382
Query * subquery
Definition: parsenodes.h:985
TargetEntry * get_tle_by_resno(List *tlist, AttrNumber resno)
#define elog
Definition: elog.h:219
Alias * eref
Definition: parsenodes.h:1066
#define GetCTETargetList(cte)
Definition: parsenodes.h:1409
int16 AttrNumber
Definition: attnum.h:21

◆ markTargetListOrigins()

void markTargetListOrigins ( ParseState pstate,
List targetlist 
)

Definition at line 329 of file parse_target.c.

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

Referenced by transformReturningList(), and transformSelectStmt().

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

◆ resolveTargetListUnknowns()

void resolveTargetListUnknowns ( ParseState pstate,
List targetlist 
)

Definition at line 299 of file parse_target.c.

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

Referenced by transformReturningList(), and transformSelectStmt().

300 {
301  ListCell *l;
302 
303  foreach(l, targetlist)
304  {
305  TargetEntry *tle = (TargetEntry *) lfirst(l);
306  Oid restype = exprType((Node *) tle->expr);
307 
308  if (restype == UNKNOWNOID)
309  {
310  tle->expr = (Expr *) coerce_type(pstate, (Node *) tle->expr,
311  restype, TEXTOID, -1,
314  -1);
315  }
316  }
317 }
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:517
unsigned int Oid
Definition: postgres_ext.h:31
#define lfirst(lc)
Definition: pg_list.h:106
Expr * expr
Definition: primnodes.h:1376
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42

◆ transformAssignedExpr()

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

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

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

◆ transformAssignmentIndirection()

static Node * transformAssignmentIndirection ( ParseState pstate,
Node basenode,
const char *  targetName,
bool  targetIsArray,
Oid  targetTypeId,
int32  targetTypMod,
Oid  targetCollation,
ListCell indirection,
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().

686 {
687  Node *result;
688  List *subscripts = NIL;
689  bool isSlice = false;
690  ListCell *i;
691 
692  if (indirection && !basenode)
693  {
694  /* Set up a substitution. We reuse CaseTestExpr for this. */
696 
697  ctest->typeId = targetTypeId;
698  ctest->typeMod = targetTypMod;
699  ctest->collation = targetCollation;
700  basenode = (Node *) ctest;
701  }
702 
703  /*
704  * We have to split any field-selection operations apart from
705  * subscripting. Adjacent A_Indices nodes have to be treated as a single
706  * multidimensional subscript operation.
707  */
708  for_each_cell(i, indirection)
709  {
710  Node *n = lfirst(i);
711 
712  if (IsA(n, A_Indices))
713  {
714  subscripts = lappend(subscripts, n);
715  if (((A_Indices *) n)->is_slice)
716  isSlice = true;
717  }
718  else if (IsA(n, A_Star))
719  {
720  ereport(ERROR,
721  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
722  errmsg("row expansion via \"*\" is not supported here"),
723  parser_errposition(pstate, location)));
724  }
725  else
726  {
727  FieldStore *fstore;
728  Oid baseTypeId;
729  int32 baseTypeMod;
730  Oid typrelid;
732  Oid fieldTypeId;
733  int32 fieldTypMod;
734  Oid fieldCollation;
735 
736  Assert(IsA(n, String));
737 
738  /* process subscripts before this field selection */
739  if (subscripts)
740  {
741  /* recurse, and then return because we're done */
742  return transformAssignmentSubscripts(pstate,
743  basenode,
744  targetName,
745  targetTypeId,
746  targetTypMod,
747  targetCollation,
748  subscripts,
749  isSlice,
750  i,
751  rhs,
752  location);
753  }
754 
755  /* No subscripts, so can process field selection here */
756 
757  /*
758  * Look up the composite type, accounting for possibility that
759  * what we are given is a domain over composite.
760  */
761  baseTypeMod = targetTypMod;
762  baseTypeId = getBaseTypeAndTypmod(targetTypeId, &baseTypeMod);
763 
764  typrelid = typeidTypeRelid(baseTypeId);
765  if (!typrelid)
766  ereport(ERROR,
767  (errcode(ERRCODE_DATATYPE_MISMATCH),
768  errmsg("cannot assign to field \"%s\" of column \"%s\" because its type %s is not a composite type",
769  strVal(n), targetName,
770  format_type_be(targetTypeId)),
771  parser_errposition(pstate, location)));
772 
773  attnum = get_attnum(typrelid, strVal(n));
774  if (attnum == InvalidAttrNumber)
775  ereport(ERROR,
776  (errcode(ERRCODE_UNDEFINED_COLUMN),
777  errmsg("cannot assign to field \"%s\" of column \"%s\" because there is no such column in data type %s",
778  strVal(n), targetName,
779  format_type_be(targetTypeId)),
780  parser_errposition(pstate, location)));
781  if (attnum < 0)
782  ereport(ERROR,
783  (errcode(ERRCODE_UNDEFINED_COLUMN),
784  errmsg("cannot assign to system column \"%s\"",
785  strVal(n)),
786  parser_errposition(pstate, location)));
787 
788  get_atttypetypmodcoll(typrelid, attnum,
789  &fieldTypeId, &fieldTypMod, &fieldCollation);
790 
791  /* recurse to create appropriate RHS for field assign */
792  rhs = transformAssignmentIndirection(pstate,
793  NULL,
794  strVal(n),
795  false,
796  fieldTypeId,
797  fieldTypMod,
798  fieldCollation,
799  lnext(i),
800  rhs,
801  location);
802 
803  /* and build a FieldStore node */
804  fstore = makeNode(FieldStore);
805  fstore->arg = (Expr *) basenode;
806  fstore->newvals = list_make1(rhs);
807  fstore->fieldnums = list_make1_int(attnum);
808  fstore->resulttype = baseTypeId;
809 
810  /* If target is a domain, apply constraints */
811  if (baseTypeId != targetTypeId)
812  return coerce_to_domain((Node *) fstore,
813  baseTypeId, baseTypeMod,
814  targetTypeId,
817  location,
818  false);
819 
820  return (Node *) fstore;
821  }
822  }
823 
824  /* process trailing subscripts, if any */
825  if (subscripts)
826  {
827  /* recurse, and then return because we're done */
828  return transformAssignmentSubscripts(pstate,
829  basenode,
830  targetName,
831  targetTypeId,
832  targetTypMod,
833  targetCollation,
834  subscripts,
835  isSlice,
836  NULL,
837  rhs,
838  location);
839  }
840 
841  /* base case: just coerce RHS to match target type ID */
842 
843  result = coerce_to_target_type(pstate,
844  rhs, exprType(rhs),
845  targetTypeId, targetTypMod,
848  -1);
849  if (result == NULL)
850  {
851  if (targetIsArray)
852  ereport(ERROR,
853  (errcode(ERRCODE_DATATYPE_MISMATCH),
854  errmsg("array assignment to \"%s\" requires type %s"
855  " but expression is of type %s",
856  targetName,
857  format_type_be(targetTypeId),
858  format_type_be(exprType(rhs))),
859  errhint("You will need to rewrite or cast the expression."),
860  parser_errposition(pstate, location)));
861  else
862  ereport(ERROR,
863  (errcode(ERRCODE_DATATYPE_MISMATCH),
864  errmsg("subfield \"%s\" is of 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  }
872 
873  return result;
874 }
#define NIL
Definition: pg_list.h:69
Oid getBaseTypeAndTypmod(Oid typid, int32 *typmod)
Definition: lsyscache.c:2292
#define IsA(nodeptr, _type_)
Definition: nodes.h:568
Expr * arg
Definition: primnodes.h:772
int errhint(const char *fmt,...)
Definition: elog.c:987
Definition: nodes.h:517
#define strVal(v)
Definition: value.h:54
int errcode(int sqlerrcode)
Definition: elog.c:575
char * format_type_be(Oid type_oid)
Definition: format_type.c:328
Oid typeidTypeRelid(Oid type_id)
Definition: parse_type.c:649
unsigned int Oid
Definition: postgres_ext.h:31
static Node * transformAssignmentSubscripts(ParseState *pstate, Node *basenode, const char *targetName, Oid targetTypeId, int32 targetTypMod, Oid targetCollation, List *subscripts, bool isSlice, ListCell *next_indirection, Node *rhs, int location)
Definition: parse_target.c:880
int32 typeMod
Definition: primnodes.h:942
signed int int32
Definition: c.h:313
#define list_make1(x1)
Definition: pg_list.h:139
#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:775
#define list_make1_int(x1)
Definition: pg_list.h:145
#define lnext(lc)
Definition: pg_list.h:105
#define ereport(elevel, rest)
Definition: elog.h:122
List * newvals
Definition: primnodes.h:773
List * lappend(List *list, void *datum)
Definition: list.c:128
int16 attnum
Definition: pg_attribute.h:79
#define makeNode(_type_)
Definition: nodes.h:565
#define Assert(condition)
Definition: c.h:699
#define lfirst(lc)
Definition: pg_list.h:106
void get_atttypetypmodcoll(Oid relid, AttrNumber attnum, Oid *typid, int32 *typmod, Oid *collid)
Definition: lsyscache.c:920
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
#define for_each_cell(cell, initcell)
Definition: pg_list.h:169
#define InvalidAttrNumber
Definition: attnum.h:23
int errmsg(const char *fmt,...)
Definition: elog.c:797
List * fieldnums
Definition: primnodes.h:774
int i
static Node * transformAssignmentIndirection(ParseState *pstate, Node *basenode, const char *targetName, bool targetIsArray, Oid targetTypeId, int32 targetTypMod, Oid targetCollation, ListCell *indirection, Node *rhs, int location)
Definition: parse_target.c:676
Definition: pg_list.h:45
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,
ListCell next_indirection,
Node rhs,
int  location 
)
static

Definition at line 880 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(), transformArraySubscripts(), transformArrayType(), and transformAssignmentIndirection().

Referenced by transformAssignmentIndirection().

891 {
892  Node *result;
893  Oid arrayType;
894  int32 arrayTypMod;
895  Oid elementTypeId;
896  Oid typeNeeded;
897  Oid collationNeeded;
898 
899  Assert(subscripts != NIL);
900 
901  /* Identify the actual array type and element type involved */
902  arrayType = targetTypeId;
903  arrayTypMod = targetTypMod;
904  elementTypeId = transformArrayType(&arrayType, &arrayTypMod);
905 
906  /* Identify type that RHS must provide */
907  typeNeeded = isSlice ? arrayType : elementTypeId;
908 
909  /*
910  * Array normally has same collation as elements, but there's an
911  * exception: we might be subscripting a domain over an array type. In
912  * that case use collation of the base type.
913  */
914  if (arrayType == targetTypeId)
915  collationNeeded = targetCollation;
916  else
917  collationNeeded = get_typcollation(arrayType);
918 
919  /* recurse to create appropriate RHS for array assign */
920  rhs = transformAssignmentIndirection(pstate,
921  NULL,
922  targetName,
923  true,
924  typeNeeded,
925  arrayTypMod,
926  collationNeeded,
927  next_indirection,
928  rhs,
929  location);
930 
931  /* process subscripts */
932  result = (Node *) transformArraySubscripts(pstate,
933  basenode,
934  arrayType,
935  elementTypeId,
936  arrayTypMod,
937  subscripts,
938  rhs);
939 
940  /* If target was a domain over array, need to coerce up to the domain */
941  if (arrayType != targetTypeId)
942  {
943  Oid resulttype = exprType(result);
944 
945  result = coerce_to_target_type(pstate,
946  result, resulttype,
947  targetTypeId, targetTypMod,
950  -1);
951  /* can fail if we had int2vector/oidvector, but not for true domains */
952  if (result == NULL)
953  ereport(ERROR,
954  (errcode(ERRCODE_CANNOT_COERCE),
955  errmsg("cannot cast type %s to %s",
956  format_type_be(resulttype),
957  format_type_be(targetTypeId)),
958  parser_errposition(pstate, location)));
959  }
960 
961  return result;
962 }
#define NIL
Definition: pg_list.h:69
Definition: nodes.h:517
int errcode(int sqlerrcode)
Definition: elog.c:575
char * format_type_be(Oid type_oid)
Definition: format_type.c:328
unsigned int Oid
Definition: postgres_ext.h:31
signed int int32
Definition: c.h:313
#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:122
Oid get_typcollation(Oid typid)
Definition: lsyscache.c:2799
#define Assert(condition)
Definition: c.h:699
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
Oid transformArrayType(Oid *arrayType, int32 *arrayTypmod)
Definition: parse_node.c:216
int errmsg(const char *fmt,...)
Definition: elog.c:797
static Node * transformAssignmentIndirection(ParseState *pstate, Node *basenode, const char *targetName, bool targetIsArray, Oid targetTypeId, int32 targetTypMod, Oid targetCollation, ListCell *indirection, Node *rhs, int location)
Definition: parse_target.c:676
ArrayRef * transformArraySubscripts(ParseState *pstate, Node *arrayBase, Oid arrayType, Oid elementType, int32 arrayTypMod, List *indirection, Node *assignFrom)
Definition: parse_node.c:294

◆ transformExpressionList()

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

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

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

◆ transformTargetEntry()

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

Definition at line 85 of file parse_target.c.

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

Referenced by findTargetlistEntrySQL99(), and transformTargetList().

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

◆ transformTargetList()

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

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

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

◆ updateTargetListEntry()

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

Definition at line 617 of file parse_target.c.

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

Referenced by transformUpdateTargetList().

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