PostgreSQL Source Code  git master
parse_utilcmd.h File Reference
Include dependency graph for parse_utilcmd.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Functions

ListtransformCreateStmt (CreateStmt *stmt, const char *queryString)
 
AlterTableStmttransformAlterTableStmt (Oid relid, AlterTableStmt *stmt, const char *queryString, List **beforeStmts, List **afterStmts)
 
IndexStmttransformIndexStmt (Oid relid, IndexStmt *stmt, const char *queryString)
 
CreateStatsStmttransformStatsStmt (Oid relid, CreateStatsStmt *stmt, const char *queryString)
 
void transformRuleStmt (RuleStmt *stmt, const char *queryString, List **actions, Node **whereClause)
 
ListtransformCreateSchemaStmtElements (List *schemaElts, const char *schemaName)
 
PartitionBoundSpectransformPartitionBound (ParseState *pstate, Relation parent, PartitionBoundSpec *spec)
 
ListexpandTableLikeClause (RangeVar *heapRel, TableLikeClause *table_like_clause)
 
IndexStmtgenerateClonedIndexStmt (RangeVar *heapRel, Relation source_idx, const struct AttrMap *attmap, Oid *constraintOid)
 

Function Documentation

◆ expandTableLikeClause()

List* expandTableLikeClause ( RangeVar heapRel,
TableLikeClause table_like_clause 
)

Definition at line 1298 of file parse_utilcmd.c.

1299 {
1300  List *result = NIL;
1301  List *atsubcmds = NIL;
1302  AttrNumber parent_attno;
1303  Relation relation;
1304  Relation childrel;
1305  TupleDesc tupleDesc;
1306  TupleConstr *constr;
1307  AttrMap *attmap;
1308  char *comment;
1309  bool at_pushed = false;
1310  ListCell *lc;
1311 
1312  /*
1313  * Open the relation referenced by the LIKE clause. We should still have
1314  * the table lock obtained by transformTableLikeClause (and this'll throw
1315  * an assertion failure if not). Hence, no need to recheck privileges
1316  * etc. We must open the rel by OID not name, to be sure we get the same
1317  * table.
1318  */
1319  if (!OidIsValid(table_like_clause->relationOid))
1320  elog(ERROR, "expandTableLikeClause called on untransformed LIKE clause");
1321 
1322  relation = relation_open(table_like_clause->relationOid, NoLock);
1323 
1324  tupleDesc = RelationGetDescr(relation);
1325  constr = tupleDesc->constr;
1326 
1327  /*
1328  * Open the newly-created child relation; we have lock on that too.
1329  */
1330  childrel = relation_openrv(heapRel, NoLock);
1331 
1332  /*
1333  * Construct a map from the LIKE relation's attnos to the child rel's.
1334  * This re-checks type match etc, although it shouldn't be possible to
1335  * have a failure since both tables are locked.
1336  */
1337  attmap = build_attrmap_by_name(RelationGetDescr(childrel),
1338  tupleDesc,
1339  false);
1340 
1341  /*
1342  * Process defaults, if required.
1343  */
1344  if ((table_like_clause->options &
1346  constr != NULL)
1347  {
1348  for (parent_attno = 1; parent_attno <= tupleDesc->natts;
1349  parent_attno++)
1350  {
1351  Form_pg_attribute attribute = TupleDescAttr(tupleDesc,
1352  parent_attno - 1);
1353 
1354  /*
1355  * Ignore dropped columns in the parent.
1356  */
1357  if (attribute->attisdropped)
1358  continue;
1359 
1360  /*
1361  * Copy default, if present and it should be copied. We have
1362  * separate options for plain default expressions and GENERATED
1363  * defaults.
1364  */
1365  if (attribute->atthasdef &&
1366  (attribute->attgenerated ?
1367  (table_like_clause->options & CREATE_TABLE_LIKE_GENERATED) :
1368  (table_like_clause->options & CREATE_TABLE_LIKE_DEFAULTS)))
1369  {
1370  Node *this_default;
1371  AlterTableCmd *atsubcmd;
1372  bool found_whole_row;
1373 
1374  this_default = TupleDescGetDefault(tupleDesc, parent_attno);
1375  if (this_default == NULL)
1376  elog(ERROR, "default expression not found for attribute %d of relation \"%s\"",
1377  parent_attno, RelationGetRelationName(relation));
1378 
1379  atsubcmd = makeNode(AlterTableCmd);
1380  atsubcmd->subtype = AT_CookedColumnDefault;
1381  atsubcmd->num = attmap->attnums[parent_attno - 1];
1382  atsubcmd->def = map_variable_attnos(this_default,
1383  1, 0,
1384  attmap,
1385  InvalidOid,
1386  &found_whole_row);
1387 
1388  /*
1389  * Prevent this for the same reason as for constraints below.
1390  * Note that defaults cannot contain any vars, so it's OK that
1391  * the error message refers to generated columns.
1392  */
1393  if (found_whole_row)
1394  ereport(ERROR,
1395  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1396  errmsg("cannot convert whole-row table reference"),
1397  errdetail("Generation expression for column \"%s\" contains a whole-row reference to table \"%s\".",
1398  NameStr(attribute->attname),
1399  RelationGetRelationName(relation))));
1400 
1401  atsubcmds = lappend(atsubcmds, atsubcmd);
1402  }
1403  }
1404  }
1405 
1406  /*
1407  * Copy CHECK constraints if requested, being careful to adjust attribute
1408  * numbers so they match the child.
1409  */
1410  if ((table_like_clause->options & CREATE_TABLE_LIKE_CONSTRAINTS) &&
1411  constr != NULL)
1412  {
1413  int ccnum;
1414 
1415  for (ccnum = 0; ccnum < constr->num_check; ccnum++)
1416  {
1417  char *ccname = constr->check[ccnum].ccname;
1418  char *ccbin = constr->check[ccnum].ccbin;
1419  bool ccnoinherit = constr->check[ccnum].ccnoinherit;
1420  Node *ccbin_node;
1421  bool found_whole_row;
1422  Constraint *n;
1423  AlterTableCmd *atsubcmd;
1424 
1425  ccbin_node = map_variable_attnos(stringToNode(ccbin),
1426  1, 0,
1427  attmap,
1428  InvalidOid, &found_whole_row);
1429 
1430  /*
1431  * We reject whole-row variables because the whole point of LIKE
1432  * is that the new table's rowtype might later diverge from the
1433  * parent's. So, while translation might be possible right now,
1434  * it wouldn't be possible to guarantee it would work in future.
1435  */
1436  if (found_whole_row)
1437  ereport(ERROR,
1438  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1439  errmsg("cannot convert whole-row table reference"),
1440  errdetail("Constraint \"%s\" contains a whole-row reference to table \"%s\".",
1441  ccname,
1442  RelationGetRelationName(relation))));
1443 
1444  n = makeNode(Constraint);
1445  n->contype = CONSTR_CHECK;
1446  n->conname = pstrdup(ccname);
1447  n->location = -1;
1448  n->is_no_inherit = ccnoinherit;
1449  n->raw_expr = NULL;
1450  n->cooked_expr = nodeToString(ccbin_node);
1451 
1452  /* We can skip validation, since the new table should be empty. */
1453  n->skip_validation = true;
1454  n->initially_valid = true;
1455 
1456  atsubcmd = makeNode(AlterTableCmd);
1457  atsubcmd->subtype = AT_AddConstraint;
1458  atsubcmd->def = (Node *) n;
1459  atsubcmds = lappend(atsubcmds, atsubcmd);
1460 
1461  /* Copy comment on constraint */
1462  if ((table_like_clause->options & CREATE_TABLE_LIKE_COMMENTS) &&
1464  n->conname, false),
1465  ConstraintRelationId,
1466  0)) != NULL)
1467  {
1469 
1470  stmt->objtype = OBJECT_TABCONSTRAINT;
1471  stmt->object = (Node *) list_make3(makeString(heapRel->schemaname),
1472  makeString(heapRel->relname),
1473  makeString(n->conname));
1474  stmt->comment = comment;
1475 
1476  result = lappend(result, stmt);
1477  }
1478  }
1479  }
1480 
1481  /*
1482  * Copy not-null constraints, too (these do not require any option to have
1483  * been given).
1484  */
1485  foreach(lc, RelationGetNotNullConstraints(RelationGetRelid(relation), false))
1486  {
1487  AlterTableCmd *atsubcmd;
1488 
1489  atsubcmd = makeNode(AlterTableCmd);
1490  atsubcmd->subtype = AT_AddConstraint;
1491  atsubcmd->def = (Node *) lfirst_node(Constraint, lc);
1492  atsubcmds = lappend(atsubcmds, atsubcmd);
1493  }
1494 
1495  /*
1496  * If we generated any ALTER TABLE actions above, wrap them into a single
1497  * ALTER TABLE command. Stick it at the front of the result, so it runs
1498  * before any CommentStmts we made above.
1499  */
1500  if (atsubcmds)
1501  {
1503 
1504  atcmd->relation = copyObject(heapRel);
1505  atcmd->cmds = atsubcmds;
1506  atcmd->objtype = OBJECT_TABLE;
1507  atcmd->missing_ok = false;
1508  result = lcons(atcmd, result);
1509 
1510  at_pushed = true;
1511  }
1512 
1513  /*
1514  * Process indexes if required.
1515  */
1516  if ((table_like_clause->options & CREATE_TABLE_LIKE_INDEXES) &&
1517  relation->rd_rel->relhasindex)
1518  {
1519  List *parent_indexes;
1520  ListCell *l;
1521 
1522  parent_indexes = RelationGetIndexList(relation);
1523 
1524  foreach(l, parent_indexes)
1525  {
1526  Oid parent_index_oid = lfirst_oid(l);
1527  Relation parent_index;
1528  IndexStmt *index_stmt;
1529 
1530  parent_index = index_open(parent_index_oid, AccessShareLock);
1531 
1532  /* Build CREATE INDEX statement to recreate the parent_index */
1533  index_stmt = generateClonedIndexStmt(heapRel,
1534  parent_index,
1535  attmap,
1536  NULL);
1537 
1538  /*
1539  * The PK columns might not yet non-nullable, so make sure they
1540  * become so.
1541  */
1542  if (index_stmt->primary)
1543  {
1544  foreach(lc, index_stmt->indexParams)
1545  {
1546  IndexElem *col = lfirst_node(IndexElem, lc);
1547  AlterTableCmd *notnullcmd = makeNode(AlterTableCmd);
1548 
1549  notnullcmd->subtype = AT_SetAttNotNull;
1550  notnullcmd->name = pstrdup(col->name);
1551  /* Luckily we can still add more AT-subcmds here */
1552  atsubcmds = lappend(atsubcmds, notnullcmd);
1553  }
1554 
1555  /*
1556  * If we had already put the AlterTableStmt into the output
1557  * list, we don't need to do so again; otherwise do it.
1558  */
1559  if (!at_pushed)
1560  {
1562 
1563  atcmd->relation = copyObject(heapRel);
1564  atcmd->cmds = atsubcmds;
1565  atcmd->objtype = OBJECT_TABLE;
1566  atcmd->missing_ok = false;
1567  result = lcons(atcmd, result);
1568  }
1569  }
1570 
1571  /* Copy comment on index, if requested */
1572  if (table_like_clause->options & CREATE_TABLE_LIKE_COMMENTS)
1573  {
1574  comment = GetComment(parent_index_oid, RelationRelationId, 0);
1575 
1576  /*
1577  * We make use of IndexStmt's idxcomment option, so as not to
1578  * need to know now what name the index will have.
1579  */
1580  index_stmt->idxcomment = comment;
1581  }
1582 
1583  result = lappend(result, index_stmt);
1584 
1585  index_close(parent_index, AccessShareLock);
1586  }
1587  }
1588 
1589  /* Done with child rel */
1590  table_close(childrel, NoLock);
1591 
1592  /*
1593  * Close the parent rel, but keep our AccessShareLock on it until xact
1594  * commit. That will prevent someone else from deleting or ALTERing the
1595  * parent before the child is committed.
1596  */
1597  table_close(relation, NoLock);
1598 
1599  return result;
1600 }
AttrMap * build_attrmap_by_name(TupleDesc indesc, TupleDesc outdesc, bool missing_ok)
Definition: attmap.c:178
int16 AttrNumber
Definition: attnum.h:21
#define NameStr(name)
Definition: c.h:735
#define OidIsValid(objectId)
Definition: c.h:764
char * GetComment(Oid oid, Oid classoid, int32 subid)
Definition: comment.c:410
int errdetail(const char *fmt,...)
Definition: elog.c:1208
int errcode(int sqlerrcode)
Definition: elog.c:860
int errmsg(const char *fmt,...)
Definition: elog.c:1075
#define ERROR
Definition: elog.h:39
#define ereport(elevel,...)
Definition: elog.h:149
#define stmt
Definition: indent_codes.h:59
#define comment
Definition: indent_codes.h:49
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:182
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:138
List * lappend(List *list, void *datum)
Definition: list.c:339
List * lcons(void *datum, List *list)
Definition: list.c:495
#define NoLock
Definition: lockdefs.h:34
#define AccessShareLock
Definition: lockdefs.h:36
char * pstrdup(const char *in)
Definition: mcxt.c:1619
#define copyObject(obj)
Definition: nodes.h:223
#define makeNode(_type_)
Definition: nodes.h:155
char * nodeToString(const void *obj)
Definition: outfuncs.c:762
IndexStmt * generateClonedIndexStmt(RangeVar *heapRel, Relation source_idx, const AttrMap *attmap, Oid *constraintOid)
@ CONSTR_CHECK
Definition: parsenodes.h:2544
@ OBJECT_TABLE
Definition: parsenodes.h:2137
@ OBJECT_TABCONSTRAINT
Definition: parsenodes.h:2136
@ AT_SetAttNotNull
Definition: parsenodes.h:2194
@ AT_AddConstraint
Definition: parsenodes.h:2205
@ AT_CookedColumnDefault
Definition: parsenodes.h:2191
@ CREATE_TABLE_LIKE_COMMENTS
Definition: parsenodes.h:748
@ CREATE_TABLE_LIKE_GENERATED
Definition: parsenodes.h:752
@ CREATE_TABLE_LIKE_INDEXES
Definition: parsenodes.h:754
@ CREATE_TABLE_LIKE_DEFAULTS
Definition: parsenodes.h:751
@ CREATE_TABLE_LIKE_CONSTRAINTS
Definition: parsenodes.h:750
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:209
List * RelationGetNotNullConstraints(Oid relid, bool cooked)
Oid get_relation_constraint_oid(Oid relid, const char *conname, bool missing_ok)
#define lfirst_node(type, lc)
Definition: pg_list.h:176
#define NIL
Definition: pg_list.h:68
#define list_make3(x1, x2, x3)
Definition: pg_list.h:216
#define lfirst_oid(lc)
Definition: pg_list.h:174
#define InvalidOid
Definition: postgres_ext.h:36
unsigned int Oid
Definition: postgres_ext.h:31
void * stringToNode(const char *str)
Definition: read.c:90
#define RelationGetRelid(relation)
Definition: rel.h:504
#define RelationGetDescr(relation)
Definition: rel.h:530
#define RelationGetRelationName(relation)
Definition: rel.h:538
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4755
Node * map_variable_attnos(Node *node, int target_varno, int sublevels_up, const AttrMap *attno_map, Oid to_rowtype, bool *found_whole_row)
Relation relation_openrv(const RangeVar *relation, LOCKMODE lockmode)
Definition: relation.c:138
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:48
AlterTableType subtype
Definition: parsenodes.h:2267
RangeVar * relation
Definition: parsenodes.h:2180
ObjectType objtype
Definition: parsenodes.h:2182
Definition: attmap.h:35
AttrNumber * attnums
Definition: attmap.h:36
char * ccname
Definition: tupdesc.h:30
bool ccnoinherit
Definition: tupdesc.h:33
char * ccbin
Definition: tupdesc.h:31
ConstrType contype
Definition: parsenodes.h:2570
bool is_no_inherit
Definition: parsenodes.h:2576
char * cooked_expr
Definition: parsenodes.h:2579
bool initially_valid
Definition: parsenodes.h:2575
bool skip_validation
Definition: parsenodes.h:2574
Node * raw_expr
Definition: parsenodes.h:2577
char * conname
Definition: parsenodes.h:2571
char * name
Definition: parsenodes.h:770
List * indexParams
Definition: parsenodes.h:3195
char * idxcomment
Definition: parsenodes.h:3201
bool primary
Definition: parsenodes.h:3209
Definition: pg_list.h:54
Definition: nodes.h:129
char * relname
Definition: primnodes.h:82
char * schemaname
Definition: primnodes.h:79
Form_pg_class rd_rel
Definition: rel.h:111
ConstrCheck * check
Definition: tupdesc.h:40
uint16 num_check
Definition: tupdesc.h:43
TupleConstr * constr
Definition: tupdesc.h:85
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:126
Node * TupleDescGetDefault(TupleDesc tupdesc, AttrNumber attnum)
Definition: tupdesc.c:851
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
String * makeString(char *str)
Definition: value.c:63

