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)
 
ListtransformAlterTableStmt (Oid relid, AlterTableStmt *stmt, const char *queryString)
 
IndexStmttransformIndexStmt (Oid relid, IndexStmt *stmt, const char *queryString)
 
void transformRuleStmt (RuleStmt *stmt, const char *queryString, List **actions, Node **whereClause)
 
ListtransformCreateSchemaStmt (CreateSchemaStmt *stmt)
 
PartitionBoundSpectransformPartitionBound (ParseState *pstate, Relation parent, PartitionBoundSpec *spec)
 
IndexStmtgenerateClonedIndexStmt (RangeVar *heapRel, Relation source_idx, const AttrNumber *attmap, int attmap_length, Oid *constraintOid)
 

Function Documentation

◆ generateClonedIndexStmt()

IndexStmt* generateClonedIndexStmt ( RangeVar heapRel,
Relation  source_idx,
const AttrNumber attmap,
int  attmap_length,
Oid constraintOid 
)

Definition at line 1334 of file parse_utilcmd.c.

References IndexStmt::accessMethod, IndexAmRoutine::amcanorder, AMOID, Assert, attname, attnum, AttributeNumberIsValid, IndexElem::collation, IndexStmt::concurrent, CONSTROID, DatumGetArrayTypeP, DatumGetObjectId, DatumGetPointer, deconstruct_array(), IndexStmt::deferrable, elog, ereport, errcode(), errdetail(), errmsg(), ERROR, IndexStmt::excludeOpNames, IndexElem::expr, exprType(), get_attname(), get_atttype(), get_collation(), get_index_constraint(), get_namespace_name(), get_opclass(), get_tablespace_name(), GETSTRUCT, HeapTupleIsValid, i, IndexStmt::idxcomment, IndexStmt::idxname, IndexStmt::if_not_exists, IndexElem::indexcolname, IndexStmt::indexIncludingParams, IndexStmt::indexOid, IndexStmt::indexParams, INDEXRELID, IndexStmt::initdeferred, InvalidOid, IndexStmt::isconstraint, lappend(), lfirst, list_head(), list_make2, lnext(), makeNode, makeString(), map_variable_attnos(), IndexElem::name, NameStr, NIL, IndexElem::nulls_ordering, ObjectIdGetDatum, OidIsValid, IndexStmt::oldNode, IndexElem::opclass, OPEROID, IndexStmt::options, IndexElem::ordering, IndexStmt::primary, pstrdup(), RelationData::rd_indam, RelationData::rd_indextuple, RelationData::rd_indoption, IndexStmt::relation, RelationGetDescr, RelationGetRelationName, RelationGetRelid, ReleaseSysCache(), RELOID, IndexStmt::reset_default_tblspc, SearchSysCache1(), SORTBY_DEFAULT, SORTBY_DESC, SORTBY_NULLS_DEFAULT, SORTBY_NULLS_FIRST, SORTBY_NULLS_LAST, stringToNode(), SysCacheGetAttr(), IndexStmt::tableSpace, TextDatumGetCString, IndexStmt::transformed, TupleDescAttr, IndexStmt::unique, untransformRelOptions(), oidvector::values, and IndexStmt::whereClause.

Referenced by AttachPartitionEnsureIndexes(), DefineRelation(), and transformTableLikeClause().

