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 1301 of file parse_utilcmd.c.

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

3584 {
3585  Relation rel;
3586  TupleDesc tupdesc;
3587  ParseState *pstate;
3588  CreateStmtContext cxt;
3589  List *save_alist;
3590  ListCell *lcmd,
3591  *l;
3592  List *newcmds = NIL;
3593  bool skipValidation = true;
3594  AlterTableCmd *newcmd;
3595  ParseNamespaceItem *nsitem;
3596 
3597  /* Caller is responsible for locking the relation */
3598  rel = relation_open(relid, NoLock);
3599  tupdesc = RelationGetDescr(rel);
3600 
3601  /* Set up pstate */
3602  pstate = make_parsestate(NULL);
3603  pstate->p_sourcetext = queryString;
3604  nsitem = addRangeTableEntryForRelation(pstate,
3605  rel,
3607  NULL,
3608  false,
3609  true);
3610  addNSItemToQuery(pstate, nsitem, false, true, true);
3611 
3612  /* Set up CreateStmtContext */
3613  cxt.pstate = pstate;
3614  if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
3615  {
3616  cxt.stmtType = "ALTER FOREIGN TABLE";
3617  cxt.isforeign = true;
3618  }
3619  else
3620  {
3621  cxt.stmtType = "ALTER TABLE";
3622  cxt.isforeign = false;
3623  }
3624  cxt.relation = stmt->relation;
3625  cxt.rel = rel;
3626  cxt.inhRelations = NIL;
3627  cxt.isalter = true;
3628  cxt.columns = NIL;
3629  cxt.ckconstraints = NIL;
3630  cxt.nnconstraints = NIL;
3631  cxt.fkconstraints = NIL;
3632  cxt.ixconstraints = NIL;
3633  cxt.likeclauses = NIL;
3634  cxt.extstats = NIL;
3635  cxt.blist = NIL;
3636  cxt.alist = NIL;
3637  cxt.pkey = NULL;
3638  cxt.ispartitioned = (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
3639  cxt.partbound = NULL;
3640  cxt.ofType = false;
3641 
3642  /*
3643  * Transform ALTER subcommands that need it (most don't). These largely
3644  * re-use code from CREATE TABLE.
3645  */
3646  foreach(lcmd, stmt->cmds)
3647  {
3648  AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
3649 
3650  switch (cmd->subtype)
3651  {
3652  case AT_AddColumn:
3653  {
3654  ColumnDef *def = castNode(ColumnDef, cmd->def);
3655 
3656  transformColumnDefinition(&cxt, def);
3657 
3658  /*
3659  * If the column has a non-null default, we can't skip
3660  * validation of foreign keys.
3661  */
3662  if (def->raw_default != NULL)
3663  skipValidation = false;
3664 
3665  /*
3666  * All constraints are processed in other ways. Remove the
3667  * original list
3668  */
3669  def->constraints = NIL;
3670 
3671  newcmds = lappend(newcmds, cmd);
3672  break;
3673  }
3674 
3675  case AT_AddConstraint:
3676 
3677  /*
3678  * The original AddConstraint cmd node doesn't go to newcmds
3679  */
3680  if (IsA(cmd->def, Constraint))
3681  {
3682  transformTableConstraint(&cxt, (Constraint *) cmd->def);
3683  if (((Constraint *) cmd->def)->contype == CONSTR_FOREIGN)
3684  skipValidation = false;
3685  }
3686  else
3687  elog(ERROR, "unrecognized node type: %d",
3688  (int) nodeTag(cmd->def));
3689  break;
3690 
3691  case AT_AlterColumnType:
3692  {
3693  ColumnDef *def = castNode(ColumnDef, cmd->def);
3695 
3696  /*
3697  * For ALTER COLUMN TYPE, transform the USING clause if
3698  * one was specified.
3699  */
3700  if (def->raw_default)
3701  {
3702  def->cooked_default =
3703  transformExpr(pstate, def->raw_default,
3705  }
3706 
3707  /*
3708  * For identity column, create ALTER SEQUENCE command to
3709  * change the data type of the sequence.
3710  */
3711  attnum = get_attnum(relid, cmd->name);
3712  if (attnum == InvalidAttrNumber)
3713  ereport(ERROR,
3714  (errcode(ERRCODE_UNDEFINED_COLUMN),
3715  errmsg("column \"%s\" of relation \"%s\" does not exist",
3716  cmd->name, RelationGetRelationName(rel))));
3717 
3718  if (attnum > 0 &&
3719  TupleDescAttr(tupdesc, attnum - 1)->attidentity)
3720  {
3721  Oid seq_relid = getIdentitySequence(relid, attnum, false);
3722  Oid typeOid = typenameTypeId(pstate, def->typeName);
3723  AlterSeqStmt *altseqstmt = makeNode(AlterSeqStmt);
3724 
3725  altseqstmt->sequence = makeRangeVar(get_namespace_name(get_rel_namespace(seq_relid)),
3726  get_rel_name(seq_relid),
3727  -1);
3728  altseqstmt->options = list_make1(makeDefElem("as", (Node *) makeTypeNameFromOid(typeOid, -1), -1));
3729  altseqstmt->for_identity = true;
3730  cxt.blist = lappend(cxt.blist, altseqstmt);
3731  }
3732 
3733  newcmds = lappend(newcmds, cmd);
3734  break;
3735  }
3736 
3737  case AT_AddIdentity:
3738  {
3739  Constraint *def = castNode(Constraint, cmd->def);
3740  ColumnDef *newdef = makeNode(ColumnDef);
3742 
3743  newdef->colname = cmd->name;
3744  newdef->identity = def->generated_when;
3745  cmd->def = (Node *) newdef;
3746 
3747  attnum = get_attnum(relid, cmd->name);
3748  if (attnum == InvalidAttrNumber)
3749  ereport(ERROR,
3750  (errcode(ERRCODE_UNDEFINED_COLUMN),
3751  errmsg("column \"%s\" of relation \"%s\" does not exist",
3752  cmd->name, RelationGetRelationName(rel))));
3753 
3754  generateSerialExtraStmts(&cxt, newdef,
3755  get_atttype(relid, attnum),
3756  def->options, true, true,
3757  NULL, NULL);
3758 
3759  newcmds = lappend(newcmds, cmd);
3760  break;
3761  }
3762 
3763  case AT_SetIdentity:
3764  {
3765  /*
3766  * Create an ALTER SEQUENCE statement for the internal
3767  * sequence of the identity column.
3768  */
3769  ListCell *lc;
3770  List *newseqopts = NIL;
3771  List *newdef = NIL;
3773  Oid seq_relid;
3774 
3775  /*
3776  * Split options into those handled by ALTER SEQUENCE and
3777  * those for ALTER TABLE proper.
3778  */
3779  foreach(lc, castNode(List, cmd->def))
3780  {
3781  DefElem *def = lfirst_node(DefElem, lc);
3782 
3783  if (strcmp(def->defname, "generated") == 0)
3784  newdef = lappend(newdef, def);
3785  else
3786  newseqopts = lappend(newseqopts, def);
3787  }
3788 
3789  attnum = get_attnum(relid, cmd->name);
3790  if (attnum == InvalidAttrNumber)
3791  ereport(ERROR,
3792  (errcode(ERRCODE_UNDEFINED_COLUMN),
3793  errmsg("column \"%s\" of relation \"%s\" does not exist",
3794  cmd->name, RelationGetRelationName(rel))));
3795 
3796  seq_relid = getIdentitySequence(relid, attnum, true);
3797 
3798  if (seq_relid)
3799  {
3800  AlterSeqStmt *seqstmt;
3801 
3802  seqstmt = makeNode(AlterSeqStmt);
3804  get_rel_name(seq_relid), -1);
3805  seqstmt->options = newseqopts;
3806  seqstmt->for_identity = true;
3807  seqstmt->missing_ok = false;
3808 
3809  cxt.blist = lappend(cxt.blist, seqstmt);
3810  }
3811 
3812  /*
3813  * If column was not an identity column, we just let the
3814  * ALTER TABLE command error out later. (There are cases
3815  * this fails to cover, but we'll need to restructure
3816  * where creation of the sequence dependency linkage
3817  * happens before we can fix it.)
3818  */
3819 
3820  cmd->def = (Node *) newdef;
3821  newcmds = lappend(newcmds, cmd);
3822  break;
3823  }
3824 
3825  case AT_AttachPartition:
3826  case AT_DetachPartition:
3827  {
3828  PartitionCmd *partcmd = (PartitionCmd *) cmd->def;
3829 
3830  transformPartitionCmd(&cxt, partcmd->bound);
3831  /* assign transformed value of the partition bound */
3832  partcmd->bound = cxt.partbound;
3833  }
3834 
3835  newcmds = lappend(newcmds, cmd);
3836  break;
3837 
3838  case AT_SplitPartition:
3839  case AT_MergePartitions:
3840  {
3841  PartitionCmd *partcmd = (PartitionCmd *) cmd->def;
3842 
3843  if (list_length(partcmd->partlist) < 2)
3844  ereport(ERROR,
3845  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3846  errmsg("list of new partitions should contain at least two items")));
3847 
3848  if (cmd->subtype == AT_SplitPartition)
3849  transformPartitionCmdForSplit(&cxt, partcmd);
3850  else
3851  transformPartitionCmdForMerge(&cxt, partcmd);
3852  newcmds = lappend(newcmds, cmd);
3853  break;
3854  }
3855 
3856  default:
3857 
3858  /*
3859  * Currently, we shouldn't actually get here for subcommand
3860  * types that don't require transformation; but if we do, just
3861  * emit them unchanged.
3862  */
3863  newcmds = lappend(newcmds, cmd);
3864  break;
3865  }
3866  }
3867 
3868  /*
3869  * Transfer anything we already have in cxt.alist into save_alist, to keep
3870  * it separate from the output of transformIndexConstraints.
3871  */
3872  save_alist = cxt.alist;
3873  cxt.alist = NIL;
3874 
3875  /* Postprocess constraints */
3877  transformFKConstraints(&cxt, skipValidation, true);
3878  transformCheckConstraints(&cxt, false);
3879 
3880  /*
3881  * Push any index-creation commands into the ALTER, so that they can be
3882  * scheduled nicely by tablecmds.c. Note that tablecmds.c assumes that
3883  * the IndexStmt attached to an AT_AddIndex or AT_AddIndexConstraint
3884  * subcommand has already been through transformIndexStmt.
3885  */
3886  foreach(l, cxt.alist)
3887  {
3888  Node *istmt = (Node *) lfirst(l);
3889 
3890  /*
3891  * We assume here that cxt.alist contains only IndexStmts and possibly
3892  * AT_SetAttNotNull statements generated from primary key constraints.
3893  * We absorb the subcommands of the latter directly.
3894  */
3895  if (IsA(istmt, IndexStmt))
3896  {
3897  IndexStmt *idxstmt = (IndexStmt *) istmt;
3898 
3899  idxstmt = transformIndexStmt(relid, idxstmt, queryString);
3900  newcmd = makeNode(AlterTableCmd);
3902  newcmd->def = (Node *) idxstmt;
3903  newcmds = lappend(newcmds, newcmd);
3904  }
3905  else if (IsA(istmt, AlterTableStmt))
3906  {
3907  AlterTableStmt *alterstmt = (AlterTableStmt *) istmt;
3908 
3909  newcmds = list_concat(newcmds, alterstmt->cmds);
3910  }
3911  else
3912  elog(ERROR, "unexpected stmt type %d", (int) nodeTag(istmt));
3913  }
3914  cxt.alist = NIL;
3915 
3916  /* Append any CHECK, NOT NULL or FK constraints to the commands list */
3917  foreach(l, cxt.ckconstraints)
3918  {
3919  newcmd = makeNode(AlterTableCmd);
3920  newcmd->subtype = AT_AddConstraint;
3921  newcmd->def = (Node *) lfirst_node(Constraint, l);
3922  newcmds = lappend(newcmds, newcmd);
3923  }
3924  foreach(l, cxt.nnconstraints)
3925  {
3926  newcmd = makeNode(AlterTableCmd);
3927  newcmd->subtype = AT_AddConstraint;
3928  newcmd->def = (Node *) lfirst_node(Constraint, l);
3929  newcmds = lappend(newcmds, newcmd);
3930  }
3931  foreach(l, cxt.fkconstraints)
3932  {
3933  newcmd = makeNode(AlterTableCmd);
3934  newcmd->subtype = AT_AddConstraint;
3935  newcmd->def = (Node *) lfirst_node(Constraint, l);
3936  newcmds = lappend(newcmds, newcmd);
3937  }
3938 
3939  /* Append extended statistics objects */
3941 
3942  /* Close rel */
3943  relation_close(rel, NoLock);
3944 
3945  /*
3946  * Output results.
3947  */
3948  stmt->cmds = newcmds;
3949 
3950  *beforeStmts = cxt.blist;
3951  *afterStmts = list_concat(cxt.alist, save_alist);
3952 
3953  return stmt;
3954 }
#define InvalidAttrNumber
Definition: attnum.h:23
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:77
List * list_concat(List *list1, const List *list2)
Definition: list.c:561
AttrNumber get_attnum(Oid relid, const char *attname)
Definition: lsyscache.c:858
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3366
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:1952
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1928
Oid get_atttype(Oid relid, AttrNumber attnum)
Definition: lsyscache.c:913
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition: makefuncs.c:424
DefElem * makeDefElem(char *name, Node *arg, int location)
Definition: makefuncs.c:564
TypeName * makeTypeNameFromOid(Oid typeOid, int32 typmod)
Definition: makefuncs.c:474
#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:121
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:39
@ EXPR_KIND_ALTER_COL_TRANSFORM
Definition: parse_node.h:75
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 transformPartitionCmdForSplit(CreateStmtContext *cxt, PartitionCmd *partcmd)
static void transformTableConstraint(CreateStmtContext *cxt, Constraint *constraint)
static void transformPartitionCmdForMerge(CreateStmtContext *cxt, PartitionCmd *partcmd)
IndexStmt * transformIndexStmt(Oid relid, IndexStmt *stmt, const char *queryString)
static void transformPartitionCmd(CreateStmtContext *cxt, PartitionBoundSpec *bound)
static void transformCheckConstraints(CreateStmtContext *cxt, bool skipValidation)
static void transformFKConstraints(CreateStmtContext *cxt, bool skipValidation, bool isAddConstraint)
@ CONSTR_FOREIGN
Definition: parsenodes.h:2717
@ AT_AddIndexConstraint
Definition: parsenodes.h:2377
@ AT_MergePartitions
Definition: parsenodes.h:2419
@ AT_SetIdentity
Definition: parsenodes.h:2421
@ AT_AddIndex
Definition: parsenodes.h:2370
@ AT_AddIdentity
Definition: parsenodes.h:2420
@ AT_AlterColumnType
Definition: parsenodes.h:2380
@ AT_DetachPartition
Definition: parsenodes.h:2416
@ AT_AttachPartition
Definition: parsenodes.h:2415
@ AT_SplitPartition
Definition: parsenodes.h:2418
@ AT_AddColumn
Definition: parsenodes.h:2355
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
static int list_length(const List *l)
Definition: pg_list.h:152
#define list_make1(x1)
Definition: pg_list.h:212
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:205
List * options
Definition: parsenodes.h:3142
RangeVar * sequence
Definition: parsenodes.h:3141
bool for_identity
Definition: parsenodes.h:3143
char identity
Definition: parsenodes.h:737
List * constraints
Definition: parsenodes.h:743
Node * cooked_default
Definition: parsenodes.h:736
char * colname
Definition: parsenodes.h:726
TypeName * typeName
Definition: parsenodes.h:727
Node * raw_default
Definition: parsenodes.h:735
List * options
Definition: parsenodes.h:2761
char generated_when
Definition: parsenodes.h:2750
IndexStmt * pkey
Definition: parse_utilcmd.c:96
const char * stmtType
Definition: parse_utilcmd.c:79
RangeVar * relation
Definition: parse_utilcmd.c:80
ParseState * pstate
Definition: parse_utilcmd.c:78
PartitionBoundSpec * partbound
Definition: parse_utilcmd.c:98
char * defname
Definition: parsenodes.h:815
Oid indexOid
Definition: parsenodes.h:3373
const char * p_sourcetext
Definition: parse_node.h:193
PartitionBoundSpec * bound
Definition: parsenodes.h:958
List * partlist
Definition: parsenodes.h:959