References AccessShareLock, AT_AddConstraint, AT_CookedColumnDefault, AT_SetAttNotNull, AttrMap::attnums, build_attrmap_by_name(), ConstrCheck::ccbin, ConstrCheck::ccname, ConstrCheck::ccnoinherit, TupleConstr::check, AlterTableStmt::cmds, comment, Constraint::conname, TupleDescData::constr, CONSTR_CHECK, Constraint::contype, Constraint::cooked_expr, copyObject, CREATE_TABLE_LIKE_COMMENTS, CREATE_TABLE_LIKE_CONSTRAINTS, CREATE_TABLE_LIKE_DEFAULTS, CREATE_TABLE_LIKE_GENERATED, CREATE_TABLE_LIKE_INDEXES, AlterTableCmd::def, elog(), ereport, errcode(), errdetail(), errmsg(), ERROR, generateClonedIndexStmt(), get_relation_constraint_oid(), GetComment(), IndexStmt::idxcomment, index_close(), index_open(), IndexStmt::indexParams, Constraint::initially_valid, InvalidOid, Constraint::is_no_inherit, lappend(), lcons(), lfirst_node, lfirst_oid, list_make3, Constraint::location, makeNode, makeString(), map_variable_attnos(), AlterTableStmt::missing_ok, IndexElem::name, AlterTableCmd::name, NameStr, TupleDescData::natts, NIL, nodeToString(), NoLock, AlterTableCmd::num, TupleConstr::num_check, OBJECT_TABCONSTRAINT, OBJECT_TABLE, AlterTableStmt::objtype, OidIsValid, TableLikeClause::options, IndexStmt::primary, pstrdup(), Constraint::raw_expr, RelationData::rd_rel, AlterTableStmt::relation, relation_open(), relation_openrv(), RelationGetDescr, RelationGetIndexList(), RelationGetNotNullConstraints(), RelationGetRelationName, RelationGetRelid, TableLikeClause::relationOid, RangeVar::relname, RangeVar::schemaname, Constraint::skip_validation, stmt, stringToNode(), AlterTableCmd::subtype, table_close(), TupleDescAttr, and TupleDescGetDefault().

Referenced by ProcessUtilitySlow().

◆ generateClonedIndexStmt()

IndexStmt* generateClonedIndexStmt ( RangeVar heapRel,
Relation  source_idx,
const struct AttrMap attmap,
Oid constraintOid 
)

◆ transformAlterTableStmt()

AlterTableStmt* transformAlterTableStmt ( Oid  relid,
AlterTableStmt stmt,
const char *  queryString,
List **  beforeStmts,
List **  afterStmts 
)

Definition at line 3429 of file parse_utilcmd.c.