1337 {
1338  Oid source_relid = RelationGetRelid(source_idx);
1339  HeapTuple ht_idxrel;
1340  HeapTuple ht_idx;
1341  HeapTuple ht_am;
1342  Form_pg_class idxrelrec;
1343  Form_pg_index idxrec;
1344  Form_pg_am amrec;
1345  oidvector *indcollation;
1346  oidvector *indclass;
1347  IndexStmt *index;
1348  List *indexprs;
1349  ListCell *indexpr_item;
1350  Oid indrelid;
1351  int keyno;
1352  Oid keycoltype;
1353  Datum datum;
1354  bool isnull;
1355 
1356  if (constraintOid)
1357  *constraintOid = InvalidOid;
1358 
1359  /*
1360  * Fetch pg_class tuple of source index. We can't use the copy in the
1361  * relcache entry because it doesn't include optional fields.
1362  */
1363  ht_idxrel = SearchSysCache1(RELOID, ObjectIdGetDatum(source_relid));
1364  if (!HeapTupleIsValid(ht_idxrel))
1365  elog(ERROR, "cache lookup failed for relation %u", source_relid);
1366  idxrelrec = (Form_pg_class) GETSTRUCT(ht_idxrel);
1367 
1368  /* Fetch pg_index tuple for source index from relcache entry */
1369  ht_idx = source_idx->rd_indextuple;
1370  idxrec = (Form_pg_index) GETSTRUCT(ht_idx);
1371  indrelid = idxrec->indrelid;
1372 
1373  /* Fetch the pg_am tuple of the index' access method */
1374  ht_am = SearchSysCache1(AMOID, ObjectIdGetDatum(idxrelrec->relam));
1375  if (!HeapTupleIsValid(ht_am))
1376  elog(ERROR, "cache lookup failed for access method %u",
1377  idxrelrec->relam);
1378  amrec = (Form_pg_am) GETSTRUCT(ht_am);
1379 
1380  /* Extract indcollation from the pg_index tuple */
1381  datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1382  Anum_pg_index_indcollation, &isnull);
1383  Assert(!isnull);
1384  indcollation = (oidvector *) DatumGetPointer(datum);
1385 
1386  /* Extract indclass from the pg_index tuple */
1387  datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1388  Anum_pg_index_indclass, &isnull);
1389  Assert(!isnull);
1390  indclass = (oidvector *) DatumGetPointer(datum);
1391 
1392  /* Begin building the IndexStmt */
1393  index = makeNode(IndexStmt);
1394  index->relation = heapRel;
1395  index->accessMethod = pstrdup(NameStr(amrec->amname));
1396  if (OidIsValid(idxrelrec->reltablespace))
1397  index->tableSpace = get_tablespace_name(idxrelrec->reltablespace);
1398  else
1399  index->tableSpace = NULL;
1400  index->excludeOpNames = NIL;
1401  index->idxcomment = NULL;
1402  index->indexOid = InvalidOid;
1403  index->oldNode = InvalidOid;
1404  index->unique = idxrec->indisunique;
1405  index->primary = idxrec->indisprimary;
1406  index->transformed = true; /* don't need transformIndexStmt */
1407  index->concurrent = false;
1408  index->if_not_exists = false;
1409  index->reset_default_tblspc = false;
1410 
1411  /*
1412  * We don't try to preserve the name of the source index; instead, just
1413  * let DefineIndex() choose a reasonable name. (If we tried to preserve
1414  * the name, we'd get duplicate-relation-name failures unless the source
1415  * table was in a different schema.)
1416  */
1417  index->idxname = NULL;
1418 
1419  /*
1420  * If the index is marked PRIMARY or has an exclusion condition, it's
1421  * certainly from a constraint; else, if it's not marked UNIQUE, it
1422  * certainly isn't. If it is or might be from a constraint, we have to
1423  * fetch the pg_constraint record.
1424  */
1425  if (index->primary || index->unique || idxrec->indisexclusion)
1426  {
1427  Oid constraintId = get_index_constraint(source_relid);
1428 
1429  if (OidIsValid(constraintId))
1430  {
1431  HeapTuple ht_constr;
1432  Form_pg_constraint conrec;
1433 
1434  if (constraintOid)
1435  *constraintOid = constraintId;
1436 
1437  ht_constr = SearchSysCache1(CONSTROID,
1438  ObjectIdGetDatum(constraintId));
1439  if (!HeapTupleIsValid(ht_constr))
1440  elog(ERROR, "cache lookup failed for constraint %u",
1441  constraintId);
1442  conrec = (Form_pg_constraint) GETSTRUCT(ht_constr);
1443 
1444  index->isconstraint = true;
1445  index->deferrable = conrec->condeferrable;
1446  index->initdeferred = conrec->condeferred;
1447 
1448  /* If it's an exclusion constraint, we need the operator names */
1449  if (idxrec->indisexclusion)
1450  {
1451  Datum *elems;
1452  int nElems;
1453  int i;
1454 
1455  Assert(conrec->contype == CONSTRAINT_EXCLUSION);
1456  /* Extract operator OIDs from the pg_constraint tuple */
1457  datum = SysCacheGetAttr(CONSTROID, ht_constr,
1458  Anum_pg_constraint_conexclop,
1459  &isnull);
1460  if (isnull)
1461  elog(ERROR, "null conexclop for constraint %u",
1462  constraintId);
1463 
1465  OIDOID, sizeof(Oid), true, 'i',
1466  &elems, NULL, &nElems);
1467 
1468  for (i = 0; i < nElems; i++)
1469  {
1470  Oid operid = DatumGetObjectId(elems[i]);
1471  HeapTuple opertup;
1472  Form_pg_operator operform;
1473  char *oprname;
1474  char *nspname;
1475  List *namelist;
1476 
1477  opertup = SearchSysCache1(OPEROID,
1478  ObjectIdGetDatum(operid));
1479  if (!HeapTupleIsValid(opertup))
1480  elog(ERROR, "cache lookup failed for operator %u",
1481  operid);
1482  operform = (Form_pg_operator) GETSTRUCT(opertup);
1483  oprname = pstrdup(NameStr(operform->oprname));
1484  /* For simplicity we always schema-qualify the op name */
1485  nspname = get_namespace_name(operform->oprnamespace);
1486  namelist = list_make2(makeString(nspname),
1487  makeString(oprname));
1488  index->excludeOpNames = lappend(index->excludeOpNames,
1489  namelist);
1490  ReleaseSysCache(opertup);
1491  }
1492  }
1493 
1494  ReleaseSysCache(ht_constr);
1495  }
1496  else
1497  index->isconstraint = false;
1498  }
1499  else
1500  index->isconstraint = false;
1501 
1502  /* Get the index expressions, if any */
1503  datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1504  Anum_pg_index_indexprs, &isnull);
1505  if (!isnull)
1506  {
1507  char *exprsString;
1508 
1509  exprsString = TextDatumGetCString(datum);
1510  indexprs = (List *) stringToNode(exprsString);
1511  }
1512  else
1513  indexprs = NIL;
1514 
1515  /* Build the list of IndexElem */
1516  index->indexParams = NIL;
1517  index->indexIncludingParams = NIL;
1518 
1519  indexpr_item = list_head(indexprs);
1520  for (keyno = 0; keyno < idxrec->indnkeyatts; keyno++)
1521  {
1522  IndexElem *iparam;
1523  AttrNumber attnum = idxrec->indkey.values[keyno];
1525  keyno);
1526  int16 opt = source_idx->rd_indoption[keyno];
1527 
1528  iparam = makeNode(IndexElem);
1529 
1530  if (AttributeNumberIsValid(attnum))
1531  {
1532  /* Simple index column */
1533  char *attname;
1534 
1535  attname = get_attname(indrelid, attnum, false);
1536  keycoltype = get_atttype(indrelid, attnum);
1537 
1538  iparam->name = attname;
1539  iparam->expr = NULL;
1540  }
1541  else
1542  {
1543  /* Expressional index */
1544  Node *indexkey;
1545  bool found_whole_row;
1546 
1547  if (indexpr_item == NULL)
1548  elog(ERROR, "too few entries in indexprs list");
1549  indexkey = (Node *) lfirst(indexpr_item);
1550  indexpr_item = lnext(indexprs, indexpr_item);
1551 
1552  /* Adjust Vars to match new table's column numbering */
1553  indexkey = map_variable_attnos(indexkey,
1554  1, 0,
1555  attmap, attmap_length,
1556  InvalidOid, &found_whole_row);
1557 
1558  /* As in transformTableLikeClause, reject whole-row variables */
1559  if (found_whole_row)
1560  ereport(ERROR,
1561  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1562  errmsg("cannot convert whole-row table reference"),
1563  errdetail("Index \"%s\" contains a whole-row table reference.",
1564  RelationGetRelationName(source_idx))));
1565 
1566  iparam->name = NULL;
1567  iparam->expr = indexkey;
1568 
1569  keycoltype = exprType(indexkey);
1570  }
1571 
1572  /* Copy the original index column name */
1573  iparam->indexcolname = pstrdup(NameStr(attr->attname));
1574 
1575  /* Add the collation name, if non-default */
1576  iparam->collation = get_collation(indcollation->values[keyno], keycoltype);
1577 
1578  /* Add the operator class name, if non-default */
1579  iparam->opclass = get_opclass(indclass->values[keyno], keycoltype);
1580 
1581  iparam->ordering = SORTBY_DEFAULT;
1583 
1584  /* Adjust options if necessary */
1585  if (source_idx->rd_indam->amcanorder)
1586  {
1587  /*
1588  * If it supports sort ordering, copy DESC and NULLS opts. Don't
1589  * set non-default settings unnecessarily, though, so as to
1590  * improve the chance of recognizing equivalence to constraint
1591  * indexes.
1592  */
1593  if (opt & INDOPTION_DESC)
1594  {
1595  iparam->ordering = SORTBY_DESC;
1596  if ((opt & INDOPTION_NULLS_FIRST) == 0)
1598  }
1599  else
1600  {
1601  if (opt & INDOPTION_NULLS_FIRST)
1603  }
1604  }
1605 
1606  index->indexParams = lappend(index->indexParams, iparam);
1607  }
1608 
1609  /* Handle included columns separately */
1610  for (keyno = idxrec->indnkeyatts; keyno < idxrec->indnatts; keyno++)
1611  {
1612  IndexElem *iparam;
1613  AttrNumber attnum = idxrec->indkey.values[keyno];
1615  keyno);
1616 
1617  iparam = makeNode(IndexElem);
1618 
1619  if (AttributeNumberIsValid(attnum))
1620  {
1621  /* Simple index column */
1622  char *attname;
1623 
1624  attname = get_attname(indrelid, attnum, false);
1625  keycoltype = get_atttype(indrelid, attnum);
1626 
1627  iparam->name = attname;
1628  iparam->expr = NULL;
1629  }
1630  else
1631  ereport(ERROR,
1632  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1633  errmsg("expressions are not supported in included columns")));
1634 
1635  /* Copy the original index column name */
1636  iparam->indexcolname = pstrdup(NameStr(attr->attname));
1637 
1638  index->indexIncludingParams = lappend(index->indexIncludingParams, iparam);
1639  }
1640  /* Copy reloptions if any */
1641  datum = SysCacheGetAttr(RELOID, ht_idxrel,
1642  Anum_pg_class_reloptions, &isnull);
1643  if (!isnull)
1644  index->options = untransformRelOptions(datum);
1645 
1646  /* If it's a partial index, decompile and append the predicate */
1647  datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1648  Anum_pg_index_indpred, &isnull);
1649  if (!isnull)
1650  {
1651  char *pred_str;
1652  Node *pred_tree;
1653  bool found_whole_row;
1654 
1655  /* Convert text string to node tree */
1656  pred_str = TextDatumGetCString(datum);
1657  pred_tree = (Node *) stringToNode(pred_str);
1658 
1659  /* Adjust Vars to match new table's column numbering */
1660  pred_tree = map_variable_attnos(pred_tree,
1661  1, 0,
1662  attmap, attmap_length,
1663  InvalidOid, &found_whole_row);
1664 
1665  /* As in transformTableLikeClause, reject whole-row variables */
1666  if (found_whole_row)
1667  ereport(ERROR,
1668  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1669  errmsg("cannot convert whole-row table reference"),
1670  errdetail("Index \"%s\" contains a whole-row table reference.",
1671  RelationGetRelationName(source_idx))));
1672 
1673  index->whereClause = pred_tree;
1674  }
1675 
1676  /* Clean up */
1677  ReleaseSysCache(ht_idxrel);
1678  ReleaseSysCache(ht_am);
1679 
1680  return index;
1681 }
#define list_make2(x1, x2)
Definition: pg_list.h:229
bool deferrable
Definition: parsenodes.h:2768
Value * makeString(char *str)
Definition: value.c:53
signed short int16
Definition: c.h:346
#define NIL
Definition: pg_list.h:65
static List * get_opclass(Oid opclass, Oid actual_datatype)
Definition: c.h:595
bool primary
Definition: parsenodes.h:2766
struct IndexAmRoutine * rd_indam
Definition: rel.h:157
int16 * rd_indoption
Definition: rel.h:162
SortByDir ordering
Definition: parsenodes.h:704
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
Definition: syscache.h:36
List * options
Definition: parsenodes.h:2759
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:321
#define RelationGetDescr(relation)
Definition: rel.h:448
char * tableSpace
Definition: parsenodes.h:2755
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
#define DatumGetObjectId(X)
Definition: postgres.h:500
char * pstrdup(const char *in)
Definition: mcxt.c:1186
Node * whereClause
Definition: parsenodes.h:2760
Definition: nodes.h:525
int errcode(int sqlerrcode)
Definition: elog.c:608
void * stringToNode(const char *str)
Definition: read.c:89
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:645
struct HeapTupleData * rd_indextuple
Definition: rel.h:145
List * indexIncludingParams
Definition: parsenodes.h:2757
Definition: type.h:89
Oid indexOid
Definition: parsenodes.h:2763
Node * expr
Definition: parsenodes.h:700
RangeVar * relation
Definition: parsenodes.h:2753
SortByNulls nulls_ordering
Definition: parsenodes.h:705
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
NameData attname
Definition: pg_attribute.h:40
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3094
Oid values[FLEXIBLE_ARRAY_MEMBER]
Definition: c.h:603
bool transformed
Definition: parsenodes.h:2770
int errdetail(const char *fmt,...)
Definition: elog.c:955
char * indexcolname
Definition: parsenodes.h:701
#define RelationGetRelationName(relation)
Definition: rel.h:456
static ListCell * list_head(const List *l)
Definition: pg_list.h:125
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:200
Oid get_index_constraint(Oid indexId)
Definition: pg_depend.c:873
Oid get_atttype(Oid relid, AttrNumber attnum)
Definition: lsyscache.c:861
#define ereport(elevel, rest)
Definition: elog.h:141
Node * map_variable_attnos(Node *node, int target_varno, int sublevels_up, const AttrNumber *attno_map, int map_length, Oid to_rowtype, bool *found_whole_row)
List * lappend(List *list, void *datum)
Definition: list.c:322
char * idxname
Definition: parsenodes.h:2752
FormData_pg_index * Form_pg_index
Definition: pg_index.h:66
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1116
#define AttributeNumberIsValid(attributeNumber)
Definition: attnum.h:34
#define TextDatumGetCString(d)
Definition: builtins.h:84
bool reset_default_tblspc
Definition: parsenodes.h:2773
bool if_not_exists
Definition: parsenodes.h:2772
uintptr_t Datum
Definition: postgres.h:367
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1377
bool unique
Definition: parsenodes.h:2765
List * untransformRelOptions(Datum options)
Definition: reloptions.c:1039
char * accessMethod
Definition: parsenodes.h:2754
#define InvalidOid
Definition: postgres_ext.h:36
int16 attnum
Definition: pg_attribute.h:79
List * opclass
Definition: parsenodes.h:703
#define makeNode(_type_)
Definition: nodes.h:573
FormData_pg_constraint * Form_pg_constraint
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:739
#define lfirst(lc)
Definition: pg_list.h:190
List * indexParams
Definition: parsenodes.h:2756
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
List * excludeOpNames
Definition: parsenodes.h:2761
bool initdeferred
Definition: parsenodes.h:2769
bool amcanorder
Definition: amapi.h:175
char * name
Definition: parsenodes.h:699
char * idxcomment
Definition: parsenodes.h:2762
FormData_pg_operator * Form_pg_operator
Definition: pg_operator.h:83
#define DatumGetPointer(X)
Definition: postgres.h:549
void deconstruct_array(ArrayType *array, Oid elmtype, int elmlen, bool elmbyval, char elmalign, Datum **elemsp, bool **nullsp, int *nelemsp)
Definition: arrayfuncs.c:3461
FormData_pg_class * Form_pg_class
Definition: pg_class.h:150
bool concurrent
Definition: parsenodes.h:2771
bool isconstraint
Definition: parsenodes.h:2767
FormData_pg_am * Form_pg_am
Definition: pg_am.h:48
int errmsg(const char *fmt,...)
Definition: elog.c:822
char * get_tablespace_name(Oid spc_oid)
Definition: tablespace.c:1462
#define elog(elevel,...)
Definition: elog.h:228
int i
#define NameStr(name)
Definition: c.h:616
List * collation
Definition: parsenodes.h:702
char * get_attname(Oid relid, AttrNumber attnum, bool missing_ok)
Definition: lsyscache.c:775
static List * get_collation(Oid collation, Oid actual_datatype)
Definition: pg_list.h:50
int16 AttrNumber
Definition: attnum.h:21
#define RelationGetRelid(relation)
Definition: rel.h:422
#define DatumGetArrayTypeP(X)
Definition: array.h:249