References AccessShareLock, addNSItemToQuery(), addRangeTableEntryForRelation(), CreateStmtContext::alist, AT_AddColumn, AT_AddConstraint, AT_AddIdentity, AT_AddIndex, AT_AddIndexConstraint, AT_AlterColumnType, AT_AttachPartition, AT_DetachPartition, AT_MergePartitions, AT_SetIdentity, AT_SplitPartition, 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, if(), IndexStmt::indexOid, CreateStmtContext::inhRelations, InvalidAttrNumber, IsA, CreateStmtContext::isalter, CreateStmtContext::isforeign, CreateStmtContext::ispartitioned, CreateStmtContext::ixconstraints, lappend(), lfirst, lfirst_node, CreateStmtContext::likeclauses, list_concat(), list_length(), 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, PartitionCmd::partlist, 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(), transformPartitionCmdForMerge(), transformPartitionCmdForSplit(), transformTableConstraint(), TupleDescAttr, ColumnDef::typeName, and typenameTypeId().

Referenced by ATParseTransformCmd(), and ATPostAlterTypeParse().

◆ transformCreateSchemaStmtElements()

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

Definition at line 4139 of file parse_utilcmd.c.

4140 {
4142  List *result;
4143  ListCell *elements;
4144 
4145  cxt.schemaname = schemaName;
4146  cxt.sequences = NIL;
4147  cxt.tables = NIL;
4148  cxt.views = NIL;
4149  cxt.indexes = NIL;
4150  cxt.triggers = NIL;
4151  cxt.grants = NIL;
4152 
4153  /*
4154  * Run through each schema element in the schema element list. Separate
4155  * statements by type, and do preliminary analysis.
4156  */
4157  foreach(elements, schemaElts)
4158  {
4159  Node *element = lfirst(elements);
4160 
4161  switch (nodeTag(element))
4162  {
4163  case T_CreateSeqStmt:
4164  {
4165  CreateSeqStmt *elp = (CreateSeqStmt *) element;
4166 
4168  cxt.sequences = lappend(cxt.sequences, element);
4169  }
4170  break;
4171 
4172  case T_CreateStmt:
4173  {
4174  CreateStmt *elp = (CreateStmt *) element;
4175 
4177 
4178  /*
4179  * XXX todo: deal with constraints
4180  */
4181  cxt.tables = lappend(cxt.tables, element);
4182  }
4183  break;
4184 
4185  case T_ViewStmt:
4186  {
4187  ViewStmt *elp = (ViewStmt *) element;
4188 
4189  setSchemaName(cxt.schemaname, &elp->view->schemaname);
4190 
4191  /*
4192  * XXX todo: deal with references between views
4193  */
4194  cxt.views = lappend(cxt.views, element);
4195  }
4196  break;
4197 
4198  case T_IndexStmt:
4199  {
4200  IndexStmt *elp = (IndexStmt *) element;
4201 
4203  cxt.indexes = lappend(cxt.indexes, element);
4204  }
4205  break;
4206 
4207  case T_CreateTrigStmt:
4208  {
4210 
4212  cxt.triggers = lappend(cxt.triggers, element);
4213  }
4214  break;
4215 
4216  case T_GrantStmt:
4217  cxt.grants = lappend(cxt.grants, element);
4218  break;
4219 
4220  default:
4221  elog(ERROR, "unrecognized node type: %d",
4222  (int) nodeTag(element));
4223  }
4224  }
4225 
4226  result = NIL;
4227  result = list_concat(result, cxt.sequences);
4228  result = list_concat(result, cxt.tables);
4229  result = list_concat(result, cxt.views);
4230  result = list_concat(result, cxt.indexes);
4231  result = list_concat(result, cxt.triggers);
4232  result = list_concat(result, cxt.grants);
4233 
4234  return result;
4235 }
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:3131
RangeVar * relation
Definition: parsenodes.h:2658
RangeVar * relation
Definition: parsenodes.h:3018
RangeVar * relation
Definition: parsenodes.h:3363
RangeVar * view
Definition: parsenodes.h:3755

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 167 of file parse_utilcmd.c.

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

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

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 4315 of file parse_utilcmd.c.