3432 {
3433  Relation rel;
3434  TupleDesc tupdesc;
3435  ParseState *pstate;
3436  CreateStmtContext cxt;
3437  List *save_alist;
3438  ListCell *lcmd,
3439  *l;
3440  List *newcmds = NIL;
3441  bool skipValidation = true;
3442  AlterTableCmd *newcmd;
3443  ParseNamespaceItem *nsitem;
3444 
3445  /* Caller is responsible for locking the relation */
3446  rel = relation_open(relid, NoLock);
3447  tupdesc = RelationGetDescr(rel);
3448 
3449  /* Set up pstate */
3450  pstate = make_parsestate(NULL);
3451  pstate->p_sourcetext = queryString;
3452  nsitem = addRangeTableEntryForRelation(pstate,
3453  rel,
3455  NULL,
3456  false,
3457  true);
3458  addNSItemToQuery(pstate, nsitem, false, true, true);
3459 
3460  /* Set up CreateStmtContext */
3461  cxt.pstate = pstate;
3462  if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
3463  {
3464  cxt.stmtType = "ALTER FOREIGN TABLE";
3465  cxt.isforeign = true;
3466  }
3467  else
3468  {
3469  cxt.stmtType = "ALTER TABLE";
3470  cxt.isforeign = false;
3471  }
3472  cxt.relation = stmt->relation;
3473  cxt.rel = rel;
3474  cxt.inhRelations = NIL;
3475  cxt.isalter = true;
3476  cxt.columns = NIL;
3477  cxt.ckconstraints = NIL;
3478  cxt.nnconstraints = NIL;
3479  cxt.fkconstraints = NIL;
3480  cxt.ixconstraints = NIL;
3481  cxt.likeclauses = NIL;
3482  cxt.extstats = NIL;
3483  cxt.blist = NIL;
3484  cxt.alist = NIL;
3485  cxt.pkey = NULL;
3486  cxt.ispartitioned = (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
3487  cxt.partbound = NULL;
3488  cxt.ofType = false;
3489 
3490  /*
3491  * Transform ALTER subcommands that need it (most don't). These largely
3492  * re-use code from CREATE TABLE.
3493  */
3494  foreach(lcmd, stmt->cmds)
3495  {
3496  AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
3497 
3498  switch (cmd->subtype)
3499  {
3500  case AT_AddColumn:
3501  {
3502  ColumnDef *def = castNode(ColumnDef, cmd->def);
3503 
3504  transformColumnDefinition(&cxt, def);
3505 
3506  /*
3507  * If the column has a non-null default, we can't skip
3508  * validation of foreign keys.
3509  */
3510  if (def->raw_default != NULL)
3511  skipValidation = false;
3512 
3513  /*
3514  * All constraints are processed in other ways. Remove the
3515  * original list
3516  */
3517  def->constraints = NIL;
3518 
3519  newcmds = lappend(newcmds, cmd);
3520  break;
3521  }
3522 
3523  case AT_AddConstraint:
3524 
3525  /*
3526  * The original AddConstraint cmd node doesn't go to newcmds
3527  */
3528  if (IsA(cmd->def, Constraint))
3529  {
3530  transformTableConstraint(&cxt, (Constraint *) cmd->def);
3531  if (((Constraint *) cmd->def)->contype == CONSTR_FOREIGN)
3532  skipValidation = false;
3533  }
3534  else
3535  elog(ERROR, "unrecognized node type: %d",
3536  (int) nodeTag(cmd->def));
3537  break;
3538 
3539  case AT_AlterColumnType:
3540  {
3541  ColumnDef *def = castNode(ColumnDef, cmd->def);
3543 
3544  /*
3545  * For ALTER COLUMN TYPE, transform the USING clause if
3546  * one was specified.
3547  */
3548  if (def->raw_default)
3549  {
3550  def->cooked_default =
3551  transformExpr(pstate, def->raw_default,
3553  }
3554 
3555  /*
3556  * For identity column, create ALTER SEQUENCE command to
3557  * change the data type of the sequence.
3558  */
3559  attnum = get_attnum(relid, cmd->name);
3560  if (attnum == InvalidAttrNumber)
3561  ereport(ERROR,
3562  (errcode(ERRCODE_UNDEFINED_COLUMN),
3563  errmsg("column \"%s\" of relation \"%s\" does not exist",
3564  cmd->name, RelationGetRelationName(rel))));
3565 
3566  if (attnum > 0 &&
3567  TupleDescAttr(tupdesc, attnum - 1)->attidentity)
3568  {
3569  Oid seq_relid = getIdentitySequence(relid, attnum, false);
3570  Oid typeOid = typenameTypeId(pstate, def->typeName);
3571  AlterSeqStmt *altseqstmt = makeNode(AlterSeqStmt);
3572 
3573  altseqstmt->sequence = makeRangeVar(get_namespace_name(get_rel_namespace(seq_relid)),
3574  get_rel_name(seq_relid),
3575  -1);
3576  altseqstmt->options = list_make1(makeDefElem("as", (Node *) makeTypeNameFromOid(typeOid, -1), -1));
3577  altseqstmt->for_identity = true;
3578  cxt.blist = lappend(cxt.blist, altseqstmt);
3579  }
3580 
3581  newcmds = lappend(newcmds, cmd);
3582  break;
3583  }
3584 
3585  case AT_AddIdentity:
3586  {
3587  Constraint *def = castNode(Constraint, cmd->def);
3588  ColumnDef *newdef = makeNode(ColumnDef);
3590 
3591  newdef->colname = cmd->name;
3592  newdef->identity = def->generated_when;
3593  cmd->def = (Node *) newdef;
3594 
3595  attnum = get_attnum(relid, cmd->name);
3596  if (attnum == InvalidAttrNumber)
3597  ereport(ERROR,
3598  (errcode(ERRCODE_UNDEFINED_COLUMN),
3599  errmsg("column \"%s\" of relation \"%s\" does not exist",
3600  cmd->name, RelationGetRelationName(rel))));
3601 
3602  generateSerialExtraStmts(&cxt, newdef,
3603  get_atttype(relid, attnum),
3604  def->options, true, true,
3605  NULL, NULL);
3606 
3607  newcmds = lappend(newcmds, cmd);
3608  break;
3609  }
3610 
3611  case AT_SetIdentity:
3612  {
3613  /*
3614  * Create an ALTER SEQUENCE statement for the internal
3615  * sequence of the identity column.
3616  */
3617  ListCell *lc;
3618  List *newseqopts = NIL;
3619  List *newdef = NIL;
3621  Oid seq_relid;
3622 
3623  /*
3624  * Split options into those handled by ALTER SEQUENCE and
3625  * those for ALTER TABLE proper.
3626  */
3627  foreach(lc, castNode(List, cmd->def))
3628  {
3629  DefElem *def = lfirst_node(DefElem, lc);
3630 
3631  if (strcmp(def->defname, "generated") == 0)
3632  newdef = lappend(newdef, def);
3633  else
3634  newseqopts = lappend(newseqopts, def);
3635  }
3636 
3637  attnum = get_attnum(relid, cmd->name);
3638  if (attnum == InvalidAttrNumber)
3639  ereport(ERROR,
3640  (errcode(ERRCODE_UNDEFINED_COLUMN),
3641  errmsg("column \"%s\" of relation \"%s\" does not exist",
3642  cmd->name, RelationGetRelationName(rel))));
3643 
3644  seq_relid = getIdentitySequence(relid, attnum, true);
3645 
3646  if (seq_relid)
3647  {
3648  AlterSeqStmt *seqstmt;
3649 
3650  seqstmt = makeNode(AlterSeqStmt);
3652  get_rel_name(seq_relid), -1);
3653  seqstmt->options = newseqopts;
3654  seqstmt->for_identity = true;
3655  seqstmt->missing_ok = false;
3656 
3657  cxt.blist = lappend(cxt.blist, seqstmt);
3658  }
3659 
3660  /*
3661  * If column was not an identity column, we just let the
3662  * ALTER TABLE command error out later. (There are cases
3663  * this fails to cover, but we'll need to restructure
3664  * where creation of the sequence dependency linkage
3665  * happens before we can fix it.)
3666  */
3667 
3668  cmd->def = (Node *) newdef;
3669  newcmds = lappend(newcmds, cmd);
3670  break;
3671  }
3672 
3673  case AT_AttachPartition:
3674  case AT_DetachPartition:
3675  {
3676  PartitionCmd *partcmd = (PartitionCmd *) cmd->def;
3677 
3678  transformPartitionCmd(&cxt, partcmd);
3679  /* assign transformed value of the partition bound */
3680  partcmd->bound = cxt.partbound;
3681  }
3682 
3683  newcmds = lappend(newcmds, cmd);
3684  break;
3685 
3686  default:
3687 
3688  /*
3689  * Currently, we shouldn't actually get here for subcommand
3690  * types that don't require transformation; but if we do, just
3691  * emit them unchanged.
3692  */
3693  newcmds = lappend(newcmds, cmd);
3694  break;
3695  }
3696  }
3697 
3698  /*
3699  * Transfer anything we already have in cxt.alist into save_alist, to keep
3700  * it separate from the output of transformIndexConstraints.
3701  */
3702  save_alist = cxt.alist;
3703  cxt.alist = NIL;
3704 
3705  /* Postprocess constraints */
3707  transformFKConstraints(&cxt, skipValidation, true);
3708  transformCheckConstraints(&cxt, false);
3709 
3710  /*
3711  * Push any index-creation commands into the ALTER, so that they can be
3712  * scheduled nicely by tablecmds.c. Note that tablecmds.c assumes that
3713  * the IndexStmt attached to an AT_AddIndex or AT_AddIndexConstraint
3714  * subcommand has already been through transformIndexStmt.
3715  */
3716  foreach(l, cxt.alist)
3717  {
3718  Node *istmt = (Node *) lfirst(l);
3719 
3720  /*
3721  * We assume here that cxt.alist contains only IndexStmts and possibly
3722  * AT_SetAttNotNull statements generated from primary key constraints.
3723  * We absorb the subcommands of the latter directly.
3724  */
3725  if (IsA(istmt, IndexStmt))
3726  {
3727  IndexStmt *idxstmt = (IndexStmt *) istmt;
3728 
3729  idxstmt = transformIndexStmt(relid, idxstmt, queryString);
3730  newcmd = makeNode(AlterTableCmd);
3732  newcmd->def = (Node *) idxstmt;
3733  newcmds = lappend(newcmds, newcmd);
3734  }
3735  else if (IsA(istmt, AlterTableStmt))
3736  {
3737  AlterTableStmt *alterstmt = (AlterTableStmt *) istmt;
3738 
3739  newcmds = list_concat(newcmds, alterstmt->cmds);
3740  }
3741  else
3742  elog(ERROR, "unexpected stmt type %d", (int) nodeTag(istmt));
3743  }
3744  cxt.alist = NIL;
3745 
3746  /* Append any CHECK, NOT NULL or FK constraints to the commands list */
3747  foreach(l, cxt.ckconstraints)
3748  {
3749  newcmd = makeNode(AlterTableCmd);
3750  newcmd->subtype = AT_AddConstraint;
3751  newcmd->def = (Node *) lfirst_node(Constraint, l);
3752  newcmds = lappend(newcmds, newcmd);
3753  }
3754  foreach(l, cxt.nnconstraints)
3755  {
3756  newcmd = makeNode(AlterTableCmd);
3757  newcmd->subtype = AT_AddConstraint;
3758  newcmd->def = (Node *) lfirst_node(Constraint, l);
3759  newcmds = lappend(newcmds, newcmd);
3760  }
3761  foreach(l, cxt.fkconstraints)
3762  {
3763  newcmd = makeNode(AlterTableCmd);
3764  newcmd->subtype = AT_AddConstraint;
3765  newcmd->def = (Node *) lfirst_node(Constraint, l);
3766  newcmds = lappend(newcmds, newcmd);
3767  }
3768 
3769  /* Append extended statistics objects */
3771 
3772  /* Close rel */
3773  relation_close(rel, NoLock);
3774 
3775  /*
3776  * Output results.
3777  */
3778  stmt->cmds = newcmds;
3779 
3780  *beforeStmts = cxt.blist;
3781  *afterStmts = list_concat(cxt.alist, save_alist);
3782 
3783  return stmt;
3784 }
#define InvalidAttrNumber
Definition: attnum.h:23
List * list_concat(List *list1, const List *list2)
Definition: list.c:561
AttrNumber get_attnum(Oid relid, const char *attname)
Definition: lsyscache.c:857
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3321
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:1929
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1905
Oid get_atttype(Oid relid, AttrNumber attnum)
Definition: lsyscache.c:912
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition: makefuncs.c:425
DefElem * makeDefElem(char *name, Node *arg, int location)
Definition: makefuncs.c:549
TypeName * makeTypeNameFromOid(Oid typeOid, int32 typmod)
Definition: makefuncs.c:475
#define IsA(nodeptr, _type_)
Definition: nodes.h:158
#define nodeTag(nodeptr)
Definition: nodes.h:133
#define castNode(_type_, nodeptr)
Definition: nodes.h:176
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:110
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:44
@ EXPR_KIND_ALTER_COL_TRANSFORM
Definition: parse_node.h:74
ParseNamespaceItem * addRangeTableEntryForRelation(ParseState *pstate, Relation rel, int lockmode, Alias *alias, bool inh, bool inFromCl)
void addNSItemToQuery(ParseState *pstate, ParseNamespaceItem *nsitem, bool addToJoinList, bool addToRelNameSpace, bool addToVarNameSpace)
Oid typenameTypeId(ParseState *pstate, const TypeName *typeName)
Definition: parse_type.c:291
static void generateSerialExtraStmts(CreateStmtContext *cxt, ColumnDef *column, Oid seqtypid, List *seqoptions, bool for_identity, bool col_exists, char **snamespace_p, char **sname_p)
static void transformColumnDefinition(CreateStmtContext *cxt, ColumnDef *column)
static void transformIndexConstraints(CreateStmtContext *cxt)
static void transformExtendedStatistics(CreateStmtContext *cxt)
static void transformTableConstraint(CreateStmtContext *cxt, Constraint *constraint)
IndexStmt * transformIndexStmt(Oid relid, IndexStmt *stmt, const char *queryString)
static void transformPartitionCmd(CreateStmtContext *cxt, PartitionCmd *cmd)
static void transformCheckConstraints(CreateStmtContext *cxt, bool skipValidation)
static void transformFKConstraints(CreateStmtContext *cxt, bool skipValidation, bool isAddConstraint)
@ CONSTR_FOREIGN
Definition: parsenodes.h:2548
@ AT_AddIndexConstraint
Definition: parsenodes.h:2210
@ AT_SetIdentity
Definition: parsenodes.h:2252
@ AT_AddIndex
Definition: parsenodes.h:2203
@ AT_AddIdentity
Definition: parsenodes.h:2251
@ AT_AlterColumnType
Definition: parsenodes.h:2213
@ AT_DetachPartition
Definition: parsenodes.h:2249
@ AT_AttachPartition
Definition: parsenodes.h:2248
@ AT_AddColumn
Definition: parsenodes.h:2188
int16 attnum
Definition: pg_attribute.h:74
Oid getIdentitySequence(Oid relid, AttrNumber attnum, bool missing_ok)
Definition: pg_depend.c:944
#define lfirst(lc)
Definition: pg_list.h:172
#define list_make1(x1)
Definition: pg_list.h:212
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:206
List * options
Definition: parsenodes.h:2971
RangeVar * sequence
Definition: parsenodes.h:2970
bool for_identity
Definition: parsenodes.h:2972
char identity
Definition: parsenodes.h:724
List * constraints
Definition: parsenodes.h:730
Node * cooked_default
Definition: parsenodes.h:723
char * colname
Definition: parsenodes.h:713
TypeName * typeName
Definition: parsenodes.h:714
Node * raw_default
Definition: parsenodes.h:722
List * options
Definition: parsenodes.h:2592
char generated_when
Definition: parsenodes.h:2581
IndexStmt * pkey
Definition: parse_utilcmd.c:93
const char * stmtType
Definition: parse_utilcmd.c:76
RangeVar * relation
Definition: parse_utilcmd.c:77
ParseState * pstate
Definition: parse_utilcmd.c:75
PartitionBoundSpec * partbound
Definition: parse_utilcmd.c:95
char * defname
Definition: parsenodes.h:802
Oid indexOid
Definition: parsenodes.h:3202
const char * p_sourcetext
Definition: parse_node.h:192
PartitionBoundSpec * bound
Definition: parsenodes.h:934

References AccessShareLock, addNSItemToQuery(), addRangeTableEntryForRelation(), CreateStmtContext::alist, AT_AddColumn, AT_AddConstraint, AT_AddIdentity, AT_AddIndex, AT_AddIndexConstraint, AT_AlterColumnType, AT_AttachPartition, AT_DetachPartition, AT_SetIdentity, attnum, CreateStmtContext::blist, PartitionCmd::bound, castNode, CreateStmtContext::ckconstraints, AlterTableStmt::cmds, ColumnDef::colname, CreateStmtContext::columns, CONSTR_FOREIGN, ColumnDef::constraints, ColumnDef::cooked_default, AlterTableCmd::def, DefElem::defname, elog(), ereport, errcode(), errmsg(), ERROR, EXPR_KIND_ALTER_COL_TRANSFORM, CreateStmtContext::extstats, CreateStmtContext::fkconstraints, AlterSeqStmt::for_identity, Constraint::generated_when, generateSerialExtraStmts(), get_attnum(), get_atttype(), get_namespace_name(), get_rel_name(), get_rel_namespace(), getIdentitySequence(), ColumnDef::identity, IndexStmt::indexOid, CreateStmtContext::inhRelations, InvalidAttrNumber, IsA, CreateStmtContext::isalter, CreateStmtContext::isforeign, CreateStmtContext::ispartitioned, CreateStmtContext::ixconstraints, lappend(), lfirst, lfirst_node, CreateStmtContext::likeclauses, list_concat(), list_make1, make_parsestate(), makeDefElem(), makeNode, makeRangeVar(), makeTypeNameFromOid(), AlterSeqStmt::missing_ok, AlterTableCmd::name, NIL, CreateStmtContext::nnconstraints, nodeTag, NoLock, CreateStmtContext::ofType, OidIsValid, Constraint::options, AlterSeqStmt::options, ParseState::p_sourcetext, CreateStmtContext::partbound, CreateStmtContext::pkey, CreateStmtContext::pstate, ColumnDef::raw_default, RelationData::rd_rel, CreateStmtContext::rel, CreateStmtContext::relation, relation_close(), relation_open(), RelationGetDescr, RelationGetRelationName, AlterSeqStmt::sequence, stmt, CreateStmtContext::stmtType, AlterTableCmd::subtype, transformCheckConstraints(), transformColumnDefinition(), transformExpr(), transformExtendedStatistics(), transformFKConstraints(), transformIndexConstraints(), transformIndexStmt(), transformPartitionCmd(), transformTableConstraint(), TupleDescAttr, ColumnDef::typeName, and typenameTypeId().

Referenced by ATParseTransformCmd(), and ATPostAlterTypeParse().

◆ transformCreateSchemaStmtElements()

List* transformCreateSchemaStmtElements ( List schemaElts,
const char *  schemaName 
)

Definition at line 3969 of file parse_utilcmd.c.

3970 {
3972  List *result;
3973  ListCell *elements;
3974 
3975  cxt.schemaname = schemaName;
3976  cxt.sequences = NIL;
3977  cxt.tables = NIL;
3978  cxt.views = NIL;
3979  cxt.indexes = NIL;
3980  cxt.triggers = NIL;
3981  cxt.grants = NIL;
3982 
3983  /*
3984  * Run through each schema element in the schema element list. Separate
3985  * statements by type, and do preliminary analysis.
3986  */
3987  foreach(elements, schemaElts)
3988  {
3989  Node *element = lfirst(elements);
3990 
3991  switch (nodeTag(element))
3992  {
3993  case T_CreateSeqStmt:
3994  {
3995  CreateSeqStmt *elp = (CreateSeqStmt *) element;
3996 
3998  cxt.sequences = lappend(cxt.sequences, element);
3999  }
4000  break;
4001 
4002  case T_CreateStmt:
4003  {
4004  CreateStmt *elp = (CreateStmt *) element;
4005 
4007 
4008  /*
4009  * XXX todo: deal with constraints
4010  */
4011  cxt.tables = lappend(cxt.tables, element);
4012  }
4013  break;
4014 
4015  case T_ViewStmt:
4016  {
4017  ViewStmt *elp = (ViewStmt *) element;
4018 
4019  setSchemaName(cxt.schemaname, &elp->view->schemaname);
4020 
4021  /*
4022  * XXX todo: deal with references between views
4023  */
4024  cxt.views = lappend(cxt.views, element);
4025  }
4026  break;
4027 
4028  case T_IndexStmt:
4029  {
4030  IndexStmt *elp = (IndexStmt *) element;
4031 
4033  cxt.indexes = lappend(cxt.indexes, element);
4034  }
4035  break;
4036 
4037  case T_CreateTrigStmt:
4038  {
4040 
4042  cxt.triggers = lappend(cxt.triggers, element);
4043  }
4044  break;
4045 
4046  case T_GrantStmt:
4047  cxt.grants = lappend(cxt.grants, element);
4048  break;
4049 
4050  default:
4051  elog(ERROR, "unrecognized node type: %d",
4052  (int) nodeTag(element));
4053  }
4054  }
4055 
4056  result = NIL;
4057  result = list_concat(result, cxt.sequences);
4058  result = list_concat(result, cxt.tables);
4059  result = list_concat(result, cxt.views);
4060  result = list_concat(result, cxt.indexes);
4061  result = list_concat(result, cxt.triggers);
4062  result = list_concat(result, cxt.grants);
4063 
4064  return result;
4065 }
static void setSchemaName(const char *context_schema, char **stmt_schema_name)
static chr element(struct vars *v, const chr *startp, const chr *endp)
Definition: regc_locale.c:376
RangeVar * sequence
Definition: parsenodes.h:2960
RangeVar * relation
Definition: parsenodes.h:2489
RangeVar * relation
Definition: parsenodes.h:2847
RangeVar * relation
Definition: parsenodes.h:3192
RangeVar * view
Definition: parsenodes.h:3584

References element(), elog(), ERROR, CreateSchemaStmtContext::grants, CreateSchemaStmtContext::indexes, lappend(), lfirst, list_concat(), NIL, nodeTag, CreateStmt::relation, CreateTrigStmt::relation, IndexStmt::relation, CreateSchemaStmtContext::schemaname, RangeVar::schemaname, CreateSeqStmt::sequence, CreateSchemaStmtContext::sequences, setSchemaName(), CreateSchemaStmtContext::tables, CreateSchemaStmtContext::triggers, ViewStmt::view, and CreateSchemaStmtContext::views.

Referenced by CreateSchemaCommand().

◆ transformCreateStmt()

List* transformCreateStmt ( CreateStmt stmt,
const char *  queryString 
)

Definition at line 164 of file parse_utilcmd.c.

165 {
166  ParseState *pstate;
167  CreateStmtContext cxt;
168  List *result;
169  List *save_alist;
170  ListCell *elements;
171  Oid namespaceid;
172  Oid existing_relid;
173  ParseCallbackState pcbstate;
174 
175  /* Set up pstate */
176  pstate = make_parsestate(NULL);
177  pstate->p_sourcetext = queryString;
178 
179  /*
180  * Look up the creation namespace. This also checks permissions on the
181  * target namespace, locks it against concurrent drops, checks for a
182  * preexisting relation in that namespace with the same name, and updates
183  * stmt->relation->relpersistence if the selected namespace is temporary.
184  */
185  setup_parser_errposition_callback(&pcbstate, pstate,
186  stmt->relation->location);
187  namespaceid =
189  &existing_relid);
191 
192  /*
193  * If the relation already exists and the user specified "IF NOT EXISTS",
194  * bail out with a NOTICE.
195  */
196  if (stmt->if_not_exists && OidIsValid(existing_relid))
197  {
198  /*
199  * If we are in an extension script, insist that the pre-existing
200  * object be a member of the extension, to avoid security risks.
201  */
202  ObjectAddress address;
203 
204  ObjectAddressSet(address, RelationRelationId, existing_relid);
206 
207  /* OK to skip */
208  ereport(NOTICE,
209  (errcode(ERRCODE_DUPLICATE_TABLE),
210  errmsg("relation \"%s\" already exists, skipping",
211  stmt->relation->relname)));
212  return NIL;
213  }
214 
215  /*
216  * If the target relation name isn't schema-qualified, make it so. This
217  * prevents some corner cases in which added-on rewritten commands might
218  * think they should apply to other relations that have the same name and
219  * are earlier in the search path. But a local temp table is effectively
220  * specified to be in pg_temp, so no need for anything extra in that case.
221  */
222  if (stmt->relation->schemaname == NULL
223  && stmt->relation->relpersistence != RELPERSISTENCE_TEMP)
224  stmt->relation->schemaname = get_namespace_name(namespaceid);
225 
226  /* Set up CreateStmtContext */
227  cxt.pstate = pstate;
229  {
230  cxt.stmtType = "CREATE FOREIGN TABLE";
231  cxt.isforeign = true;
232  }
233  else
234  {
235  cxt.stmtType = "CREATE TABLE";
236  cxt.isforeign = false;
237  }
238  cxt.relation = stmt->relation;
239  cxt.rel = NULL;
240  cxt.inhRelations = stmt->inhRelations;
241  cxt.isalter = false;
242  cxt.columns = NIL;
243  cxt.ckconstraints = NIL;
244  cxt.nnconstraints = NIL;
245  cxt.fkconstraints = NIL;
246  cxt.ixconstraints = NIL;
247  cxt.likeclauses = NIL;
248  cxt.extstats = NIL;
249  cxt.blist = NIL;
250  cxt.alist = NIL;
251  cxt.pkey = NULL;
252  cxt.ispartitioned = stmt->partspec != NULL;
253  cxt.partbound = stmt->partbound;
254  cxt.ofType = (stmt->ofTypename != NULL);
255 
256  Assert(!stmt->ofTypename || !stmt->inhRelations); /* grammar enforces */
257 
258  if (stmt->ofTypename)
259  transformOfType(&cxt, stmt->ofTypename);
260 
261  if (stmt->partspec)
262  {
263  if (stmt->inhRelations && !stmt->partbound)
264  ereport(ERROR,
265  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
266  errmsg("cannot create partitioned table as inheritance child")));
267  }
268 
269  /*
270  * Run through each primary element in the table creation clause. Separate
271  * column defs from constraints, and do preliminary analysis.
272  */
273  foreach(elements, stmt->tableElts)
274  {
275  Node *element = lfirst(elements);
276 
277  switch (nodeTag(element))
278  {
279  case T_ColumnDef:
281  break;
282 
283  case T_Constraint:
285  break;
286 
287  case T_TableLikeClause:
289  break;
290 
291  default:
292  elog(ERROR, "unrecognized node type: %d",
293  (int) nodeTag(element));
294  break;
295  }
296  }
297 
298  /*
299  * Transfer anything we already have in cxt.alist into save_alist, to keep
300  * it separate from the output of transformIndexConstraints. (This may
301  * not be necessary anymore, but we'll keep doing it to preserve the
302  * historical order of execution of the alist commands.)
303  */
304  save_alist = cxt.alist;
305  cxt.alist = NIL;
306 
307  Assert(stmt->constraints == NIL);
308 
309  /*
310  * Postprocess constraints that give rise to index definitions.
311  */
313 
314  /*
315  * Re-consideration of LIKE clauses should happen after creation of
316  * indexes, but before creation of foreign keys. This order is critical
317  * because a LIKE clause may attempt to create a primary key. If there's
318  * also a pkey in the main CREATE TABLE list, creation of that will not
319  * check for a duplicate at runtime (since index_check_primary_key()
320  * expects that we rejected dups here). Creation of the LIKE-generated
321  * pkey behaves like ALTER TABLE ADD, so it will check, but obviously that
322  * only works if it happens second. On the other hand, we want to make
323  * pkeys before foreign key constraints, in case the user tries to make a
324  * self-referential FK.
325  */
326  cxt.alist = list_concat(cxt.alist, cxt.likeclauses);
327 
328  /*
329  * Postprocess foreign-key constraints.
330  */
331  transformFKConstraints(&cxt, true, false);
332 
333  /*
334  * Postprocess check constraints.
335  *
336  * For regular tables all constraints can be marked valid immediately,
337  * because the table is new therefore empty. Not so for foreign tables.
338  */
340 
341  /*
342  * Postprocess extended statistics.
343  */
345 
346  /*
347  * Output results.
348  */
349  stmt->tableElts = cxt.columns;
350  stmt->constraints = cxt.ckconstraints;
351  stmt->nnconstraints = cxt.nnconstraints;
352 
353  result = lappend(cxt.blist, stmt);
354  result = list_concat(result, cxt.alist);
355  result = list_concat(result, save_alist);
356 
357  return result;
358 }
#define NOTICE
Definition: elog.h:35
Assert(fmt[strlen(fmt) - 1] !='\n')
Oid RangeVarGetAndCheckCreationNamespace(RangeVar *relation, LOCKMODE lockmode, Oid *existing_relation_id)
Definition: namespace.c:724
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
void cancel_parser_errposition_callback(ParseCallbackState *pcbstate)
Definition: parse_node.c:161
void setup_parser_errposition_callback(ParseCallbackState *pcbstate, ParseState *pstate, int location)
Definition: parse_node.c:145
static void transformTableLikeClause(CreateStmtContext *cxt, TableLikeClause *table_like_clause)
static void transformOfType(CreateStmtContext *cxt, TypeName *ofTypename)
void checkMembershipInCurrentExtension(const ObjectAddress *object)
Definition: pg_depend.c:257