◆ transformAlterTableStmt()

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

Definition at line 3014 of file parse_utilcmd.c.

References AccessShareLock, addRangeTableEntryForRelation(), addRTEtoQuery(), CreateStmtContext::alist, AT_AddColumn, AT_AddColumnToView, AT_AddConstraint, AT_AddIdentity, AT_AddIndex, AT_AddIndexConstraint, AT_AlterColumnType, AT_AttachPartition, AT_DetachPartition, AT_ProcessedConstraint, AT_SetIdentity, attnum, CreateStmtContext::blist, PartitionCmd::bound, castNode, CreateStmtContext::ckconstraints, AlterTableStmt::cmds, ColumnDef::colname, CreateStmtContext::columns, CONSTR_FOREIGN, ColumnDef::constraints, ColumnDef::cooked_default, copyObject, AlterTableCmd::def, DefElem::defname, elog, 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::inh_indexes, CreateStmtContext::inhRelations, InvalidAttrNumber, IsA, CreateStmtContext::isalter, CreateStmtContext::isforeign, CreateStmtContext::ispartitioned, CreateStmtContext::ixconstraints, lappend(), lfirst, lfirst_node, list_concat(), list_make1, make_parsestate(), makeDefElem(), makeNode, makeRangeVar(), makeTypeNameFromOid(), AlterSeqStmt::missing_ok, AlterTableCmd::name, NIL, nodeTag, NoLock, OBJECT_FOREIGN_TABLE, 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, AlterTableStmt::relation, relation_close(), relation_open(), RelationGetDescr, AlterTableStmt::relkind, AlterSeqStmt::sequence, CreateStmtContext::stmtType, AlterTableCmd::subtype, transformCheckConstraints(), transformColumnDefinition(), transformExpr(), transformExtendedStatistics(), transformFKConstraints(), transformIndexConstraints(), transformIndexStmt(), transformPartitionCmd(), transformTableConstraint(), TupleDescAttr, ColumnDef::typeName, and typenameTypeId().

Referenced by ATPostAlterTypeParse(), and ProcessUtilitySlow().

