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:345
#define NIL
Definition: pg_list.h:65
static List * get_opclass(Oid opclass, Oid actual_datatype)
Definition: c.h:588
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:445
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:570
void * stringToNode(const char *str)
Definition: read.c:89
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:638
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:596
bool transformed
Definition: parsenodes.h:2770
int errdetail(const char *fmt,...)
Definition: elog.c:860
char * indexcolname
Definition: parsenodes.h:701
#define RelationGetRelationName(relation)
Definition: rel.h:453
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:1124
#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:1172
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1385
bool unique
Definition: parsenodes.h:2765
List * untransformRelOptions(Datum options)
Definition: reloptions.c:1030
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:732
#define lfirst(lc)
Definition: pg_list.h:190
List * indexParams
Definition: parsenodes.h:2756
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
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:84
#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:784
char * get_tablespace_name(Oid spc_oid)
Definition: tablespace.c:1463
#define elog(elevel,...)
Definition: elog.h:226
int i
#define NameStr(name)
Definition: c.h:609
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:419
#define DatumGetArrayTypeP(X)
Definition: array.h:249

◆ transformAlterTableStmt()

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

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

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

◆ transformCreateSchemaStmt()

List* transformCreateSchemaStmt ( CreateSchemaStmt stmt)

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

3547 {
3549  List *result;
3550  ListCell *elements;
3551 
3552  cxt.stmtType = "CREATE SCHEMA";
3553  cxt.schemaname = stmt->schemaname;
3554  cxt.authrole = (RoleSpec *) stmt->authrole;
3555  cxt.sequences = NIL;
3556  cxt.tables = NIL;
3557  cxt.views = NIL;
3558  cxt.indexes = NIL;
3559  cxt.triggers = NIL;
3560  cxt.grants = NIL;
3561 
3562  /*
3563  * Run through each schema element in the schema element list. Separate
3564  * statements by type, and do preliminary analysis.
3565  */
3566  foreach(elements, stmt->schemaElts)
3567  {
3568  Node *element = lfirst(elements);
3569 
3570  switch (nodeTag(element))
3571  {
3572  case T_CreateSeqStmt:
3573  {
3574  CreateSeqStmt *elp = (CreateSeqStmt *) element;
3575 
3577  cxt.sequences = lappend(cxt.sequences, element);
3578  }
3579  break;
3580 
3581  case T_CreateStmt:
3582  {
3583  CreateStmt *elp = (CreateStmt *) element;
3584 
3586 
3587  /*
3588  * XXX todo: deal with constraints
3589  */
3590  cxt.tables = lappend(cxt.tables, element);
3591  }
3592  break;
3593 
3594  case T_ViewStmt:
3595  {
3596  ViewStmt *elp = (ViewStmt *) element;
3597 
3598  setSchemaName(cxt.schemaname, &elp->view->schemaname);
3599 
3600  /*
3601  * XXX todo: deal with references between views
3602  */
3603  cxt.views = lappend(cxt.views, element);
3604  }
3605  break;
3606 
3607  case T_IndexStmt:
3608  {
3609  IndexStmt *elp = (IndexStmt *) element;
3610 
3612  cxt.indexes = lappend(cxt.indexes, element);
3613  }
3614  break;
3615 
3616  case T_CreateTrigStmt:
3617  {
3618  CreateTrigStmt *elp = (CreateTrigStmt *) element;
3619 
3621  cxt.triggers = lappend(cxt.triggers, element);
3622  }
3623  break;
3624 
3625  case T_GrantStmt:
3626  cxt.grants = lappend(cxt.grants, element);
3627  break;
3628 
3629  default:
3630  elog(ERROR, "unrecognized node type: %d",
3631  (int) nodeTag(element));
3632  }
3633  }
3634 
3635  result = NIL;
3636  result = list_concat(result, cxt.sequences);
3637  result = list_concat(result, cxt.tables);
3638  result = list_concat(result, cxt.views);
3639  result = list_concat(result, cxt.indexes);
3640  result = list_concat(result, cxt.triggers);
3641  result = list_concat(result, cxt.grants);
3642 
3643  return result;
3644 }
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:226
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:570
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:638
char * schemaname
Definition: primnodes.h:67
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:44
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:161
#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:145
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:732
#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:784
#define elog(elevel,...)
Definition: elog.h:226
#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 2596 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().

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

◆ transformPartitionBound()

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

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

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

◆ transformRuleStmt()

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

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

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