References CreateStmtContext::alist, Assert(), CreateStmtContext::blist, cancel_parser_errposition_callback(), checkMembershipInCurrentExtension(), CreateStmtContext::ckconstraints, CreateStmtContext::columns, element(), elog(), ereport, errcode(), errmsg(), ERROR, CreateStmtContext::extstats, CreateStmtContext::fkconstraints, get_namespace_name(), CreateStmtContext::inhRelations, IsA, CreateStmtContext::isalter, CreateStmtContext::isforeign, CreateStmtContext::ispartitioned, CreateStmtContext::ixconstraints, lappend(), lfirst, CreateStmtContext::likeclauses, list_concat(), make_parsestate(), NIL, CreateStmtContext::nnconstraints, nodeTag, NoLock, NOTICE, ObjectAddressSet, CreateStmtContext::ofType, OidIsValid, ParseState::p_sourcetext, CreateStmtContext::partbound, CreateStmtContext::pkey, CreateStmtContext::pstate, RangeVarGetAndCheckCreationNamespace(), CreateStmtContext::rel, CreateStmtContext::relation, setup_parser_errposition_callback(), stmt, CreateStmtContext::stmtType, transformCheckConstraints(), transformColumnDefinition(), transformExtendedStatistics(), transformFKConstraints(), transformIndexConstraints(), transformOfType(), transformTableConstraint(), and transformTableLikeClause().