3016 {
3017  Relation rel;
3018  TupleDesc tupdesc;
3019  ParseState *pstate;
3020  CreateStmtContext cxt;
3021  List *result;
3022  List *save_alist;
3023  ListCell *lcmd,
3024  *l;
3025  List *newcmds = NIL;
3026  bool skipValidation = true;
3027  AlterTableCmd *newcmd;
3028  RangeTblEntry *rte;
3029 
3030  /*
3031  * We must not scribble on the passed-in AlterTableStmt, so copy it. (This
3032  * is overkill, but easy.)
3033  */
3034  stmt = copyObject(stmt);
3035 
3036  /* Caller is responsible for locking the relation */
3037  rel = relation_open(relid, NoLock);
3038  tupdesc = RelationGetDescr(rel);
3039 
3040  /* Set up pstate */
3041  pstate = make_parsestate(NULL);
3042  pstate->p_sourcetext = queryString;
3043  rte = addRangeTableEntryForRelation(pstate,
3044  rel,
3046  NULL,
3047  false,
3048  true);
3049  addRTEtoQuery(pstate, rte, false, true, true);
3050 
3051  /* Set up CreateStmtContext */
3052  cxt.pstate = pstate;
3053  if (stmt->relkind == OBJECT_FOREIGN_TABLE)
3054  {
3055  cxt.stmtType = "ALTER FOREIGN TABLE";
3056  cxt.isforeign = true;
3057  }
3058  else
3059  {
3060  cxt.stmtType = "ALTER TABLE";
3061  cxt.isforeign = false;
3062  }
3063  cxt.relation = stmt->relation;
3064  cxt.rel = rel;
3065  cxt.inhRelations = NIL;
3066  cxt.isalter = true;
3067  cxt.columns = NIL;
3068  cxt.ckconstraints = NIL;
3069  cxt.fkconstraints = NIL;
3070  cxt.ixconstraints = NIL;
3071  cxt.inh_indexes = NIL;
3072  cxt.extstats = NIL;
3073  cxt.blist = NIL;
3074  cxt.alist = NIL;
3075  cxt.pkey = NULL;
3076  cxt.ispartitioned = (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
3077  cxt.partbound = NULL;
3078  cxt.ofType = false;
3079 
3080  /*
3081  * The only subtypes that currently require parse transformation handling
3082  * are ADD COLUMN, ADD CONSTRAINT and SET DATA TYPE. These largely re-use
3083  * code from CREATE TABLE.
3084  */
3085  foreach(lcmd, stmt->cmds)
3086  {
3087  AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
3088 
3089  switch (cmd->subtype)
3090  {
3091  case AT_AddColumn:
3092  case AT_AddColumnToView:
3093  {
3094  ColumnDef *def = castNode(ColumnDef, cmd->def);
3095 
3096  transformColumnDefinition(&cxt, def);
3097 
3098  /*
3099  * If the column has a non-null default, we can't skip
3100  * validation of foreign keys.
3101  */
3102  if (def->raw_default != NULL)
3103  skipValidation = false;
3104 
3105  /*
3106  * All constraints are processed in other ways. Remove the
3107  * original list
3108  */
3109  def->constraints = NIL;
3110 
3111  newcmds = lappend(newcmds, cmd);
3112  break;
3113  }
3114 
3115  case AT_AddConstraint:
3116 
3117  /*
3118  * The original AddConstraint cmd node doesn't go to newcmds
3119  */
3120  if (IsA(cmd->def, Constraint))
3121  {
3122  transformTableConstraint(&cxt, (Constraint *) cmd->def);
3123  if (((Constraint *) cmd->def)->contype == CONSTR_FOREIGN)
3124  skipValidation = false;
3125  }
3126  else
3127  elog(ERROR, "unrecognized node type: %d",
3128  (int) nodeTag(cmd->def));
3129  break;
3130 
3132 
3133  /*
3134  * Already-transformed ADD CONSTRAINT, so just make it look
3135  * like the standard case.
3136  */
3137  cmd->subtype = AT_AddConstraint;
3138  newcmds = lappend(newcmds, cmd);
3139  break;
3140 
3141  case AT_AlterColumnType:
3142  {
3143  ColumnDef *def = (ColumnDef *) cmd->def;
3145 
3146  /*
3147  * For ALTER COLUMN TYPE, transform the USING clause if
3148  * one was specified.
3149  */
3150  if (def->raw_default)
3151  {
3152  def->cooked_default =
3153  transformExpr(pstate, def->raw_default,
3155  }
3156 
3157  /*
3158  * For identity column, create ALTER SEQUENCE command to
3159  * change the data type of the sequence.
3160  */
3161  attnum = get_attnum(relid, cmd->name);
3162 
3163  /*
3164  * if attribute not found, something will error about it
3165  * later
3166  */
3167  if (attnum != InvalidAttrNumber &&
3168  TupleDescAttr(tupdesc, attnum - 1)->attidentity)
3169  {
3170  Oid seq_relid = getIdentitySequence(relid, attnum, false);
3171  Oid typeOid = typenameTypeId(pstate, def->typeName);
3172  AlterSeqStmt *altseqstmt = makeNode(AlterSeqStmt);
3173 
3174  altseqstmt->sequence = makeRangeVar(get_namespace_name(get_rel_namespace(seq_relid)),
3175  get_rel_name(seq_relid),
3176  -1);
3177  altseqstmt->options = list_make1(makeDefElem("as", (Node *) makeTypeNameFromOid(typeOid, -1), -1));
3178  altseqstmt->for_identity = true;
3179  cxt.blist = lappend(cxt.blist, altseqstmt);
3180  }
3181 
3182  newcmds = lappend(newcmds, cmd);
3183  break;
3184  }
3185 
3186  case AT_AddIdentity:
3187  {
3188  Constraint *def = castNode(Constraint, cmd->def);
3189  ColumnDef *newdef = makeNode(ColumnDef);
3191 
3192  newdef->colname = cmd->name;
3193  newdef->identity = def->generated_when;
3194  cmd->def = (Node *) newdef;
3195 
3196  attnum = get_attnum(relid, cmd->name);
3197 
3198  /*
3199  * if attribute not found, something will error about it
3200  * later
3201  */
3202  if (attnum != InvalidAttrNumber)
3203  generateSerialExtraStmts(&cxt, newdef,
3204  get_atttype(relid, attnum),
3205  def->options, true,
3206  NULL, NULL);
3207 
3208  newcmds = lappend(newcmds, cmd);
3209  break;
3210  }
3211 
3212  case AT_SetIdentity:
3213  {
3214  /*
3215  * Create an ALTER SEQUENCE statement for the internal
3216  * sequence of the identity column.
3217  */
3218  ListCell *lc;
3219  List *newseqopts = NIL;
3220  List *newdef = NIL;
3222 
3223  /*
3224  * Split options into those handled by ALTER SEQUENCE and
3225  * those for ALTER TABLE proper.
3226  */
3227  foreach(lc, castNode(List, cmd->def))
3228  {
3229  DefElem *def = lfirst_node(DefElem, lc);
3230 
3231  if (strcmp(def->defname, "generated") == 0)
3232  newdef = lappend(newdef, def);
3233  else
3234  newseqopts = lappend(newseqopts, def);
3235  }
3236 
3237  attnum = get_attnum(relid, cmd->name);
3238 
3239  if (attnum)
3240  {
3241  Oid seq_relid = getIdentitySequence(relid, attnum, true);
3242 
3243  if (seq_relid)
3244  {
3245  AlterSeqStmt *seqstmt;
3246 
3247  seqstmt = makeNode(AlterSeqStmt);
3249  get_rel_name(seq_relid), -1);
3250  seqstmt->options = newseqopts;
3251  seqstmt->for_identity = true;
3252  seqstmt->missing_ok = false;
3253 
3254  cxt.alist = lappend(cxt.alist, seqstmt);
3255  }
3256  }
3257 
3258  /*
3259  * If column was not found or was not an identity column,
3260  * we just let the ALTER TABLE command error out later.
3261  */
3262 
3263  cmd->def = (Node *) newdef;
3264  newcmds = lappend(newcmds, cmd);
3265  break;
3266  }
3267 
3268  case AT_AttachPartition:
3269  case AT_DetachPartition:
3270  {
3271  PartitionCmd *partcmd = (PartitionCmd *) cmd->def;
3272 
3273  transformPartitionCmd(&cxt, partcmd);
3274  /* assign transformed value of the partition bound */
3275  partcmd->bound = cxt.partbound;
3276  }
3277 
3278  newcmds = lappend(newcmds, cmd);
3279  break;
3280 
3281  default:
3282  newcmds = lappend(newcmds, cmd);
3283  break;
3284  }
3285  }
3286 
3287  /*
3288  * Transfer anything we already have in cxt.alist into save_alist, to keep
3289  * it separate from the output of transformIndexConstraints.
3290  */
3291  save_alist = cxt.alist;
3292  cxt.alist = NIL;
3293 
3294  /* Postprocess constraints */
3296  transformFKConstraints(&cxt, skipValidation, true);
3297  transformCheckConstraints(&cxt, false);
3298 
3299  /*
3300  * Push any index-creation commands into the ALTER, so that they can be
3301  * scheduled nicely by tablecmds.c. Note that tablecmds.c assumes that
3302  * the IndexStmt attached to an AT_AddIndex or AT_AddIndexConstraint
3303  * subcommand has already been through transformIndexStmt.
3304  */
3305  foreach(l, cxt.alist)
3306  {
3307  Node *istmt = (Node *) lfirst(l);
3308 
3309  /*
3310  * We assume here that cxt.alist contains only IndexStmts and possibly
3311  * ALTER TABLE SET NOT NULL statements generated from primary key
3312  * constraints. We absorb the subcommands of the latter directly.
3313  */
3314  if (IsA(istmt, IndexStmt))
3315  {
3316  IndexStmt *idxstmt = (IndexStmt *) istmt;
3317 
3318  idxstmt = transformIndexStmt(relid, idxstmt, queryString);
3319  newcmd = makeNode(AlterTableCmd);
3321  newcmd->def = (Node *) idxstmt;
3322  newcmds = lappend(newcmds, newcmd);
3323  }
3324  else if (IsA(istmt, AlterTableStmt))
3325  {
3326  AlterTableStmt *alterstmt = (AlterTableStmt *) istmt;
3327 
3328  newcmds = list_concat(newcmds, alterstmt->cmds);
3329  }
3330  else
3331  elog(ERROR, "unexpected stmt type %d", (int) nodeTag(istmt));
3332  }
3333  cxt.alist = NIL;
3334 
3335  /* Append any CHECK or FK constraints to the commands list */
3336  foreach(l, cxt.ckconstraints)
3337  {
3338  newcmd = makeNode(AlterTableCmd);
3339  newcmd->subtype = AT_AddConstraint;
3340  newcmd->def = (Node *) lfirst(l);
3341  newcmds = lappend(newcmds, newcmd);
3342  }
3343  foreach(l, cxt.fkconstraints)
3344  {
3345  newcmd = makeNode(AlterTableCmd);
3346  newcmd->subtype = AT_AddConstraint;
3347  newcmd->def = (Node *) lfirst(l);
3348  newcmds = lappend(newcmds, newcmd);
3349  }
3350 
3351  /* Append extended statistic objects */
3353 
3354  /* Close rel */
3355  relation_close(rel, NoLock);
3356 
3357  /*
3358  * Output results.
3359  */
3360  stmt->cmds = newcmds;
3361 
3362  result = lappend(cxt.blist, stmt);
3363  result = list_concat(result, cxt.alist);
3364  result = list_concat(result, save_alist);
3365 
3366  return result;
3367 }
#define NIL
Definition: pg_list.h:65
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
static void generateSerialExtraStmts(CreateStmtContext *cxt, ColumnDef *column, Oid seqtypid, List *seqoptions, bool for_identity, char **snamespace_p, char **sname_p)
char generated_when
Definition: parsenodes.h:2141
#define RelationGetDescr(relation)
Definition: rel.h:448
#define castNode(_type_, nodeptr)
Definition: nodes.h:594
char identity
Definition: parsenodes.h:655
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
List * constraints
Definition: parsenodes.h:661
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:1754
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:144
#define AccessShareLock
Definition: lockdefs.h:36
Definition: nodes.h:525
List * list_concat(List *list1, const List *list2)
Definition: list.c:516
AlterTableType subtype
Definition: parsenodes.h:1840
Form_pg_class rd_rel
Definition: rel.h:83
unsigned int Oid
Definition: postgres_ext.h:31
Oid getIdentitySequence(Oid relid, AttrNumber attnum, bool missing_ok)
Definition: pg_depend.c:780
#define OidIsValid(objectId)
Definition: c.h:645
DefElem * makeDefElem(char *name, Node *arg, int location)
Definition: makefuncs.c:544
List * options
Definition: parsenodes.h:2533
List * options
Definition: parsenodes.h:2153
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:43
#define list_make1(x1)
Definition: pg_list.h:227
ParseState * pstate
Definition: parse_utilcmd.c:78
Node * cooked_default
Definition: parsenodes.h:654
Oid indexOid
Definition: parsenodes.h:2763
RangeVar * relation
Definition: parse_utilcmd.c:80
IndexStmt * pkey
Definition: parse_utilcmd.c:95
#define ERROR
Definition: elog.h:43
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:48
#define lfirst_node(type, lc)
Definition: pg_list.h:193
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3094
#define NoLock
Definition: lockdefs.h:34
AttrNumber get_attnum(Oid relid, const char *attname)
Definition: lsyscache.c:806
RangeTblEntry * addRangeTableEntryForRelation(ParseState *pstate, Relation rel, int lockmode, Alias *alias, bool inh, bool inFromCl)
const char * p_sourcetext
Definition: parse_node.h:176
Oid get_atttype(Oid relid, AttrNumber attnum)
Definition: lsyscache.c:861
ObjectType relkind
Definition: parsenodes.h:1755
void addRTEtoQuery(ParseState *pstate, RangeTblEntry *rte, bool addToJoinList, bool addToRelNameSpace, bool addToVarNameSpace)
PartitionBoundSpec * partbound
Definition: parse_utilcmd.c:97
Node * raw_default
Definition: parsenodes.h:653
List * lappend(List *list, void *datum)
Definition: list.c:322
TypeName * makeTypeNameFromOid(Oid typeOid, int32 typmod)
Definition: makefuncs.c:470
RangeVar * sequence
Definition: parsenodes.h:2532
int16 attnum
Definition: pg_attribute.h:79
#define makeNode(_type_)
Definition: nodes.h:573
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:206
#define lfirst(lc)
Definition: pg_list.h:190
static void transformColumnDefinition(CreateStmtContext *cxt, ColumnDef *column)
PartitionBoundSpec * bound
Definition: parsenodes.h:859
TypeName * typeName
Definition: parsenodes.h:647
static void transformPartitionCmd(CreateStmtContext *cxt, PartitionCmd *cmd)
static void transformFKConstraints(CreateStmtContext *cxt, bool skipValidation, bool isAddConstraint)
#define InvalidAttrNumber
Definition: attnum.h:23
#define nodeTag(nodeptr)
Definition: nodes.h:530
const char * stmtType
Definition: parse_utilcmd.c:79
static void transformExtendedStatistics(CreateStmtContext *cxt)
RangeVar * relation
Definition: parsenodes.h:1753
#define elog(elevel,...)
Definition: elog.h:228
bool for_identity
Definition: parsenodes.h:2534
char * defname
Definition: parsenodes.h:730
char * colname
Definition: parsenodes.h:646
#define copyObject(obj)
Definition: nodes.h:641
static void transformTableConstraint(CreateStmtContext *cxt, Constraint *constraint)
static void transformIndexConstraints(CreateStmtContext *cxt)
IndexStmt * transformIndexStmt(Oid relid, IndexStmt *stmt, const char *queryString)
Definition: pg_list.h:50
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1730
int16 AttrNumber
Definition: attnum.h:21
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition: makefuncs.c:420
static void transformCheckConstraints(CreateStmtContext *cxt, bool skipValidation)
Oid typenameTypeId(ParseState *pstate, const TypeName *typeName)
Definition: parse_type.c:291

◆ transformCreateSchemaStmt()

List* transformCreateSchemaStmt ( CreateSchemaStmt stmt)

Definition at line 3548 of file parse_utilcmd.c.

References CreateSchemaStmtContext::authrole, CreateSchemaStmt::authrole, element(), elog, ERROR, CreateSchemaStmtContext::grants, CreateSchemaStmtContext::indexes, lappend(), lfirst, list_concat(), NIL, nodeTag, CreateStmt::relation, CreateTrigStmt::relation, IndexStmt::relation, CreateSchemaStmt::schemaElts, RangeVar::schemaname, CreateSchemaStmtContext::schemaname, CreateSchemaStmt::schemaname, CreateSeqStmt::sequence, CreateSchemaStmtContext::sequences, setSchemaName(), CreateSchemaStmtContext::stmtType, T_CreateSeqStmt, T_CreateStmt, T_CreateTrigStmt, T_GrantStmt, T_IndexStmt, T_ViewStmt, CreateSchemaStmtContext::tables, CreateSchemaStmtContext::triggers, ViewStmt::view, and CreateSchemaStmtContext::views.

Referenced by CreateSchemaCommand().

3549 {
3551  List *result;
3552  ListCell *elements;
3553 
3554  cxt.stmtType = "CREATE SCHEMA";
3555  cxt.schemaname = stmt->schemaname;
3556  cxt.authrole = (RoleSpec *) stmt->authrole;
3557  cxt.sequences = NIL;
3558  cxt.tables = NIL;
3559  cxt.views = NIL;
3560  cxt.indexes = NIL;
3561  cxt.triggers = NIL;
3562  cxt.grants = NIL;
3563 
3564  /*
3565  * Run through each schema element in the schema element list. Separate
3566  * statements by type, and do preliminary analysis.
3567  */
3568  foreach(elements, stmt->schemaElts)
3569  {
3570  Node *element = lfirst(elements);
3571 
3572  switch (nodeTag(element))
3573  {
3574  case T_CreateSeqStmt:
3575  {
3576  CreateSeqStmt *elp = (CreateSeqStmt *) element;
3577 
3579  cxt.sequences = lappend(cxt.sequences, element);
3580  }
3581  break;
3582 
3583  case T_CreateStmt:
3584  {
3585  CreateStmt *elp = (CreateStmt *) element;
3586 
3588 
3589  /*
3590  * XXX todo: deal with constraints
3591  */
3592  cxt.tables = lappend(cxt.tables, element);
3593  }
3594  break;
3595 
3596  case T_ViewStmt:
3597  {
3598  ViewStmt *elp = (ViewStmt *) element;
3599 
3600  setSchemaName(cxt.schemaname, &elp->view->schemaname);
3601 
3602  /*
3603  * XXX todo: deal with references between views
3604  */
3605  cxt.views = lappend(cxt.views, element);
3606  }
3607  break;
3608 
3609  case T_IndexStmt:
3610  {
3611  IndexStmt *elp = (IndexStmt *) element;
3612 
3614  cxt.indexes = lappend(cxt.indexes, element);
3615  }
3616  break;
3617 
3618  case T_CreateTrigStmt:
3619  {
3620  CreateTrigStmt *elp = (CreateTrigStmt *) element;
3621 
3623  cxt.triggers = lappend(cxt.triggers, element);
3624  }
3625  break;
3626 
3627  case T_GrantStmt:
3628  cxt.grants = lappend(cxt.grants, element);
3629  break;
3630 
3631  default:
3632  elog(ERROR, "unrecognized node type: %d",
3633  (int) nodeTag(element));
3634  }
3635  }
3636 
3637  result = NIL;
3638  result = list_concat(result, cxt.sequences);
3639  result = list_concat(result, cxt.tables);
3640  result = list_concat(result, cxt.views);
3641  result = list_concat(result, cxt.indexes);
3642  result = list_concat(result, cxt.triggers);
3643  result = list_concat(result, cxt.grants);
3644 
3645  return result;
3646 }
RangeVar * relation
Definition: parsenodes.h:2049
#define NIL
Definition: pg_list.h:65
Definition: nodes.h:525
List * list_concat(List *list1, const List *list2)
Definition: list.c:516
RangeVar * view
Definition: parsenodes.h:3092
char * schemaname
Definition: primnodes.h:67
RangeVar * relation
Definition: parsenodes.h:2753
RoleSpec * authrole
Definition: parsenodes.h:1735
#define ERROR
Definition: elog.h:43
List * lappend(List *list, void *datum)
Definition: list.c:322
static chr element(struct vars *v, const chr *startp, const chr *endp)
Definition: regc_locale.c:380
RangeVar * sequence
Definition: parsenodes.h:2522
#define lfirst(lc)
Definition: pg_list.h:190
static void setSchemaName(char *context_schema, char **stmt_schema_name)
#define nodeTag(nodeptr)
Definition: nodes.h:530
#define elog(elevel,...)
Definition: elog.h:228
RangeVar * relation
Definition: parsenodes.h:2408
Definition: pg_list.h:50

◆ transformCreateStmt()

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

Definition at line 165 of file parse_utilcmd.c.

References CreateStmtContext::alist, Assert, CreateStmtContext::blist, cancel_parser_errposition_callback(), CreateStmtContext::ckconstraints, CreateStmtContext::columns, CreateStmt::constraints, copyObject, element(), elog, ereport, errcode(), errmsg(), ERROR, CreateStmtContext::extstats, CreateStmtContext::fkconstraints, get_namespace_name(), CreateStmt::if_not_exists, CreateStmtContext::inh_indexes, CreateStmtContext::inhRelations, CreateStmt::inhRelations, IsA, CreateStmtContext::isalter, CreateStmtContext::isforeign, CreateStmtContext::ispartitioned, CreateStmtContext::ixconstraints, lappend(), lfirst, list_concat(), RangeVar::location, make_parsestate(), NIL, nodeTag, NoLock, NOTICE, CreateStmtContext::ofType, CreateStmt::ofTypename, OidIsValid, ParseState::p_sourcetext, CreateStmtContext::partbound, CreateStmt::partbound, CreateStmt::partspec, CreateStmtContext::pkey, CreateStmtContext::pstate, RangeVarGetAndCheckCreationNamespace(), CreateStmtContext::rel, CreateStmtContext::relation, CreateStmt::relation, RangeVar::relname, RangeVar::relpersistence, RangeVar::schemaname, setup_parser_errposition_callback(), CreateStmtContext::stmtType, T_ColumnDef, T_Constraint, T_TableLikeClause, CreateStmt::tableElts, transformCheckConstraints(), transformColumnDefinition(), transformExtendedStatistics(), transformFKConstraints(), transformIndexConstraints(), transformOfType(), transformTableConstraint(), and transformTableLikeClause().

Referenced by ProcessUtilitySlow().

166 {
167  ParseState *pstate;
168  CreateStmtContext cxt;
169  List *result;
170  List *save_alist;
171  ListCell *elements;
172  Oid namespaceid;
173  Oid existing_relid;
174  ParseCallbackState pcbstate;
175  bool is_foreign_table = IsA(stmt, CreateForeignTableStmt);
176 
177  /*
178  * We must not scribble on the passed-in CreateStmt, so copy it. (This is
179  * overkill, but easy.)
180  */
181  stmt = copyObject(stmt);
182 
183  /* Set up pstate */
184  pstate = make_parsestate(NULL);
185  pstate->p_sourcetext = queryString;
186 
187  /*
188  * Look up the creation namespace. This also checks permissions on the
189  * target namespace, locks it against concurrent drops, checks for a
190  * preexisting relation in that namespace with the same name, and updates
191  * stmt->relation->relpersistence if the selected namespace is temporary.
192  */
193  setup_parser_errposition_callback(&pcbstate, pstate,
194  stmt->relation->location);
195  namespaceid =
197  &existing_relid);
199 
200  /*
201  * If the relation already exists and the user specified "IF NOT EXISTS",
202  * bail out with a NOTICE.
203  */
204  if (stmt->if_not_exists && OidIsValid(existing_relid))
205  {
206  ereport(NOTICE,
207  (errcode(ERRCODE_DUPLICATE_TABLE),
208  errmsg("relation \"%s\" already exists, skipping",
209  stmt->relation->relname)));
210  return NIL;
211  }
212 
213  /*
214  * If the target relation name isn't schema-qualified, make it so. This
215  * prevents some corner cases in which added-on rewritten commands might
216  * think they should apply to other relations that have the same name and
217  * are earlier in the search path. But a local temp table is effectively
218  * specified to be in pg_temp, so no need for anything extra in that case.
219  */
220  if (stmt->relation->schemaname == NULL
221  && stmt->relation->relpersistence != RELPERSISTENCE_TEMP)
222  stmt->relation->schemaname = get_namespace_name(namespaceid);
223 
224  /* Set up CreateStmtContext */
225  cxt.pstate = pstate;
226  if (IsA(stmt, CreateForeignTableStmt))
227  {
228  cxt.stmtType = "CREATE FOREIGN TABLE";
229  cxt.isforeign = true;
230  }
231  else
232  {
233  cxt.stmtType = "CREATE TABLE";
234  cxt.isforeign = false;
235  }
236  cxt.relation = stmt->relation;
237  cxt.rel = NULL;
238  cxt.inhRelations = stmt->inhRelations;
239  cxt.isalter = false;
240  cxt.columns = NIL;
241  cxt.ckconstraints = NIL;
242  cxt.fkconstraints = NIL;
243  cxt.ixconstraints = NIL;
244  cxt.inh_indexes = NIL;
245  cxt.extstats = NIL;
246  cxt.blist = NIL;
247  cxt.alist = NIL;
248  cxt.pkey = NULL;
249  cxt.ispartitioned = stmt->partspec != NULL;
250  cxt.partbound = stmt->partbound;
251  cxt.ofType = (stmt->ofTypename != NULL);
252 
253  Assert(!stmt->ofTypename || !stmt->inhRelations); /* grammar enforces */
254 
255  if (stmt->ofTypename)
256  transformOfType(&cxt, stmt->ofTypename);
257 
258  if (stmt->partspec)
259  {
260  if (stmt->inhRelations && !stmt->partbound)
261  ereport(ERROR,
262  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
263  errmsg("cannot create partitioned table as inheritance child")));
264  }
265 
266  /*
267  * Run through each primary element in the table creation clause. Separate
268  * column defs from constraints, and do preliminary analysis.
269  */
270  foreach(elements, stmt->tableElts)
271  {
272  Node *element = lfirst(elements);
273 
274  switch (nodeTag(element))
275  {
276  case T_ColumnDef:
277  transformColumnDefinition(&cxt, (ColumnDef *) element);
278  break;
279 
280  case T_Constraint:
281  transformTableConstraint(&cxt, (Constraint *) element);
282  break;
283 
284  case T_TableLikeClause:
285  transformTableLikeClause(&cxt, (TableLikeClause *) element);
286  break;
287 
288  default:
289  elog(ERROR, "unrecognized node type: %d",
290  (int) nodeTag(element));
291  break;
292  }
293  }
294 
295  /*
296  * Transfer anything we already have in cxt.alist into save_alist, to keep
297  * it separate from the output of transformIndexConstraints. (This may
298  * not be necessary anymore, but we'll keep doing it to preserve the
299  * historical order of execution of the alist commands.)
300  */
301  save_alist = cxt.alist;
302  cxt.alist = NIL;
303 
304  Assert(stmt->constraints == NIL);
305 
306  /*
307  * Postprocess constraints that give rise to index definitions.
308  */
310 
311  /*
312  * Postprocess foreign-key constraints.
313  */
314  transformFKConstraints(&cxt, true, false);
315 
316  /*
317  * Postprocess check constraints.
318  */
319  transformCheckConstraints(&cxt, !is_foreign_table ? true : false);
320 
321  /*
322  * Postprocess extended statistics.
323  */
325 
326  /*
327  * Output results.
328  */
329  stmt->tableElts = cxt.columns;
330  stmt->constraints = cxt.ckconstraints;
331 
332  result = lappend(cxt.blist, stmt);
333  result = list_concat(result, cxt.alist);
334  result = list_concat(result, save_alist);
335 
336  return result;
337 }
RangeVar * relation
Definition: parsenodes.h:2049
#define NIL
Definition: pg_list.h:65
List * inhRelations
Definition: parsenodes.h:2051
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
Definition: nodes.h:525
List * list_concat(List *list1, const List *list2)
Definition: list.c:516
int errcode(int sqlerrcode)
Definition: elog.c:608
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:645
char * schemaname
Definition: primnodes.h:67
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:43
List * constraints
Definition: parsenodes.h:2056
bool if_not_exists
Definition: parsenodes.h:2061
int location
Definition: primnodes.h:73
ParseState * pstate
Definition: parse_utilcmd.c:78
PartitionBoundSpec * partbound
Definition: parsenodes.h:2053
char * relname
Definition: primnodes.h:68
RangeVar * relation
Definition: parse_utilcmd.c:80
IndexStmt * pkey
Definition: parse_utilcmd.c:95
void cancel_parser_errposition_callback(ParseCallbackState *pcbstate)
Definition: parse_node.c:160
#define ERROR
Definition: elog.h:43
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3094
#define NoLock
Definition: lockdefs.h:34
const char * p_sourcetext
Definition: parse_node.h:176
#define ereport(elevel, rest)
Definition: elog.h:141
void setup_parser_errposition_callback(ParseCallbackState *pcbstate, ParseState *pstate, int location)
Definition: parse_node.c:144
PartitionBoundSpec * partbound
Definition: parse_utilcmd.c:97
List * lappend(List *list, void *datum)
Definition: list.c:322
static chr element(struct vars *v, const chr *startp, const chr *endp)
Definition: regc_locale.c:380
Oid RangeVarGetAndCheckCreationNamespace(RangeVar *relation, LOCKMODE lockmode, Oid *existing_relation_id)
Definition: namespace.c:526
#define NOTICE
Definition: elog.h:37
List * tableElts
Definition: parsenodes.h:2050
static void transformOfType(CreateStmtContext *cxt, TypeName *ofTypename)
#define Assert(condition)
Definition: c.h:739
#define lfirst(lc)
Definition: pg_list.h:190
static void transformColumnDefinition(CreateStmtContext *cxt, ColumnDef *column)
static void transformFKConstraints(CreateStmtContext *cxt, bool skipValidation, bool isAddConstraint)
#define nodeTag(nodeptr)
Definition: nodes.h:530
const char * stmtType
Definition: parse_utilcmd.c:79
static void transformExtendedStatistics(CreateStmtContext *cxt)
char relpersistence
Definition: primnodes.h:71
int errmsg(const char *fmt,...)
Definition: elog.c:822
#define elog(elevel,...)
Definition: elog.h:228
#define copyObject(obj)
Definition: nodes.h:641
static void transformTableConstraint(CreateStmtContext *cxt, Constraint *constraint)
static void transformIndexConstraints(CreateStmtContext *cxt)
PartitionSpec * partspec
Definition: parsenodes.h:2054
Definition: pg_list.h:50
static void transformTableLikeClause(CreateStmtContext *cxt, TableLikeClause *table_like_clause)
TypeName * ofTypename
Definition: parsenodes.h:2055
static void transformCheckConstraints(CreateStmtContext *cxt, bool skipValidation)