4317 {
4318  PartitionBoundSpec *result_spec;
4320  char strategy = get_partition_strategy(key);
4321  int partnatts = get_partition_natts(key);
4322  List *partexprs = get_partition_exprs(key);
4323 
4324  /* Avoid scribbling on input */
4325  result_spec = copyObject(spec);
4326 
4327  if (spec->is_default)
4328  {
4329  /*
4330  * Hash partitioning does not support a default partition; there's no
4331  * use case for it (since the set of partitions to create is perfectly
4332  * defined), and if users do get into it accidentally, it's hard to
4333  * back out from it afterwards.
4334  */
4335  if (strategy == PARTITION_STRATEGY_HASH)
4336  ereport(ERROR,
4337  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4338  errmsg("a hash-partitioned table may not have a default partition")));
4339 
4340  /*
4341  * In case of the default partition, parser had no way to identify the
4342  * partition strategy. Assign the parent's strategy to the default
4343  * partition bound spec.
4344  */
4345  result_spec->strategy = strategy;
4346 
4347  return result_spec;
4348  }
4349 
4350  if (strategy == PARTITION_STRATEGY_HASH)
4351  {
4352  if (spec->strategy != PARTITION_STRATEGY_HASH)
4353  ereport(ERROR,
4354  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4355  errmsg("invalid bound specification for a hash partition"),
4356  parser_errposition(pstate, exprLocation((Node *) spec))));
4357 
4358  if (spec->modulus <= 0)
4359  ereport(ERROR,
4360  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4361  errmsg("modulus for hash partition must be an integer value greater than zero")));
4362 
4363  Assert(spec->remainder >= 0);
4364 
4365  if (spec->remainder >= spec->modulus)
4366  ereport(ERROR,
4367  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4368  errmsg("remainder for hash partition must be less than modulus")));
4369  }
4370  else if (strategy == PARTITION_STRATEGY_LIST)
4371  {
4372  ListCell *cell;
4373  char *colname;
4374  Oid coltype;
4375  int32 coltypmod;
4376  Oid partcollation;
4377 
4378  if (spec->strategy != PARTITION_STRATEGY_LIST)
4379  ereport(ERROR,
4380  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4381  errmsg("invalid bound specification for a list partition"),
4382  parser_errposition(pstate, exprLocation((Node *) spec))));
4383 
4384  /* Get the only column's name in case we need to output an error */
4385  if (key->partattrs[0] != 0)
4386  colname = get_attname(RelationGetRelid(parent),
4387  key->partattrs[0], false);
4388  else
4389  colname = deparse_expression((Node *) linitial(partexprs),
4391  RelationGetRelid(parent)),
4392  false, false);
4393  /* Need its type data too */
4394  coltype = get_partition_col_typid(key, 0);
4395  coltypmod = get_partition_col_typmod(key, 0);
4396  partcollation = get_partition_col_collation(key, 0);
4397 
4398  result_spec->listdatums = NIL;
4399  foreach(cell, spec->listdatums)
4400  {
4401  Node *expr = lfirst(cell);
4402  Const *value;
4403  ListCell *cell2;
4404  bool duplicate;
4405 
4406  value = transformPartitionBoundValue(pstate, expr,
4407  colname, coltype, coltypmod,
4408  partcollation);
4409 
4410  /* Don't add to the result if the value is a duplicate */
4411  duplicate = false;
4412  foreach(cell2, result_spec->listdatums)
4413  {
4414  Const *value2 = lfirst_node(Const, cell2);
4415 
4416  if (equal(value, value2))
4417  {
4418  duplicate = true;
4419  break;
4420  }
4421  }
4422  if (duplicate)
4423  continue;
4424 
4425  result_spec->listdatums = lappend(result_spec->listdatums,
4426  value);
4427  }
4428  }
4429  else if (strategy == PARTITION_STRATEGY_RANGE)
4430  {
4431  if (spec->strategy != PARTITION_STRATEGY_RANGE)
4432  ereport(ERROR,
4433  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4434  errmsg("invalid bound specification for a range partition"),
4435  parser_errposition(pstate, exprLocation((Node *) spec))));
4436 
4437  if (list_length(spec->lowerdatums) != partnatts)
4438  ereport(ERROR,
4439  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4440  errmsg("FROM must specify exactly one value per partitioning column")));
4441  if (list_length(spec->upperdatums) != partnatts)
4442  ereport(ERROR,
4443  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4444  errmsg("TO must specify exactly one value per partitioning column")));
4445 
4446  /*
4447  * Convert raw parse nodes into PartitionRangeDatum nodes and perform
4448  * any necessary validation.
4449  */
4450  result_spec->lowerdatums =
4452  parent);
4453  result_spec->upperdatums =
4455  parent);
4456  }
4457  else
4458  elog(ERROR, "unexpected partition strategy: %d", (int) strategy);
4459 
4460  return result_spec;
4461 }
signed int int32
Definition: c.h:494
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:223
static struct @155 value
char * get_attname(Oid relid, AttrNumber attnum, bool missing_ok)
Definition: lsyscache.c:827
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1386
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:106
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:874
@ PARTITION_STRATEGY_LIST
Definition: parsenodes.h:872
@ PARTITION_STRATEGY_RANGE
Definition: parsenodes.h:873
PartitionKey RelationGetPartitionKey(Relation rel)
Definition: partcache.c:51
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:3625
List * deparse_context_for(const char *aliasname, Oid relid)
Definition: ruleutils.c:3685

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 3126 of file parse_utilcmd.c.

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

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

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