Referenced by ProcessUtilitySlow().

◆ transformIndexStmt()

IndexStmt* transformIndexStmt ( Oid  relid,
IndexStmt stmt,
const char *  queryString 
)

Definition at line 2953 of file parse_utilcmd.c.

2954 {
2955  ParseState *pstate;
2956  ParseNamespaceItem *nsitem;
2957  ListCell *l;
2958  Relation rel;
2959 
2960  /* Nothing to do if statement already transformed. */
2961  if (stmt->transformed)
2962  return stmt;
2963 
2964  /* Set up pstate */
2965  pstate = make_parsestate(NULL);
2966  pstate->p_sourcetext = queryString;
2967 
2968  /*
2969  * Put the parent table into the rtable so that the expressions can refer
2970  * to its fields without qualification. Caller is responsible for locking
2971  * relation, but we still need to open it.
2972  */
2973  rel = relation_open(relid, NoLock);
2974  nsitem = addRangeTableEntryForRelation(pstate, rel,
2976  NULL, false, true);
2977 
2978  /* no to join list, yes to namespaces */
2979  addNSItemToQuery(pstate, nsitem, false, true, true);
2980 
2981  /* take care of the where clause */
2982  if (stmt->whereClause)
2983  {
2984  stmt->whereClause = transformWhereClause(pstate,
2985  stmt->whereClause,
2987  "WHERE");
2988  /* we have to fix its collations too */
2989  assign_expr_collations(pstate, stmt->whereClause);
2990  }
2991 
2992  /* take care of any index expressions */
2993  foreach(l, stmt->indexParams)
2994  {
2995  IndexElem *ielem = (IndexElem *) lfirst(l);
2996 
2997  if (ielem->expr)
2998  {
2999  /* Extract preliminary index col name before transforming expr */
3000  if (ielem->indexcolname == NULL)
3001  ielem->indexcolname = FigureIndexColname(ielem->expr);
3002 
3003  /* Now do parse transformation of the expression */
3004  ielem->expr = transformExpr(pstate, ielem->expr,
3006 
3007  /* We have to fix its collations too */
3008  assign_expr_collations(pstate, ielem->expr);
3009 
3010  /*
3011  * transformExpr() should have already rejected subqueries,
3012  * aggregates, window functions, and SRFs, based on the EXPR_KIND_
3013  * for an index expression.
3014  *
3015  * DefineIndex() will make more checks.
3016  */
3017  }
3018  }
3019 
3020  /*
3021  * Check that only the base rel is mentioned. (This should be dead code
3022  * now that add_missing_from is history.)
3023  */
3024  if (list_length(pstate->p_rtable) != 1)
3025  ereport(ERROR,
3026  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
3027  errmsg("index expressions and predicates can refer only to the table being indexed")));
3028 
3029  free_parsestate(pstate);
3030 
3031  /* Close relation */
3032  table_close(rel, NoLock);
3033 
3034  /* Mark statement as successfully transformed */
3035  stmt->transformed = true;
3036 
3037  return stmt;
3038 }
Node * transformWhereClause(ParseState *pstate, Node *clause, ParseExprKind exprKind, const char *constructName)
void assign_expr_collations(ParseState *pstate, Node *expr)
void free_parsestate(ParseState *pstate)
Definition: parse_node.c:77
@ EXPR_KIND_INDEX_EXPRESSION
Definition: parse_node.h:71
@ EXPR_KIND_INDEX_PREDICATE
Definition: parse_node.h:72
char * FigureIndexColname(Node *node)
static int list_length(const List *l)
Definition: pg_list.h:152
Node * expr
Definition: parsenodes.h:771
char * indexcolname
Definition: parsenodes.h:772
List * p_rtable
Definition: parse_node.h:193