◆ transformIndexStmt()

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

Definition at line 2598 of file parse_utilcmd.c.

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

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

2599 {
2600  ParseState *pstate;
2601  RangeTblEntry *rte;
2602  ListCell *l;
2603  Relation rel;
2604 
2605  /* Nothing to do if statement already transformed. */
2606  if (stmt->transformed)
2607  return stmt;
2608 
2609  /*
2610  * We must not scribble on the passed-in IndexStmt, so copy it. (This is
2611  * overkill, but easy.)
2612  */
2613  stmt = copyObject(stmt);
2614 
2615  /* Set up pstate */
2616  pstate = make_parsestate(NULL);
2617  pstate->p_sourcetext = queryString;
2618 
2619  /*
2620  * Put the parent table into the rtable so that the expressions can refer
2621  * to its fields without qualification. Caller is responsible for locking
2622  * relation, but we still need to open it.
2623  */
2624  rel = relation_open(relid, NoLock);
2625  rte = addRangeTableEntryForRelation(pstate, rel,
2627  NULL, false, true);
2628 
2629  /* no to join list, yes to namespaces */
2630  addRTEtoQuery(pstate, rte, false, true, true);
2631 
2632  /* take care of the where clause */
2633  if (stmt->whereClause)
2634  {
2635  stmt->whereClause = transformWhereClause(pstate,
2636  stmt->whereClause,
2638  "WHERE");
2639  /* we have to fix its collations too */
2640  assign_expr_collations(pstate, stmt->whereClause);
2641  }
2642 
2643  /* take care of any index expressions */
2644  foreach(l, stmt->indexParams)
2645  {
2646  IndexElem *ielem = (IndexElem *) lfirst(l);
2647 
2648  if (ielem->expr)
2649  {
2650  /* Extract preliminary index col name before transforming expr */
2651  if (ielem->indexcolname == NULL)
2652  ielem->indexcolname = FigureIndexColname(ielem->expr);
2653 
2654  /* Now do parse transformation of the expression */
2655  ielem->expr = transformExpr(pstate, ielem->expr,
2657 
2658  /* We have to fix its collations too */
2659  assign_expr_collations(pstate, ielem->expr);
2660 
2661  /*
2662  * transformExpr() should have already rejected subqueries,
2663  * aggregates, window functions, and SRFs, based on the EXPR_KIND_
2664  * for an index expression.
2665  *
2666  * DefineIndex() will make more checks.
2667  */
2668  }
2669  }
2670 
2671  /*
2672  * Check that only the base rel is mentioned. (This should be dead code
2673  * now that add_missing_from is history.)
2674  */
2675  if (list_length(pstate->p_rtable) != 1)
2676  ereport(ERROR,
2677  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2678  errmsg("index expressions and predicates can refer only to the table being indexed")));
2679 
2680  free_parsestate(pstate);
2681 
2682  /* Close relation */
2683  table_close(rel, NoLock);
2684 
2685  /* Mark statement as successfully transformed */
2686  stmt->transformed = true;
2687 
2688  return stmt;
2689 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:144
Node * whereClause
Definition: parsenodes.h:2760
#define AccessShareLock
Definition: lockdefs.h:36
int errcode(int sqlerrcode)
Definition: elog.c:608
char * FigureIndexColname(Node *node)
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:43
void assign_expr_collations(ParseState *pstate, Node *expr)
Node * expr
Definition: parsenodes.h:700
#define ERROR
Definition: elog.h:43
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:48
#define NoLock
Definition: lockdefs.h:34
bool transformed
Definition: parsenodes.h:2770
char * indexcolname
Definition: parsenodes.h:701
RangeTblEntry * addRangeTableEntryForRelation(ParseState *pstate, Relation rel, int lockmode, Alias *alias, bool inh, bool inFromCl)
const char * p_sourcetext
Definition: parse_node.h:176
#define ereport(elevel, rest)
Definition: elog.h:141
void addRTEtoQuery(ParseState *pstate, RangeTblEntry *rte, bool addToJoinList, bool addToRelNameSpace, bool addToVarNameSpace)
#define lfirst(lc)
Definition: pg_list.h:190
Node * transformWhereClause(ParseState *pstate, Node *clause, ParseExprKind exprKind, const char *constructName)
List * indexParams
Definition: parsenodes.h:2756
static int list_length(const List *l)
Definition: pg_list.h:169
int errmsg(const char *fmt,...)
Definition: elog.c:822
#define copyObject(obj)
Definition: nodes.h:641
void free_parsestate(ParseState *pstate)
Definition: parse_node.c:76
List * p_rtable
Definition: parse_node.h:177

◆ transformPartitionBound()

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

Definition at line 3718 of file parse_utilcmd.c.

References Assert, castNode, 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, linitial, list_length(), PartitionBoundSpec::listdatums, PartitionBoundSpec::lowerdatums, NIL, parser_errposition(), PartitionKeyData::partattrs, 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().

3720 {
3721  PartitionBoundSpec *result_spec;
3723  char strategy = get_partition_strategy(key);
3724  int partnatts = get_partition_natts(key);
3725  List *partexprs = get_partition_exprs(key);
3726 
3727  /* Avoid scribbling on input */
3728  result_spec = copyObject(spec);
3729 
3730  if (spec->is_default)
3731  {
3732  /*
3733  * Hash partitioning does not support a default partition; there's no
3734  * use case for it (since the set of partitions to create is perfectly
3735  * defined), and if users do get into it accidentally, it's hard to
3736  * back out from it afterwards.
3737  */
3738  if (strategy == PARTITION_STRATEGY_HASH)
3739  ereport(ERROR,
3740  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3741  errmsg("a hash-partitioned table may not have a default partition")));
3742 
3743  /*
3744  * In case of the default partition, parser had no way to identify the
3745  * partition strategy. Assign the parent's strategy to the default
3746  * partition bound spec.
3747  */
3748  result_spec->strategy = strategy;
3749 
3750  return result_spec;
3751  }
3752 
3753  if (strategy == PARTITION_STRATEGY_HASH)
3754  {
3755  if (spec->strategy != PARTITION_STRATEGY_HASH)
3756  ereport(ERROR,
3757  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3758  errmsg("invalid bound specification for a hash partition"),
3759  parser_errposition(pstate, exprLocation((Node *) spec))));
3760 
3761  if (spec->modulus <= 0)
3762  ereport(ERROR,
3763  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3764  errmsg("modulus for hash partition must be a positive integer")));
3765 
3766  Assert(spec->remainder >= 0);
3767 
3768  if (spec->remainder >= spec->modulus)
3769  ereport(ERROR,
3770  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3771  errmsg("remainder for hash partition must be less than modulus")));
3772  }
3773  else if (strategy == PARTITION_STRATEGY_LIST)
3774  {
3775  ListCell *cell;
3776  char *colname;
3777  Oid coltype;
3778  int32 coltypmod;
3779  Oid partcollation;
3780 
3781  if (spec->strategy != PARTITION_STRATEGY_LIST)
3782  ereport(ERROR,
3783  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3784  errmsg("invalid bound specification for a list partition"),
3785  parser_errposition(pstate, exprLocation((Node *) spec))));
3786 
3787  /* Get the only column's name in case we need to output an error */
3788  if (key->partattrs[0] != 0)
3789  colname = get_attname(RelationGetRelid(parent),
3790  key->partattrs[0], false);
3791  else
3792  colname = deparse_expression((Node *) linitial(partexprs),
3794  RelationGetRelid(parent)),
3795  false, false);
3796  /* Need its type data too */
3797  coltype = get_partition_col_typid(key, 0);
3798  coltypmod = get_partition_col_typmod(key, 0);
3799  partcollation = get_partition_col_collation(key, 0);
3800 
3801  result_spec->listdatums = NIL;
3802  foreach(cell, spec->listdatums)
3803  {
3804  Node *expr = lfirst(cell);
3805  Const *value;
3806  ListCell *cell2;
3807  bool duplicate;
3808 
3809  value = transformPartitionBoundValue(pstate, expr,
3810  colname, coltype, coltypmod,
3811  partcollation);
3812 
3813  /* Don't add to the result if the value is a duplicate */
3814  duplicate = false;
3815  foreach(cell2, result_spec->listdatums)
3816  {
3817  Const *value2 = castNode(Const, lfirst(cell2));
3818 
3819  if (equal(value, value2))
3820  {
3821  duplicate = true;
3822  break;
3823  }
3824  }
3825  if (duplicate)
3826  continue;
3827 
3828  result_spec->listdatums = lappend(result_spec->listdatums,
3829  value);
3830  }
3831  }
3832  else if (strategy == PARTITION_STRATEGY_RANGE)
3833  {
3834  if (spec->strategy != PARTITION_STRATEGY_RANGE)
3835  ereport(ERROR,
3836  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3837  errmsg("invalid bound specification for a range partition"),
3838  parser_errposition(pstate, exprLocation((Node *) spec))));
3839 
3840  if (list_length(spec->lowerdatums) != partnatts)
3841  ereport(ERROR,
3842  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3843  errmsg("FROM must specify exactly one value per partitioning column")));
3844  if (list_length(spec->upperdatums) != partnatts)
3845  ereport(ERROR,
3846  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3847  errmsg("TO must specify exactly one value per partitioning column")));
3848 
3849  /*
3850  * Convert raw parse nodes into PartitionRangeDatum nodes and perform
3851  * any necessary validation.
3852  */
3853  result_spec->lowerdatums =
3855  parent);
3856  result_spec->upperdatums =
3858  parent);
3859  }
3860  else
3861  elog(ERROR, "unexpected partition strategy: %d", (int) strategy);
3862 
3863  return result_spec;
3864 }
#define NIL
Definition: pg_list.h:65
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1191
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:3011
#define castNode(_type_, nodeptr)
Definition: nodes.h:594
static int32 get_partition_col_typmod(PartitionKey key, int col)
Definition: partcache.h:90
static Oid get_partition_col_typid(PartitionKey key, int col)
Definition: partcache.h:84
static struct @145 value
Definition: nodes.h:525
static int get_partition_natts(PartitionKey key)
Definition: partcache.h:63
int errcode(int sqlerrcode)
Definition: elog.c:608
unsigned int Oid
Definition: postgres_ext.h:31
signed int int32
Definition: c.h:347
static List * get_partition_exprs(PartitionKey key)
Definition: partcache.h:69
#define linitial(l)
Definition: pg_list.h:195
#define ERROR
Definition: elog.h:43
static Const * transformPartitionBoundValue(ParseState *pstate, Node *con, const char *colName, Oid colType, int32 colTypmod, Oid partCollation)
static List * transformPartitionRangeBounds(ParseState *pstate, List *blist, Relation parent)
List * deparse_context_for(const char *aliasname, Oid relid)
Definition: ruleutils.c:3256
#define RelationGetRelationName(relation)
Definition: rel.h:456
#define ereport(elevel, rest)
Definition: elog.h:141
List * lappend(List *list, void *datum)
Definition: list.c:322
AttrNumber * partattrs
Definition: partcache.h:28
#define PARTITION_STRATEGY_HASH
Definition: parsenodes.h:798
#define Assert(condition)
Definition: c.h:739
#define lfirst(lc)
Definition: pg_list.h:190
char * deparse_expression(Node *expr, List *dpcontext, bool forceprefix, bool showimplicit)
Definition: ruleutils.c:3197
static int list_length(const List *l)
Definition: pg_list.h:169
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110
#define PARTITION_STRATEGY_LIST
Definition: parsenodes.h:799
#define RelationGetPartitionKey(relation)
Definition: rel.h:603
static Oid get_partition_col_collation(PartitionKey key, int col)
Definition: partcache.h:96
#define PARTITION_STRATEGY_RANGE
Definition: parsenodes.h:800
int errmsg(const char *fmt,...)
Definition: elog.c:822
#define elog(elevel,...)
Definition: elog.h:228
char * get_attname(Oid relid, AttrNumber attnum, bool missing_ok)
Definition: lsyscache.c:775
#define copyObject(obj)
Definition: nodes.h:641
static int get_partition_strategy(PartitionKey key)
Definition: partcache.h:57
Definition: pg_list.h:50
#define RelationGetRelid(relation)
Definition: rel.h:422