References AccessShareLock, addNSItemToQuery(), addRangeTableEntryForRelation(), assign_expr_collations(), ereport, errcode(), errmsg(), ERROR, IndexElem::expr, EXPR_KIND_INDEX_EXPRESSION, EXPR_KIND_INDEX_PREDICATE, FigureIndexColname(), free_parsestate(), IndexElem::indexcolname, lfirst, list_length(), make_parsestate(), NoLock, ParseState::p_rtable, ParseState::p_sourcetext, relation_open(), stmt, table_close(), transformExpr(), and transformWhereClause().

Referenced by ATPostAlterTypeParse(), ProcessUtilitySlow(), and transformAlterTableStmt().

◆ transformPartitionBound()

PartitionBoundSpec* transformPartitionBound ( ParseState pstate,
Relation  parent,
PartitionBoundSpec spec 
)

Definition at line 4145 of file parse_utilcmd.c.

4147 {
4148  PartitionBoundSpec *result_spec;
4150  char strategy = get_partition_strategy(key);
4151  int partnatts = get_partition_natts(key);
4152  List *partexprs = get_partition_exprs(key);
4153 
4154  /* Avoid scribbling on input */
4155  result_spec = copyObject(spec);
4156 
4157  if (spec->is_default)
4158  {
4159  /*
4160  * Hash partitioning does not support a default partition; there's no
4161  * use case for it (since the set of partitions to create is perfectly
4162  * defined), and if users do get into it accidentally, it's hard to
4163  * back out from it afterwards.
4164  */
4165  if (strategy == PARTITION_STRATEGY_HASH)
4166  ereport(ERROR,
4167  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4168  errmsg("a hash-partitioned table may not have a default partition")));
4169 
4170  /*
4171  * In case of the default partition, parser had no way to identify the
4172  * partition strategy. Assign the parent's strategy to the default
4173  * partition bound spec.
4174  */
4175  result_spec->strategy = strategy;
4176 
4177  return result_spec;
4178  }
4179 
4180  if (strategy == PARTITION_STRATEGY_HASH)
4181  {
4182  if (spec->strategy != PARTITION_STRATEGY_HASH)
4183  ereport(ERROR,
4184  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4185  errmsg("invalid bound specification for a hash partition"),
4186  parser_errposition(pstate, exprLocation((Node *) spec))));
4187 
4188  if (spec->modulus <= 0)
4189  ereport(ERROR,
4190  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4191  errmsg("modulus for hash partition must be an integer value greater than zero")));
4192 
4193  Assert(spec->remainder >= 0);
4194 
4195  if (spec->remainder >= spec->modulus)
4196  ereport(ERROR,
4197  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4198  errmsg("remainder for hash partition must be less than modulus")));
4199  }
4200  else if (strategy == PARTITION_STRATEGY_LIST)
4201  {
4202  ListCell *cell;
4203  char *colname;
4204  Oid coltype;
4205  int32 coltypmod;
4206  Oid partcollation;
4207 
4208  if (spec->strategy != PARTITION_STRATEGY_LIST)
4209  ereport(ERROR,
4210  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4211  errmsg("invalid bound specification for a list partition"),
4212  parser_errposition(pstate, exprLocation((Node *) spec))));
4213 
4214  /* Get the only column's name in case we need to output an error */
4215  if (key->partattrs[0] != 0)
4216  colname = get_attname(RelationGetRelid(parent),
4217  key->partattrs[0], false);
4218  else
4219  colname = deparse_expression((Node *) linitial(partexprs),
4221  RelationGetRelid(parent)),
4222  false, false);
4223  /* Need its type data too */
4224  coltype = get_partition_col_typid(key, 0);
4225  coltypmod = get_partition_col_typmod(key, 0);
4226  partcollation = get_partition_col_collation(key, 0);
4227 
4228  result_spec->listdatums = NIL;
4229  foreach(cell, spec->listdatums)
4230  {
4231  Node *expr = lfirst(cell);
4232  Const *value;
4233  ListCell *cell2;
4234  bool duplicate;
4235 
4236  value = transformPartitionBoundValue(pstate, expr,
4237  colname, coltype, coltypmod,
4238  partcollation);
4239 
4240  /* Don't add to the result if the value is a duplicate */
4241  duplicate = false;
4242  foreach(cell2, result_spec->listdatums)
4243  {
4244  Const *value2 = lfirst_node(Const, cell2);
4245 
4246  if (equal(value, value2))
4247  {
4248  duplicate = true;
4249  break;
4250  }
4251  }
4252  if (duplicate)
4253  continue;
4254 
4255  result_spec->listdatums = lappend(result_spec->listdatums,
4256  value);
4257  }
4258  }
4259  else if (strategy == PARTITION_STRATEGY_RANGE)
4260  {
4261  if (spec->strategy != PARTITION_STRATEGY_RANGE)
4262  ereport(ERROR,
4263  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4264  errmsg("invalid bound specification for a range partition"),
4265  parser_errposition(pstate, exprLocation((Node *) spec))));
4266 
4267  if (list_length(spec->lowerdatums) != partnatts)
4268  ereport(ERROR,
4269  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4270  errmsg("FROM must specify exactly one value per partitioning column")));
4271  if (list_length(spec->upperdatums) != partnatts)
4272  ereport(ERROR,
4273  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4274  errmsg("TO must specify exactly one value per partitioning column")));
4275 
4276  /*
4277  * Convert raw parse nodes into PartitionRangeDatum nodes and perform
4278  * any necessary validation.
4279  */
4280  result_spec->lowerdatums =
4282  parent);
4283  result_spec->upperdatums =
4285  parent);
4286  }
4287  else
4288  elog(ERROR, "unexpected partition strategy: %d", (int) strategy);
4289 
4290  return result_spec;
4291 }
signed int int32
Definition: c.h:483
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:223
static struct @148 value
char * get_attname(Oid relid, AttrNumber attnum, bool missing_ok)
Definition: lsyscache.c:826
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1312
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
static List * transformPartitionRangeBounds(ParseState *pstate, List *blist, Relation parent)
static Const * transformPartitionBoundValue(ParseState *pstate, Node *val, const char *colName, Oid colType, int32 colTypmod, Oid partCollation)
@ PARTITION_STRATEGY_HASH
Definition: parsenodes.h:861
@ PARTITION_STRATEGY_LIST
Definition: parsenodes.h:859
@ PARTITION_STRATEGY_RANGE
Definition: parsenodes.h:860
PartitionKey RelationGetPartitionKey(Relation rel)
Definition: partcache.c:54
static int get_partition_strategy(PartitionKey key)
Definition: partcache.h:59
static int32 get_partition_col_typmod(PartitionKey key, int col)
Definition: partcache.h:92
static int get_partition_natts(PartitionKey key)
Definition: partcache.h:65
static Oid get_partition_col_typid(PartitionKey key, int col)
Definition: partcache.h:86
static Oid get_partition_col_collation(PartitionKey key, int col)
Definition: partcache.h:98
static List * get_partition_exprs(PartitionKey key)
Definition: partcache.h:71
#define linitial(l)
Definition: pg_list.h:178
char * deparse_expression(Node *expr, List *dpcontext, bool forceprefix, bool showimplicit)
Definition: ruleutils.c:3600
List * deparse_context_for(const char *aliasname, Oid relid)
Definition: ruleutils.c:3660

References Assert(), copyObject, deparse_context_for(), deparse_expression(), elog(), equal(), ereport, errcode(), errmsg(), ERROR, exprLocation(), get_attname(), get_partition_col_collation(), get_partition_col_typid(), get_partition_col_typmod(), get_partition_exprs(), get_partition_natts(), get_partition_strategy(), PartitionBoundSpec::is_default, sort-test::key, lappend(), lfirst, lfirst_node, linitial, list_length(), PartitionBoundSpec::listdatums, PartitionBoundSpec::lowerdatums, NIL, parser_errposition(), PARTITION_STRATEGY_HASH, PARTITION_STRATEGY_LIST, PARTITION_STRATEGY_RANGE, RelationGetPartitionKey(), RelationGetRelationName, RelationGetRelid, PartitionBoundSpec::strategy, transformPartitionBoundValue(), transformPartitionRangeBounds(), PartitionBoundSpec::upperdatums, and value.

Referenced by DefineRelation(), and transformPartitionCmd().

◆ transformRuleStmt()

void transformRuleStmt ( RuleStmt stmt,
const char *  queryString,
List **  actions,
Node **  whereClause 
)

Definition at line 3123 of file parse_utilcmd.c.

3125 {
3126  Relation rel;
3127  ParseState *pstate;
3128  ParseNamespaceItem *oldnsitem;
3129  ParseNamespaceItem *newnsitem;
3130 
3131  /*
3132  * To avoid deadlock, make sure the first thing we do is grab
3133  * AccessExclusiveLock on the target relation. This will be needed by
3134  * DefineQueryRewrite(), and we don't want to grab a lesser lock
3135  * beforehand.
3136  */
3137  rel = table_openrv(stmt->relation, AccessExclusiveLock);
3138 
3139  if (rel->rd_rel->relkind == RELKIND_MATVIEW)
3140  ereport(ERROR,
3141  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3142  errmsg("rules on materialized views are not supported")));
3143 
3144  /* Set up pstate */
3145  pstate = make_parsestate(NULL);
3146  pstate->p_sourcetext = queryString;
3147 
3148  /*
3149  * NOTE: 'OLD' must always have a varno equal to 1 and 'NEW' equal to 2.
3150  * Set up their ParseNamespaceItems in the main pstate for use in parsing
3151  * the rule qualification.
3152  */
3153  oldnsitem = addRangeTableEntryForRelation(pstate, rel,
3155  makeAlias("old", NIL),
3156  false, false);
3157  newnsitem = addRangeTableEntryForRelation(pstate, rel,
3159  makeAlias("new", NIL),
3160  false, false);
3161 
3162  /*
3163  * They must be in the namespace too for lookup purposes, but only add the
3164  * one(s) that are relevant for the current kind of rule. In an UPDATE
3165  * rule, quals must refer to OLD.field or NEW.field to be unambiguous, but
3166  * there's no need to be so picky for INSERT & DELETE. We do not add them
3167  * to the joinlist.
3168  */
3169  switch (stmt->event)
3170  {
3171  case CMD_SELECT:
3172  addNSItemToQuery(pstate, oldnsitem, false, true, true);
3173  break;
3174  case CMD_UPDATE:
3175  addNSItemToQuery(pstate, oldnsitem, false, true, true);
3176  addNSItemToQuery(pstate, newnsitem, false, true, true);
3177  break;
3178  case CMD_INSERT:
3179  addNSItemToQuery(pstate, newnsitem, false, true, true);
3180  break;
3181  case CMD_DELETE:
3182  addNSItemToQuery(pstate, oldnsitem, false, true, true);
3183  break;
3184  default:
3185  elog(ERROR, "unrecognized event type: %d",
3186  (int) stmt->event);
3187  break;
3188  }
3189 
3190  /* take care of the where clause */
3191  *whereClause = transformWhereClause(pstate,
3192  stmt->whereClause,
3194  "WHERE");
3195  /* we have to fix its collations too */
3196  assign_expr_collations(pstate, *whereClause);
3197 
3198  /* this is probably dead code without add_missing_from: */
3199  if (list_length(pstate->p_rtable) != 2) /* naughty, naughty... */
3200  ereport(ERROR,
3201  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3202  errmsg("rule WHERE condition cannot contain references to other relations")));
3203 
3204  /*
3205  * 'instead nothing' rules with a qualification need a query rangetable so
3206  * the rewrite handler can add the negated rule qualification to the
3207  * original query. We create a query with the new command type CMD_NOTHING
3208  * here that is treated specially by the rewrite system.
3209  */
3210  if (stmt->actions == NIL)
3211  {
3212  Query *nothing_qry = makeNode(Query);
3213 
3214  nothing_qry->commandType = CMD_NOTHING;
3215  nothing_qry->rtable = pstate->p_rtable;
3216  nothing_qry->rteperminfos = pstate->p_rteperminfos;
3217  nothing_qry->jointree = makeFromExpr(NIL, NULL); /* no join wanted */
3218 
3219  *actions = list_make1(nothing_qry);
3220  }
3221  else
3222  {
3223  ListCell *l;
3224  List *newactions = NIL;
3225 
3226  /*
3227  * transform each statement, like parse_sub_analyze()
3228  */
3229  foreach(l, stmt->actions)
3230  {
3231  Node *action = (Node *) lfirst(l);
3232  ParseState *sub_pstate = make_parsestate(NULL);
3233  Query *sub_qry,
3234  *top_subqry;
3235  bool has_old,
3236  has_new;
3237 
3238  /*
3239  * Since outer ParseState isn't parent of inner, have to pass down
3240  * the query text by hand.
3241  */
3242  sub_pstate->p_sourcetext = queryString;
3243 
3244  /*
3245  * Set up OLD/NEW in the rtable for this statement. The entries
3246  * are added only to relnamespace, not varnamespace, because we
3247  * don't want them to be referred to by unqualified field names
3248  * nor "*" in the rule actions. We decide later whether to put
3249  * them in the joinlist.
3250  */
3251  oldnsitem = addRangeTableEntryForRelation(sub_pstate, rel,
3253  makeAlias("old", NIL),
3254  false, false);
3255  newnsitem = addRangeTableEntryForRelation(sub_pstate, rel,
3257  makeAlias("new", NIL),
3258  false, false);
3259  addNSItemToQuery(sub_pstate, oldnsitem, false, true, false);
3260  addNSItemToQuery(sub_pstate, newnsitem, false, true, false);
3261 
3262  /* Transform the rule action statement */
3263  top_subqry = transformStmt(sub_pstate, action);
3264 
3265  /*
3266  * We cannot support utility-statement actions (eg NOTIFY) with
3267  * nonempty rule WHERE conditions, because there's no way to make
3268  * the utility action execute conditionally.
3269  */
3270  if (top_subqry->commandType == CMD_UTILITY &&
3271  *whereClause != NULL)
3272  ereport(ERROR,
3273  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3274  errmsg("rules with WHERE conditions can only have SELECT, INSERT, UPDATE, or DELETE actions")));
3275 
3276  /*
3277  * If the action is INSERT...SELECT, OLD/NEW have been pushed down
3278  * into the SELECT, and that's what we need to look at. (Ugly
3279  * kluge ... try to fix this when we redesign querytrees.)
3280  */
3281  sub_qry = getInsertSelectQuery(top_subqry, NULL);
3282 
3283  /*
3284  * If the sub_qry is a setop, we cannot attach any qualifications
3285  * to it, because the planner won't notice them. This could
3286  * perhaps be relaxed someday, but for now, we may as well reject
3287  * such a rule immediately.
3288  */
3289  if (sub_qry->setOperations != NULL && *whereClause != NULL)
3290  ereport(ERROR,
3291  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3292  errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
3293 
3294  /*
3295  * Validate action's use of OLD/NEW, qual too
3296  */
3297  has_old =
3298  rangeTableEntry_used((Node *) sub_qry, PRS2_OLD_VARNO, 0) ||
3299  rangeTableEntry_used(*whereClause, PRS2_OLD_VARNO, 0);
3300  has_new =
3301  rangeTableEntry_used((Node *) sub_qry, PRS2_NEW_VARNO, 0) ||
3302  rangeTableEntry_used(*whereClause, PRS2_NEW_VARNO, 0);
3303 
3304  switch (stmt->event)
3305  {
3306  case CMD_SELECT:
3307  if (has_old)
3308  ereport(ERROR,
3309  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3310  errmsg("ON SELECT rule cannot use OLD")));
3311  if (has_new)
3312  ereport(ERROR,
3313  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3314  errmsg("ON SELECT rule cannot use NEW")));
3315  break;
3316  case CMD_UPDATE:
3317  /* both are OK */
3318  break;
3319  case CMD_INSERT:
3320  if (has_old)
3321  ereport(ERROR,
3322  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3323  errmsg("ON INSERT rule cannot use OLD")));
3324  break;
3325  case CMD_DELETE:
3326  if (has_new)
3327  ereport(ERROR,
3328  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3329  errmsg("ON DELETE rule cannot use NEW")));
3330  break;
3331  default:
3332  elog(ERROR, "unrecognized event type: %d",
3333  (int) stmt->event);
3334  break;
3335  }
3336 
3337  /*
3338  * OLD/NEW are not allowed in WITH queries, because they would
3339  * amount to outer references for the WITH, which we disallow.
3340  * However, they were already in the outer rangetable when we
3341  * analyzed the query, so we have to check.
3342  *
3343  * Note that in the INSERT...SELECT case, we need to examine the
3344  * CTE lists of both top_subqry and sub_qry.
3345  *
3346  * Note that we aren't digging into the body of the query looking
3347  * for WITHs in nested sub-SELECTs. A WITH down there can
3348  * legitimately refer to OLD/NEW, because it'd be an
3349  * indirect-correlated outer reference.
3350  */
3351  if (rangeTableEntry_used((Node *) top_subqry->cteList,
3352  PRS2_OLD_VARNO, 0) ||
3353  rangeTableEntry_used((Node *) sub_qry->cteList,
3354  PRS2_OLD_VARNO, 0))
3355  ereport(ERROR,
3356  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3357  errmsg("cannot refer to OLD within WITH query")));
3358  if (rangeTableEntry_used((Node *) top_subqry->cteList,
3359  PRS2_NEW_VARNO, 0) ||
3360  rangeTableEntry_used((Node *) sub_qry->cteList,
3361  PRS2_NEW_VARNO, 0))
3362  ereport(ERROR,
3363  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3364  errmsg("cannot refer to NEW within WITH query")));
3365 
3366  /*
3367  * For efficiency's sake, add OLD to the rule action's jointree
3368  * only if it was actually referenced in the statement or qual.
3369  *
3370  * For INSERT, NEW is not really a relation (only a reference to
3371  * the to-be-inserted tuple) and should never be added to the
3372  * jointree.
3373  *
3374  * For UPDATE, we treat NEW as being another kind of reference to
3375  * OLD, because it represents references to *transformed* tuples
3376  * of the existing relation. It would be wrong to enter NEW
3377  * separately in the jointree, since that would cause a double
3378  * join of the updated relation. It's also wrong to fail to make
3379  * a jointree entry if only NEW and not OLD is mentioned.
3380  */
3381  if (has_old || (has_new && stmt->event == CMD_UPDATE))
3382  {
3383  RangeTblRef *rtr;
3384 
3385  /*
3386  * If sub_qry is a setop, manipulating its jointree will do no
3387  * good at all, because the jointree is dummy. (This should be
3388  * a can't-happen case because of prior tests.)
3389  */
3390  if (sub_qry->setOperations != NULL)
3391  ereport(ERROR,
3392  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3393  errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
3394  /* hackishly add OLD to the already-built FROM clause */
3395  rtr = makeNode(RangeTblRef);
3396  rtr->rtindex = oldnsitem->p_rtindex;
3397  sub_qry->jointree->fromlist =
3398  lappend(sub_qry->jointree->fromlist, rtr);
3399  }
3400 
3401  newactions = lappend(newactions, top_subqry);
3402 
3403  free_parsestate(sub_pstate);
3404  }
3405 
3406  *actions = newactions;
3407  }
3408 
3409  free_parsestate(pstate);
3410 
3411  /* Close relation, but keep the exclusive lock */
3412  table_close(rel, NoLock);
3413 }
#define AccessExclusiveLock
Definition: lockdefs.h:43
Alias * makeAlias(const char *aliasname, List *colnames)
Definition: makefuncs.c:390
FromExpr * makeFromExpr(List *fromlist, Node *quals)
Definition: makefuncs.c:288
@ CMD_UTILITY
Definition: nodes.h:260
@ CMD_INSERT
Definition: nodes.h:257
@ CMD_DELETE
Definition: nodes.h:258
@ CMD_UPDATE
Definition: nodes.h:256
@ CMD_SELECT
Definition: nodes.h:255
@ CMD_NOTHING
Definition: nodes.h:262
@ EXPR_KIND_WHERE
Definition: parse_node.h:46
Query * transformStmt(ParseState *pstate, Node *parseTree)
Definition: analyze.c:314
#define PRS2_OLD_VARNO
Definition: primnodes.h:230
#define PRS2_NEW_VARNO
Definition: primnodes.h:231
Query * getInsertSelectQuery(Query *parsetree, Query ***subquery_ptr)
Definition: rewriteManip.c:990
bool rangeTableEntry_used(Node *node, int rt_index, int sublevels_up)
Definition: rewriteManip.c:958
List * fromlist
Definition: primnodes.h:2040
List * p_rteperminfos
Definition: parse_node.h:194
FromExpr * jointree
Definition: parsenodes.h:174
Node * setOperations
Definition: parsenodes.h:209
List * cteList
Definition: parsenodes.h:165
List * rtable
Definition: parsenodes.h:167
CmdType commandType
Definition: parsenodes.h:120
Relation table_openrv(const RangeVar *relation, LOCKMODE lockmode)
Definition: table.c:83