◆ transformRuleStmt()

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

Definition at line 2705 of file parse_utilcmd.c.

References AccessExclusiveLock, AccessShareLock, generate_unaccent_rules::action, RuleStmt::actions, addRangeTableEntryForRelation(), addRTEtoQuery(), assign_expr_collations(), CMD_DELETE, CMD_INSERT, CMD_NOTHING, CMD_SELECT, CMD_UPDATE, CMD_UTILITY, Query::commandType, copyObject, Query::cteList, elog, ereport, errcode(), errmsg(), ERROR, RuleStmt::event, EXPR_KIND_WHERE, free_parsestate(), getInsertSelectQuery(), Query::jointree, lappend(), lfirst, list_length(), list_make1, make_parsestate(), makeAlias(), makeFromExpr(), makeNode, NIL, NoLock, ParseState::p_joinlist, ParseState::p_rtable, ParseState::p_sourcetext, PRS2_NEW_VARNO, PRS2_OLD_VARNO, rangeTableEntry_used(), RelationData::rd_rel, RuleStmt::relation, RangeTblEntry::requiredPerms, Query::rtable, Query::setOperations, table_close(), table_openrv(), transformStmt(), transformWhereClause(), and RuleStmt::whereClause.

Referenced by DefineRule().

2707 {
2708  Relation rel;
2709  ParseState *pstate;
2710  RangeTblEntry *oldrte;
2711  RangeTblEntry *newrte;
2712 
2713  /*
2714  * To avoid deadlock, make sure the first thing we do is grab
2715  * AccessExclusiveLock on the target relation. This will be needed by
2716  * DefineQueryRewrite(), and we don't want to grab a lesser lock
2717  * beforehand.
2718  */
2720 
2721  if (rel->rd_rel->relkind == RELKIND_MATVIEW)
2722  ereport(ERROR,
2723  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2724  errmsg("rules on materialized views are not supported")));
2725 
2726  /* Set up pstate */
2727  pstate = make_parsestate(NULL);
2728  pstate->p_sourcetext = queryString;
2729 
2730  /*
2731  * NOTE: 'OLD' must always have a varno equal to 1 and 'NEW' equal to 2.
2732  * Set up their RTEs in the main pstate for use in parsing the rule
2733  * qualification.
2734  */
2735  oldrte = addRangeTableEntryForRelation(pstate, rel,
2737  makeAlias("old", NIL),
2738  false, false);
2739  newrte = addRangeTableEntryForRelation(pstate, rel,
2741  makeAlias("new", NIL),
2742  false, false);
2743  /* Must override addRangeTableEntry's default access-check flags */
2744  oldrte->requiredPerms = 0;
2745  newrte->requiredPerms = 0;
2746 
2747  /*
2748  * They must be in the namespace too for lookup purposes, but only add the
2749  * one(s) that are relevant for the current kind of rule. In an UPDATE
2750  * rule, quals must refer to OLD.field or NEW.field to be unambiguous, but
2751  * there's no need to be so picky for INSERT & DELETE. We do not add them
2752  * to the joinlist.
2753  */
2754  switch (stmt->event)
2755  {
2756  case CMD_SELECT:
2757  addRTEtoQuery(pstate, oldrte, false, true, true);
2758  break;
2759  case CMD_UPDATE:
2760  addRTEtoQuery(pstate, oldrte, false, true, true);
2761  addRTEtoQuery(pstate, newrte, false, true, true);
2762  break;
2763  case CMD_INSERT:
2764  addRTEtoQuery(pstate, newrte, false, true, true);
2765  break;
2766  case CMD_DELETE:
2767  addRTEtoQuery(pstate, oldrte, false, true, true);
2768  break;
2769  default:
2770  elog(ERROR, "unrecognized event type: %d",
2771  (int) stmt->event);
2772  break;
2773  }
2774 
2775  /* take care of the where clause */
2776  *whereClause = transformWhereClause(pstate,
2777  (Node *) copyObject(stmt->whereClause),
2779  "WHERE");
2780  /* we have to fix its collations too */
2781  assign_expr_collations(pstate, *whereClause);
2782 
2783  /* this is probably dead code without add_missing_from: */
2784  if (list_length(pstate->p_rtable) != 2) /* naughty, naughty... */
2785  ereport(ERROR,
2786  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2787  errmsg("rule WHERE condition cannot contain references to other relations")));
2788 
2789  /*
2790  * 'instead nothing' rules with a qualification need a query rangetable so
2791  * the rewrite handler can add the negated rule qualification to the
2792  * original query. We create a query with the new command type CMD_NOTHING
2793  * here that is treated specially by the rewrite system.
2794  */
2795  if (stmt->actions == NIL)
2796  {
2797  Query *nothing_qry = makeNode(Query);
2798 
2799  nothing_qry->commandType = CMD_NOTHING;
2800  nothing_qry->rtable = pstate->p_rtable;
2801  nothing_qry->jointree = makeFromExpr(NIL, NULL); /* no join wanted */
2802 
2803  *actions = list_make1(nothing_qry);
2804  }
2805  else
2806  {
2807  ListCell *l;
2808  List *newactions = NIL;
2809 
2810  /*
2811  * transform each statement, like parse_sub_analyze()
2812  */
2813  foreach(l, stmt->actions)
2814  {
2815  Node *action = (Node *) lfirst(l);
2816  ParseState *sub_pstate = make_parsestate(NULL);
2817  Query *sub_qry,
2818  *top_subqry;
2819  bool has_old,
2820  has_new;
2821 
2822  /*
2823  * Since outer ParseState isn't parent of inner, have to pass down
2824  * the query text by hand.
2825  */
2826  sub_pstate->p_sourcetext = queryString;
2827 
2828  /*
2829  * Set up OLD/NEW in the rtable for this statement. The entries
2830  * are added only to relnamespace, not varnamespace, because we
2831  * don't want them to be referred to by unqualified field names
2832  * nor "*" in the rule actions. We decide later whether to put
2833  * them in the joinlist.
2834  */
2835  oldrte = addRangeTableEntryForRelation(sub_pstate, rel,
2837  makeAlias("old", NIL),
2838  false, false);
2839  newrte = addRangeTableEntryForRelation(sub_pstate, rel,
2841  makeAlias("new", NIL),
2842  false, false);
2843  oldrte->requiredPerms = 0;
2844  newrte->requiredPerms = 0;
2845  addRTEtoQuery(sub_pstate, oldrte, false, true, false);
2846  addRTEtoQuery(sub_pstate, newrte, false, true, false);
2847 
2848  /* Transform the rule action statement */
2849  top_subqry = transformStmt(sub_pstate,
2850  (Node *) copyObject(action));
2851 
2852  /*
2853  * We cannot support utility-statement actions (eg NOTIFY) with
2854  * nonempty rule WHERE conditions, because there's no way to make
2855  * the utility action execute conditionally.
2856  */
2857  if (top_subqry->commandType == CMD_UTILITY &&
2858  *whereClause != NULL)
2859  ereport(ERROR,
2860  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2861  errmsg("rules with WHERE conditions can only have SELECT, INSERT, UPDATE, or DELETE actions")));
2862 
2863  /*
2864  * If the action is INSERT...SELECT, OLD/NEW have been pushed down
2865  * into the SELECT, and that's what we need to look at. (Ugly
2866  * kluge ... try to fix this when we redesign querytrees.)
2867  */
2868  sub_qry = getInsertSelectQuery(top_subqry, NULL);
2869 
2870  /*
2871  * If the sub_qry is a setop, we cannot attach any qualifications
2872  * to it, because the planner won't notice them. This could
2873  * perhaps be relaxed someday, but for now, we may as well reject
2874  * such a rule immediately.
2875  */
2876  if (sub_qry->setOperations != NULL && *whereClause != NULL)
2877  ereport(ERROR,
2878  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2879  errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
2880 
2881  /*
2882  * Validate action's use of OLD/NEW, qual too
2883  */
2884  has_old =
2885  rangeTableEntry_used((Node *) sub_qry, PRS2_OLD_VARNO, 0) ||
2886  rangeTableEntry_used(*whereClause, PRS2_OLD_VARNO, 0);
2887  has_new =
2888  rangeTableEntry_used((Node *) sub_qry, PRS2_NEW_VARNO, 0) ||
2889  rangeTableEntry_used(*whereClause, PRS2_NEW_VARNO, 0);
2890 
2891  switch (stmt->event)
2892  {
2893  case CMD_SELECT:
2894  if (has_old)
2895  ereport(ERROR,
2896  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2897  errmsg("ON SELECT rule cannot use OLD")));
2898  if (has_new)
2899  ereport(ERROR,
2900  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2901  errmsg("ON SELECT rule cannot use NEW")));
2902  break;
2903  case CMD_UPDATE:
2904  /* both are OK */
2905  break;
2906  case CMD_INSERT:
2907  if (has_old)
2908  ereport(ERROR,
2909  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2910  errmsg("ON INSERT rule cannot use OLD")));
2911  break;
2912  case CMD_DELETE:
2913  if (has_new)
2914  ereport(ERROR,
2915  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2916  errmsg("ON DELETE rule cannot use NEW")));
2917  break;
2918  default:
2919  elog(ERROR, "unrecognized event type: %d",
2920  (int) stmt->event);
2921  break;
2922  }
2923 
2924  /*
2925  * OLD/NEW are not allowed in WITH queries, because they would
2926  * amount to outer references for the WITH, which we disallow.
2927  * However, they were already in the outer rangetable when we
2928  * analyzed the query, so we have to check.
2929  *
2930  * Note that in the INSERT...SELECT case, we need to examine the
2931  * CTE lists of both top_subqry and sub_qry.
2932  *
2933  * Note that we aren't digging into the body of the query looking
2934  * for WITHs in nested sub-SELECTs. A WITH down there can
2935  * legitimately refer to OLD/NEW, because it'd be an
2936  * indirect-correlated outer reference.
2937  */
2938  if (rangeTableEntry_used((Node *) top_subqry->cteList,
2939  PRS2_OLD_VARNO, 0) ||
2940  rangeTableEntry_used((Node *) sub_qry->cteList,
2941  PRS2_OLD_VARNO, 0))
2942  ereport(ERROR,
2943  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2944  errmsg("cannot refer to OLD within WITH query")));
2945  if (rangeTableEntry_used((Node *) top_subqry->cteList,
2946  PRS2_NEW_VARNO, 0) ||
2947  rangeTableEntry_used((Node *) sub_qry->cteList,
2948  PRS2_NEW_VARNO, 0))
2949  ereport(ERROR,
2950  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2951  errmsg("cannot refer to NEW within WITH query")));
2952 
2953  /*
2954  * For efficiency's sake, add OLD to the rule action's jointree
2955  * only if it was actually referenced in the statement or qual.
2956  *
2957  * For INSERT, NEW is not really a relation (only a reference to
2958  * the to-be-inserted tuple) and should never be added to the
2959  * jointree.
2960  *
2961  * For UPDATE, we treat NEW as being another kind of reference to
2962  * OLD, because it represents references to *transformed* tuples
2963  * of the existing relation. It would be wrong to enter NEW
2964  * separately in the jointree, since that would cause a double
2965  * join of the updated relation. It's also wrong to fail to make
2966  * a jointree entry if only NEW and not OLD is mentioned.
2967  */
2968  if (has_old || (has_new && stmt->event == CMD_UPDATE))
2969  {
2970  /*
2971  * If sub_qry is a setop, manipulating its jointree will do no
2972  * good at all, because the jointree is dummy. (This should be
2973  * a can't-happen case because of prior tests.)
2974  */
2975  if (sub_qry->setOperations != NULL)
2976  ereport(ERROR,
2977  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2978  errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
2979  /* hack so we can use addRTEtoQuery() */
2980  sub_pstate->p_rtable = sub_qry->rtable;
2981  sub_pstate->p_joinlist = sub_qry->jointree->fromlist;
2982  addRTEtoQuery(sub_pstate, oldrte, true, false, false);
2983  sub_qry->jointree->fromlist = sub_pstate->p_joinlist;
2984  }
2985 
2986  newactions = lappend(newactions, top_subqry);
2987 
2988  free_parsestate(sub_pstate);
2989  }
2990 
2991  *actions = newactions;
2992  }
2993 
2994  free_parsestate(pstate);
2995 
2996  /* Close relation, but keep the exclusive lock */
2997  table_close(rel, NoLock);
2998 }
#define NIL
Definition: pg_list.h:65
Query * getInsertSelectQuery(Query *parsetree, Query ***subquery_ptr)
Definition: rewriteManip.c:921
FromExpr * makeFromExpr(List *fromlist, Node *quals)
Definition: makefuncs.c:283
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
FromExpr * jointree
Definition: parsenodes.h:138
#define AccessShareLock
Definition: lockdefs.h:36
Definition: nodes.h:525
int errcode(int sqlerrcode)
Definition: elog.c:608
List * actions
Definition: parsenodes.h:2967
AclMode requiredPerms
Definition: parsenodes.h:1096
List * fromlist
Definition: primnodes.h:1496
Form_pg_class rd_rel
Definition: rel.h:83
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:43
#define list_make1(x1)
Definition: pg_list.h:227
void assign_expr_collations(ParseState *pstate, Node *expr)
Alias * makeAlias(const char *aliasname, List *colnames)
Definition: makefuncs.c:385
List * rtable
Definition: parsenodes.h:137
#define ERROR
Definition: elog.h:43
#define NoLock
Definition: lockdefs.h:34
RangeTblEntry * addRangeTableEntryForRelation(ParseState *pstate, Relation rel, int lockmode, Alias *alias, bool inh, bool inFromCl)
const char * p_sourcetext
Definition: parse_node.h:176
#define ereport(elevel, rest)
Definition: elog.h:141
void addRTEtoQuery(ParseState *pstate, RangeTblEntry *rte, bool addToJoinList, bool addToRelNameSpace, bool addToVarNameSpace)
Query * transformStmt(ParseState *pstate, Node *parseTree)
Definition: analyze.c:254
List * lappend(List *list, void *datum)
Definition: list.c:322
#define PRS2_OLD_VARNO
Definition: primnodes.h:164
Relation table_openrv(const RangeVar *relation, LOCKMODE lockmode)
Definition: table.c:68
CmdType commandType
Definition: parsenodes.h:112
#define makeNode(_type_)
Definition: nodes.h:573
CmdType event
Definition: parsenodes.h:2965
#define lfirst(lc)
Definition: pg_list.h:190
Node * transformWhereClause(ParseState *pstate, Node *clause, ParseExprKind exprKind, const char *constructName)
Node * whereClause
Definition: parsenodes.h:2964
static int list_length(const List *l)
Definition: pg_list.h:169
#define AccessExclusiveLock
Definition: lockdefs.h:45
List * cteList
Definition: parsenodes.h:135
Node * setOperations
Definition: parsenodes.h:165
int errmsg(const char *fmt,...)
Definition: elog.c:822
#define elog(elevel,...)
Definition: elog.h:228
List * p_joinlist
Definition: parse_node.h:179
bool rangeTableEntry_used(Node *node, int rt_index, int sublevels_up)
Definition: rewriteManip.c:889
#define copyObject(obj)
Definition: nodes.h:641
RangeVar * relation
Definition: parsenodes.h:2962
void free_parsestate(ParseState *pstate)
Definition: parse_node.c:76
Definition: pg_list.h:50
#define PRS2_NEW_VARNO
Definition: primnodes.h:165
List * p_rtable
Definition: parse_node.h:177