References AccessExclusiveLock, AccessShareLock, generate_unaccent_rules::action, addNSItemToQuery(), addRangeTableEntryForRelation(), assign_expr_collations(), CMD_DELETE, CMD_INSERT, CMD_NOTHING, CMD_SELECT, CMD_UPDATE, CMD_UTILITY, Query::commandType, Query::cteList, elog(), ereport, errcode(), errmsg(), ERROR, EXPR_KIND_WHERE, free_parsestate(), FromExpr::fromlist, getInsertSelectQuery(), Query::jointree, lappend(), lfirst, list_length(), list_make1, make_parsestate(), makeAlias(), makeFromExpr(), makeNode, NIL, NoLock, ParseState::p_rtable, ParseState::p_rteperminfos, ParseNamespaceItem::p_rtindex, ParseState::p_sourcetext, PRS2_NEW_VARNO, PRS2_OLD_VARNO, rangeTableEntry_used(), RelationData::rd_rel, Query::rtable, RangeTblRef::rtindex, Query::setOperations, stmt, table_close(), table_openrv(), transformStmt(), and transformWhereClause().

Referenced by DefineRule().

◆ transformStatsStmt()

CreateStatsStmt* transformStatsStmt ( Oid  relid,
CreateStatsStmt stmt,
const char *  queryString 
)

Definition at line 3048 of file parse_utilcmd.c.

3049 {
3050  ParseState *pstate;
3051  ParseNamespaceItem *nsitem;
3052  ListCell *l;
3053  Relation rel;
3054 
3055  /* Nothing to do if statement already transformed. */
3056  if (stmt->transformed)
3057  return stmt;
3058 
3059  /* Set up pstate */
3060  pstate = make_parsestate(NULL);
3061  pstate->p_sourcetext = queryString;
3062 
3063  /*
3064  * Put the parent table into the rtable so that the expressions can refer
3065  * to its fields without qualification. Caller is responsible for locking
3066  * relation, but we still need to open it.
3067  */
3068  rel = relation_open(relid, NoLock);
3069  nsitem = addRangeTableEntryForRelation(pstate, rel,
3071  NULL, false, true);
3072 
3073  /* no to join list, yes to namespaces */
3074  addNSItemToQuery(pstate, nsitem, false, true, true);
3075 
3076  /* take care of any expressions */
3077  foreach(l, stmt->exprs)
3078  {
3079  StatsElem *selem = (StatsElem *) lfirst(l);
3080 
3081  if (selem->expr)
3082  {
3083  /* Now do parse transformation of the expression */
3084  selem->expr = transformExpr(pstate, selem->expr,
3086 
3087  /* We have to fix its collations too */
3088  assign_expr_collations(pstate, selem->expr);
3089  }
3090  }
3091 
3092  /*
3093  * Check that only the base rel is mentioned. (This should be dead code
3094  * now that add_missing_from is history.)
3095  */
3096  if (list_length(pstate->p_rtable) != 1)
3097  ereport(ERROR,
3098  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
3099  errmsg("statistics expressions can refer only to the table being referenced")));
3100 
3101  free_parsestate(pstate);
3102 
3103  /* Close relation */
3104  table_close(rel, NoLock);
3105 
3106  /* Mark statement as successfully transformed */
3107  stmt->transformed = true;
3108 
3109  return stmt;
3110 }
@ EXPR_KIND_STATS_EXPRESSION
Definition: parse_node.h:73
Node * expr
Definition: parsenodes.h:3248

References AccessShareLock, addNSItemToQuery(), addRangeTableEntryForRelation(), assign_expr_collations(), ereport, errcode(), errmsg(), ERROR, StatsElem::expr, EXPR_KIND_STATS_EXPRESSION, free_parsestate(), lfirst, list_length(), make_parsestate(), NoLock, ParseState::p_rtable, ParseState::p_sourcetext, relation_open(), stmt, table_close(), and transformExpr().

Referenced by ATPostAlterTypeParse(), and ProcessUtilitySlow().