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, Oid heapOid, Relation source_idx, const AttrNumber *attmap, int attmap_length, Oid *constraintOid)
 

Function Documentation

◆ generateClonedIndexStmt()

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

Definition at line 1289 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_amroutine, RelationData::rd_indextuple, RelationData::rd_indoption, IndexStmt::relation, RelationGetDescr, RelationGetRelationName, RelationGetRelid, IndexStmt::relationId, ReleaseSysCache(), RELOID, 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().

1291 {
1292  Oid source_relid = RelationGetRelid(source_idx);
1293  HeapTuple ht_idxrel;
1294  HeapTuple ht_idx;
1295  HeapTuple ht_am;
1296  Form_pg_class idxrelrec;
1297  Form_pg_index idxrec;
1298  Form_pg_am amrec;
1299  oidvector *indcollation;
1300  oidvector *indclass;
1301  IndexStmt *index;
1302  List *indexprs;
1303  ListCell *indexpr_item;
1304  Oid indrelid;
1305  int keyno;
1306  Oid keycoltype;
1307  Datum datum;
1308  bool isnull;
1309 
1310  Assert((heapRel == NULL && OidIsValid(heapRelid)) ||
1311  (heapRel != NULL && !OidIsValid(heapRelid)));
1312 
1313  /*
1314  * Fetch pg_class tuple of source index. We can't use the copy in the
1315  * relcache entry because it doesn't include optional fields.
1316  */
1317  ht_idxrel = SearchSysCache1(RELOID, ObjectIdGetDatum(source_relid));
1318  if (!HeapTupleIsValid(ht_idxrel))
1319  elog(ERROR, "cache lookup failed for relation %u", source_relid);
1320  idxrelrec = (Form_pg_class) GETSTRUCT(ht_idxrel);
1321 
1322  /* Fetch pg_index tuple for source index from relcache entry */
1323  ht_idx = source_idx->rd_indextuple;
1324  idxrec = (Form_pg_index) GETSTRUCT(ht_idx);
1325  indrelid = idxrec->indrelid;
1326 
1327  /* Fetch the pg_am tuple of the index' access method */
1328  ht_am = SearchSysCache1(AMOID, ObjectIdGetDatum(idxrelrec->relam));
1329  if (!HeapTupleIsValid(ht_am))
1330  elog(ERROR, "cache lookup failed for access method %u",
1331  idxrelrec->relam);
1332  amrec = (Form_pg_am) GETSTRUCT(ht_am);
1333 
1334  /* Extract indcollation from the pg_index tuple */
1335  datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1336  Anum_pg_index_indcollation, &isnull);
1337  Assert(!isnull);
1338  indcollation = (oidvector *) DatumGetPointer(datum);
1339 
1340  /* Extract indclass from the pg_index tuple */
1341  datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1342  Anum_pg_index_indclass, &isnull);
1343  Assert(!isnull);
1344  indclass = (oidvector *) DatumGetPointer(datum);
1345 
1346  /* Begin building the IndexStmt */
1347  index = makeNode(IndexStmt);
1348  index->relation = heapRel;
1349  index->relationId = heapRelid;
1350  index->accessMethod = pstrdup(NameStr(amrec->amname));
1351  if (OidIsValid(idxrelrec->reltablespace))
1352  index->tableSpace = get_tablespace_name(idxrelrec->reltablespace);
1353  else
1354  index->tableSpace = NULL;
1355  index->excludeOpNames = NIL;
1356  index->idxcomment = NULL;
1357  index->indexOid = InvalidOid;
1358  index->oldNode = InvalidOid;
1359  index->unique = idxrec->indisunique;
1360  index->primary = idxrec->indisprimary;
1361  index->transformed = true; /* don't need transformIndexStmt */
1362  index->concurrent = false;
1363  index->if_not_exists = false;
1364 
1365  /*
1366  * We don't try to preserve the name of the source index; instead, just
1367  * let DefineIndex() choose a reasonable name. (If we tried to preserve
1368  * the name, we'd get duplicate-relation-name failures unless the source
1369  * table was in a different schema.)
1370  */
1371  index->idxname = NULL;
1372 
1373  /*
1374  * If the index is marked PRIMARY or has an exclusion condition, it's
1375  * certainly from a constraint; else, if it's not marked UNIQUE, it
1376  * certainly isn't. If it is or might be from a constraint, we have to
1377  * fetch the pg_constraint record.
1378  */
1379  if (index->primary || index->unique || idxrec->indisexclusion)
1380  {
1381  Oid constraintId = get_index_constraint(source_relid);
1382 
1383  if (OidIsValid(constraintId))
1384  {
1385  HeapTuple ht_constr;
1386  Form_pg_constraint conrec;
1387 
1388  if (constraintOid)
1389  *constraintOid = constraintId;
1390 
1391  ht_constr = SearchSysCache1(CONSTROID,
1392  ObjectIdGetDatum(constraintId));
1393  if (!HeapTupleIsValid(ht_constr))
1394  elog(ERROR, "cache lookup failed for constraint %u",
1395  constraintId);
1396  conrec = (Form_pg_constraint) GETSTRUCT(ht_constr);
1397 
1398  index->isconstraint = true;
1399  index->deferrable = conrec->condeferrable;
1400  index->initdeferred = conrec->condeferred;
1401 
1402  /* If it's an exclusion constraint, we need the operator names */
1403  if (idxrec->indisexclusion)
1404  {
1405  Datum *elems;
1406  int nElems;
1407  int i;
1408 
1409  Assert(conrec->contype == CONSTRAINT_EXCLUSION);
1410  /* Extract operator OIDs from the pg_constraint tuple */
1411  datum = SysCacheGetAttr(CONSTROID, ht_constr,
1412  Anum_pg_constraint_conexclop,
1413  &isnull);
1414  if (isnull)
1415  elog(ERROR, "null conexclop for constraint %u",
1416  constraintId);
1417 
1419  OIDOID, sizeof(Oid), true, 'i',
1420  &elems, NULL, &nElems);
1421 
1422  for (i = 0; i < nElems; i++)
1423  {
1424  Oid operid = DatumGetObjectId(elems[i]);
1425  HeapTuple opertup;
1426  Form_pg_operator operform;
1427  char *oprname;
1428  char *nspname;
1429  List *namelist;
1430 
1431  opertup = SearchSysCache1(OPEROID,
1432  ObjectIdGetDatum(operid));
1433  if (!HeapTupleIsValid(opertup))
1434  elog(ERROR, "cache lookup failed for operator %u",
1435  operid);
1436  operform = (Form_pg_operator) GETSTRUCT(opertup);
1437  oprname = pstrdup(NameStr(operform->oprname));
1438  /* For simplicity we always schema-qualify the op name */
1439  nspname = get_namespace_name(operform->oprnamespace);
1440  namelist = list_make2(makeString(nspname),
1441  makeString(oprname));
1442  index->excludeOpNames = lappend(index->excludeOpNames,
1443  namelist);
1444  ReleaseSysCache(opertup);
1445  }
1446  }
1447 
1448  ReleaseSysCache(ht_constr);
1449  }
1450  else
1451  index->isconstraint = false;
1452  }
1453  else
1454  index->isconstraint = false;
1455 
1456  /* Get the index expressions, if any */
1457  datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1458  Anum_pg_index_indexprs, &isnull);
1459  if (!isnull)
1460  {
1461  char *exprsString;
1462 
1463  exprsString = TextDatumGetCString(datum);
1464  indexprs = (List *) stringToNode(exprsString);
1465  }
1466  else
1467  indexprs = NIL;
1468 
1469  /* Build the list of IndexElem */
1470  index->indexParams = NIL;
1471  index->indexIncludingParams = NIL;
1472 
1473  indexpr_item = list_head(indexprs);
1474  for (keyno = 0; keyno < idxrec->indnkeyatts; keyno++)
1475  {
1476  IndexElem *iparam;
1477  AttrNumber attnum = idxrec->indkey.values[keyno];
1479  keyno);
1480  int16 opt = source_idx->rd_indoption[keyno];
1481 
1482  iparam = makeNode(IndexElem);
1483 
1484  if (AttributeNumberIsValid(attnum))
1485  {
1486  /* Simple index column */
1487  char *attname;
1488 
1489  attname = get_attname(indrelid, attnum, false);
1490  keycoltype = get_atttype(indrelid, attnum);
1491 
1492  iparam->name = attname;
1493  iparam->expr = NULL;
1494  }
1495  else
1496  {
1497  /* Expressional index */
1498  Node *indexkey;
1499  bool found_whole_row;
1500 
1501  if (indexpr_item == NULL)
1502  elog(ERROR, "too few entries in indexprs list");
1503  indexkey = (Node *) lfirst(indexpr_item);
1504  indexpr_item = lnext(indexpr_item);
1505 
1506  /* Adjust Vars to match new table's column numbering */
1507  indexkey = map_variable_attnos(indexkey,
1508  1, 0,
1509  attmap, attmap_length,
1510  InvalidOid, &found_whole_row);
1511 
1512  /* As in transformTableLikeClause, reject whole-row variables */
1513  if (found_whole_row)
1514  ereport(ERROR,
1515  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1516  errmsg("cannot convert whole-row table reference"),
1517  errdetail("Index \"%s\" contains a whole-row table reference.",
1518  RelationGetRelationName(source_idx))));
1519 
1520  iparam->name = NULL;
1521  iparam->expr = indexkey;
1522 
1523  keycoltype = exprType(indexkey);
1524  }
1525 
1526  /* Copy the original index column name */
1527  iparam->indexcolname = pstrdup(NameStr(attr->attname));
1528 
1529  /* Add the collation name, if non-default */
1530  iparam->collation = get_collation(indcollation->values[keyno], keycoltype);
1531 
1532  /* Add the operator class name, if non-default */
1533  iparam->opclass = get_opclass(indclass->values[keyno], keycoltype);
1534 
1535  iparam->ordering = SORTBY_DEFAULT;
1537 
1538  /* Adjust options if necessary */
1539  if (source_idx->rd_amroutine->amcanorder)
1540  {
1541  /*
1542  * If it supports sort ordering, copy DESC and NULLS opts. Don't
1543  * set non-default settings unnecessarily, though, so as to
1544  * improve the chance of recognizing equivalence to constraint
1545  * indexes.
1546  */
1547  if (opt & INDOPTION_DESC)
1548  {
1549  iparam->ordering = SORTBY_DESC;
1550  if ((opt & INDOPTION_NULLS_FIRST) == 0)
1552  }
1553  else
1554  {
1555  if (opt & INDOPTION_NULLS_FIRST)
1557  }
1558  }
1559 
1560  index->indexParams = lappend(index->indexParams, iparam);
1561  }
1562 
1563  /* Handle included columns separately */
1564  for (keyno = idxrec->indnkeyatts; keyno < idxrec->indnatts; keyno++)
1565  {
1566  IndexElem *iparam;
1567  AttrNumber attnum = idxrec->indkey.values[keyno];
1569  keyno);
1570 
1571  iparam = makeNode(IndexElem);
1572 
1573  if (AttributeNumberIsValid(attnum))
1574  {
1575  /* Simple index column */
1576  char *attname;
1577 
1578  attname = get_attname(indrelid, attnum, false);
1579  keycoltype = get_atttype(indrelid, attnum);
1580 
1581  iparam->name = attname;
1582  iparam->expr = NULL;
1583  }
1584  else
1585  ereport(ERROR,
1586  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1587  errmsg("expressions are not supported in included columns")));
1588 
1589  /* Copy the original index column name */
1590  iparam->indexcolname = pstrdup(NameStr(attr->attname));
1591 
1592  index->indexIncludingParams = lappend(index->indexIncludingParams, iparam);
1593  }
1594  /* Copy reloptions if any */
1595  datum = SysCacheGetAttr(RELOID, ht_idxrel,
1596  Anum_pg_class_reloptions, &isnull);
1597  if (!isnull)
1598  index->options = untransformRelOptions(datum);
1599 
1600  /* If it's a partial index, decompile and append the predicate */
1601  datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1602  Anum_pg_index_indpred, &isnull);
1603  if (!isnull)
1604  {
1605  char *pred_str;
1606  Node *pred_tree;
1607  bool found_whole_row;
1608 
1609  /* Convert text string to node tree */
1610  pred_str = TextDatumGetCString(datum);
1611  pred_tree = (Node *) stringToNode(pred_str);
1612 
1613  /* Adjust Vars to match new table's column numbering */
1614  pred_tree = map_variable_attnos(pred_tree,
1615  1, 0,
1616  attmap, attmap_length,
1617  InvalidOid, &found_whole_row);
1618 
1619  /* As in transformTableLikeClause, reject whole-row variables */
1620  if (found_whole_row)
1621  ereport(ERROR,
1622  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1623  errmsg("cannot convert whole-row table reference"),
1624  errdetail("Index \"%s\" contains a whole-row table reference.",
1625  RelationGetRelationName(source_idx))));
1626 
1627  index->whereClause = pred_tree;
1628  }
1629 
1630  /* Clean up */
1631  ReleaseSysCache(ht_idxrel);
1632  ReleaseSysCache(ht_am);
1633 
1634  return index;
1635 }
#define list_make2(x1, x2)
Definition: pg_list.h:140
bool deferrable
Definition: parsenodes.h:2734
Value * makeString(char *str)
Definition: value.c:53
signed short int16
Definition: c.h:312
#define NIL
Definition: pg_list.h:69
static List * get_opclass(Oid opclass, Oid actual_datatype)
Definition: c.h:555
bool primary
Definition: parsenodes.h:2732
void * stringToNode(char *str)
Definition: read.c:39
int16 * rd_indoption
Definition: rel.h:158
SortByDir ordering
Definition: parsenodes.h:704
#define GETSTRUCT(TUP)
Definition: htup_details.h:668
Definition: syscache.h:36
List * options
Definition: parsenodes.h:2725
#define RelationGetDescr(relation)
Definition: rel.h:433
char * tableSpace
Definition: parsenodes.h:2721
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:93
#define DatumGetObjectId(X)
Definition: postgres.h:485
char * pstrdup(const char *in)
Definition: mcxt.c:1161
Node * whereClause
Definition: parsenodes.h:2726
Definition: nodes.h:517
int errcode(int sqlerrcode)
Definition: elog.c:575
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:605
struct IndexAmRoutine * rd_amroutine
Definition: rel.h:153
struct HeapTupleData * rd_indextuple
Definition: rel.h:133
List * indexIncludingParams
Definition: parsenodes.h:2723
Definition: type.h:89
Oid indexOid
Definition: parsenodes.h:2729
Node * expr
Definition: parsenodes.h:700
RangeVar * relation
Definition: parsenodes.h:2718
SortByNulls nulls_ordering
Definition: parsenodes.h:705
#define ObjectIdGetDatum(X)
Definition: postgres.h:492
#define ERROR
Definition: elog.h:43
NameData attname
Definition: pg_attribute.h:40
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3051
Oid values[FLEXIBLE_ARRAY_MEMBER]
Definition: c.h:563
bool transformed
Definition: parsenodes.h:2736
int errdetail(const char *fmt,...)
Definition: elog.c:873
char * indexcolname
Definition: parsenodes.h:701
#define RelationGetRelationName(relation)
Definition: rel.h:441
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:197
Oid get_index_constraint(Oid indexId)
Definition: pg_depend.c:689
Oid get_atttype(Oid relid, AttrNumber attnum)
Definition: lsyscache.c:863
#define lnext(lc)
Definition: pg_list.h:105
#define ereport(elevel, rest)
Definition: elog.h:122
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:128
char * idxname
Definition: parsenodes.h:2717
FormData_pg_index * Form_pg_index
Definition: pg_index.h:66
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1112
#define AttributeNumberIsValid(attributeNumber)
Definition: attnum.h:34
#define TextDatumGetCString(d)
Definition: builtins.h:96
bool if_not_exists
Definition: parsenodes.h:2738
uintptr_t Datum
Definition: postgres.h:367
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1368
bool unique
Definition: parsenodes.h:2731
List * untransformRelOptions(Datum options)
Definition: reloptions.c:934
char * accessMethod
Definition: parsenodes.h:2720
#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:565
FormData_pg_constraint * Form_pg_constraint
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:699
#define lfirst(lc)
Definition: pg_list.h:106
List * indexParams
Definition: parsenodes.h:2722
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
List * excludeOpNames
Definition: parsenodes.h:2727
bool initdeferred
Definition: parsenodes.h:2735
bool amcanorder
Definition: amapi.h:172
char * name
Definition: parsenodes.h:699
char * idxcomment
Definition: parsenodes.h:2728
FormData_pg_operator * Form_pg_operator
Definition: pg_operator.h:82
#define DatumGetPointer(X)
Definition: postgres.h:534
void deconstruct_array(ArrayType *array, Oid elmtype, int elmlen, bool elmbyval, char elmalign, Datum **elemsp, bool **nullsp, int *nelemsp)
Definition: arrayfuncs.c:3449
FormData_pg_class * Form_pg_class
Definition: pg_class.h:93
bool concurrent
Definition: parsenodes.h:2737
bool isconstraint
Definition: parsenodes.h:2733
FormData_pg_am * Form_pg_am
Definition: pg_am.h:46
int errmsg(const char *fmt,...)
Definition: elog.c:797
char * get_tablespace_name(Oid spc_oid)
Definition: tablespace.c:1428
int i
#define NameStr(name)
Definition: c.h:576
List * collation
Definition: parsenodes.h:702
char * get_attname(Oid relid, AttrNumber attnum, bool missing_ok)
Definition: lsyscache.c:775
#define elog
Definition: elog.h:219
static List * get_collation(Oid collation, Oid actual_datatype)
Definition: pg_list.h:45
int16 AttrNumber
Definition: attnum.h:21
#define RelationGetRelid(relation)
Definition: rel.h:407
Oid relationId
Definition: parsenodes.h:2719
#define DatumGetArrayTypeP(X)
Definition: array.h:246

◆ transformAlterTableStmt()

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

Definition at line 2911 of file parse_utilcmd.c.

References 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_attidentity(), get_attnum(), get_atttype(), get_namespace_name(), get_rel_name(), get_rel_namespace(), getOwnedSequence(), getOwnedSequences(), CreateStmtContext::hasoids, ColumnDef::identity, IndexStmt::indexOid, CreateStmtContext::inh_indexes, CreateStmtContext::inhRelations, InvalidAttrNumber, IsA, CreateStmtContext::isalter, CreateStmtContext::isforeign, CreateStmtContext::ispartitioned, CreateStmtContext::ixconstraints, lappend(), lfirst, lfirst_node, linitial_oid, 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(), AlterTableStmt::relkind, AlterSeqStmt::sequence, CreateStmtContext::stmtType, AlterTableCmd::subtype, transformCheckConstraints(), transformColumnDefinition(), transformExpr(), transformExtendedStatistics(), transformFKConstraints(), transformIndexConstraints(), transformIndexStmt(), transformPartitionCmd(), transformTableConstraint(), ColumnDef::typeName, and typenameTypeId().

Referenced by ATPostAlterTypeParse(), and ProcessUtilitySlow().

2913 {
2914  Relation rel;
2915  ParseState *pstate;
2916  CreateStmtContext cxt;
2917  List *result;
2918  List *save_alist;
2919  ListCell *lcmd,
2920  *l;
2921  List *newcmds = NIL;
2922  bool skipValidation = true;
2923  AlterTableCmd *newcmd;
2924  RangeTblEntry *rte;
2925 
2926  /*
2927  * We must not scribble on the passed-in AlterTableStmt, so copy it. (This
2928  * is overkill, but easy.)
2929  */
2930  stmt = copyObject(stmt);
2931 
2932  /* Caller is responsible for locking the relation */
2933  rel = relation_open(relid, NoLock);
2934 
2935  /* Set up pstate */
2936  pstate = make_parsestate(NULL);
2937  pstate->p_sourcetext = queryString;
2938  rte = addRangeTableEntryForRelation(pstate,
2939  rel,
2940  NULL,
2941  false,
2942  true);
2943  addRTEtoQuery(pstate, rte, false, true, true);
2944 
2945  /* Set up CreateStmtContext */
2946  cxt.pstate = pstate;
2947  if (stmt->relkind == OBJECT_FOREIGN_TABLE)
2948  {
2949  cxt.stmtType = "ALTER FOREIGN TABLE";
2950  cxt.isforeign = true;
2951  }
2952  else
2953  {
2954  cxt.stmtType = "ALTER TABLE";
2955  cxt.isforeign = false;
2956  }
2957  cxt.relation = stmt->relation;
2958  cxt.rel = rel;
2959  cxt.inhRelations = NIL;
2960  cxt.isalter = true;
2961  cxt.hasoids = false; /* need not be right */
2962  cxt.columns = NIL;
2963  cxt.ckconstraints = NIL;
2964  cxt.fkconstraints = NIL;
2965  cxt.ixconstraints = NIL;
2966  cxt.inh_indexes = NIL;
2967  cxt.extstats = NIL;
2968  cxt.blist = NIL;
2969  cxt.alist = NIL;
2970  cxt.pkey = NULL;
2971  cxt.ispartitioned = (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
2972  cxt.partbound = NULL;
2973  cxt.ofType = false;
2974 
2975  /*
2976  * The only subtypes that currently require parse transformation handling
2977  * are ADD COLUMN, ADD CONSTRAINT and SET DATA TYPE. These largely re-use
2978  * code from CREATE TABLE.
2979  */
2980  foreach(lcmd, stmt->cmds)
2981  {
2982  AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
2983 
2984  switch (cmd->subtype)
2985  {
2986  case AT_AddColumn:
2987  case AT_AddColumnToView:
2988  {
2989  ColumnDef *def = castNode(ColumnDef, cmd->def);
2990 
2991  transformColumnDefinition(&cxt, def);
2992 
2993  /*
2994  * If the column has a non-null default, we can't skip
2995  * validation of foreign keys.
2996  */
2997  if (def->raw_default != NULL)
2998  skipValidation = false;
2999 
3000  /*
3001  * All constraints are processed in other ways. Remove the
3002  * original list
3003  */
3004  def->constraints = NIL;
3005 
3006  newcmds = lappend(newcmds, cmd);
3007  break;
3008  }
3009 
3010  case AT_AddConstraint:
3011 
3012  /*
3013  * The original AddConstraint cmd node doesn't go to newcmds
3014  */
3015  if (IsA(cmd->def, Constraint))
3016  {
3017  transformTableConstraint(&cxt, (Constraint *) cmd->def);
3018  if (((Constraint *) cmd->def)->contype == CONSTR_FOREIGN)
3019  skipValidation = false;
3020  }
3021  else
3022  elog(ERROR, "unrecognized node type: %d",
3023  (int) nodeTag(cmd->def));
3024  break;
3025 
3027 
3028  /*
3029  * Already-transformed ADD CONSTRAINT, so just make it look
3030  * like the standard case.
3031  */
3032  cmd->subtype = AT_AddConstraint;
3033  newcmds = lappend(newcmds, cmd);
3034  break;
3035 
3036  case AT_AlterColumnType:
3037  {
3038  ColumnDef *def = (ColumnDef *) cmd->def;
3040 
3041  /*
3042  * For ALTER COLUMN TYPE, transform the USING clause if
3043  * one was specified.
3044  */
3045  if (def->raw_default)
3046  {
3047  def->cooked_default =
3048  transformExpr(pstate, def->raw_default,
3050  }
3051 
3052  /*
3053  * For identity column, create ALTER SEQUENCE command to
3054  * change the data type of the sequence.
3055  */
3056  attnum = get_attnum(relid, cmd->name);
3057 
3058  /*
3059  * if attribute not found, something will error about it
3060  * later
3061  */
3062  if (attnum != InvalidAttrNumber && get_attidentity(relid, attnum))
3063  {
3064  Oid seq_relid = getOwnedSequence(relid, attnum);
3065  Oid typeOid = typenameTypeId(pstate, def->typeName);
3066  AlterSeqStmt *altseqstmt = makeNode(AlterSeqStmt);
3067 
3068  altseqstmt->sequence = makeRangeVar(get_namespace_name(get_rel_namespace(seq_relid)),
3069  get_rel_name(seq_relid),
3070  -1);
3071  altseqstmt->options = list_make1(makeDefElem("as", (Node *) makeTypeNameFromOid(typeOid, -1), -1));
3072  altseqstmt->for_identity = true;
3073  cxt.blist = lappend(cxt.blist, altseqstmt);
3074  }
3075 
3076  newcmds = lappend(newcmds, cmd);
3077  break;
3078  }
3079 
3080  case AT_AddIdentity:
3081  {
3082  Constraint *def = castNode(Constraint, cmd->def);
3083  ColumnDef *newdef = makeNode(ColumnDef);
3085 
3086  newdef->colname = cmd->name;
3087  newdef->identity = def->generated_when;
3088  cmd->def = (Node *) newdef;
3089 
3090  attnum = get_attnum(relid, cmd->name);
3091 
3092  /*
3093  * if attribute not found, something will error about it
3094  * later
3095  */
3096  if (attnum != InvalidAttrNumber)
3097  generateSerialExtraStmts(&cxt, newdef,
3098  get_atttype(relid, attnum),
3099  def->options, true,
3100  NULL, NULL);
3101 
3102  newcmds = lappend(newcmds, cmd);
3103  break;
3104  }
3105 
3106  case AT_SetIdentity:
3107  {
3108  /*
3109  * Create an ALTER SEQUENCE statement for the internal
3110  * sequence of the identity column.
3111  */
3112  ListCell *lc;
3113  List *newseqopts = NIL;
3114  List *newdef = NIL;
3115  List *seqlist;
3117 
3118  /*
3119  * Split options into those handled by ALTER SEQUENCE and
3120  * those for ALTER TABLE proper.
3121  */
3122  foreach(lc, castNode(List, cmd->def))
3123  {
3124  DefElem *def = lfirst_node(DefElem, lc);
3125 
3126  if (strcmp(def->defname, "generated") == 0)
3127  newdef = lappend(newdef, def);
3128  else
3129  newseqopts = lappend(newseqopts, def);
3130  }
3131 
3132  attnum = get_attnum(relid, cmd->name);
3133 
3134  if (attnum)
3135  {
3136  seqlist = getOwnedSequences(relid, attnum);
3137  if (seqlist)
3138  {
3139  AlterSeqStmt *seqstmt;
3140  Oid seq_relid;
3141 
3142  seqstmt = makeNode(AlterSeqStmt);
3143  seq_relid = linitial_oid(seqlist);
3145  get_rel_name(seq_relid), -1);
3146  seqstmt->options = newseqopts;
3147  seqstmt->for_identity = true;
3148  seqstmt->missing_ok = false;
3149 
3150  cxt.alist = lappend(cxt.alist, seqstmt);
3151  }
3152  }
3153 
3154  /*
3155  * If column was not found or was not an identity column,
3156  * we just let the ALTER TABLE command error out later.
3157  */
3158 
3159  cmd->def = (Node *) newdef;
3160  newcmds = lappend(newcmds, cmd);
3161  break;
3162  }
3163 
3164  case AT_AttachPartition:
3165  case AT_DetachPartition:
3166  {
3167  PartitionCmd *partcmd = (PartitionCmd *) cmd->def;
3168 
3169  transformPartitionCmd(&cxt, partcmd);
3170  /* assign transformed value of the partition bound */
3171  partcmd->bound = cxt.partbound;
3172  }
3173 
3174  newcmds = lappend(newcmds, cmd);
3175  break;
3176 
3177  default:
3178  newcmds = lappend(newcmds, cmd);
3179  break;
3180  }
3181  }
3182 
3183  /*
3184  * transformIndexConstraints wants cxt.alist to contain only index
3185  * statements, so transfer anything we already have into save_alist
3186  * immediately.
3187  */
3188  save_alist = cxt.alist;
3189  cxt.alist = NIL;
3190 
3191  /* Postprocess constraints */
3193  transformFKConstraints(&cxt, skipValidation, true);
3194  transformCheckConstraints(&cxt, false);
3195 
3196  /*
3197  * Push any index-creation commands into the ALTER, so that they can be
3198  * scheduled nicely by tablecmds.c. Note that tablecmds.c assumes that
3199  * the IndexStmt attached to an AT_AddIndex or AT_AddIndexConstraint
3200  * subcommand has already been through transformIndexStmt.
3201  */
3202  foreach(l, cxt.alist)
3203  {
3204  IndexStmt *idxstmt = lfirst_node(IndexStmt, l);
3205 
3206  idxstmt = transformIndexStmt(relid, idxstmt, queryString);
3207  newcmd = makeNode(AlterTableCmd);
3209  newcmd->def = (Node *) idxstmt;
3210  newcmds = lappend(newcmds, newcmd);
3211  }
3212  cxt.alist = NIL;
3213 
3214  /* Append any CHECK or FK constraints to the commands list */
3215  foreach(l, cxt.ckconstraints)
3216  {
3217  newcmd = makeNode(AlterTableCmd);
3218  newcmd->subtype = AT_AddConstraint;
3219  newcmd->def = (Node *) lfirst(l);
3220  newcmds = lappend(newcmds, newcmd);
3221  }
3222  foreach(l, cxt.fkconstraints)
3223  {
3224  newcmd = makeNode(AlterTableCmd);
3225  newcmd->subtype = AT_AddConstraint;
3226  newcmd->def = (Node *) lfirst(l);
3227  newcmds = lappend(newcmds, newcmd);
3228  }
3229 
3230  /* Append extended statistic objects */
3232 
3233  /* Close rel */
3234  relation_close(rel, NoLock);
3235 
3236  /*
3237  * Output results.
3238  */
3239  stmt->cmds = newcmds;
3240 
3241  result = lappend(cxt.blist, stmt);
3242  result = list_concat(result, cxt.alist);
3243  result = list_concat(result, save_alist);
3244 
3245  return result;
3246 }
#define NIL
Definition: pg_list.h:69
Oid getOwnedSequence(Oid relid, AttrNumber attnum)
Definition: pg_depend.c:605
#define IsA(nodeptr, _type_)
Definition: nodes.h:568
char get_attidentity(Oid relid, AttrNumber attnum)
Definition: lsyscache.c:836
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:2104
#define castNode(_type_, nodeptr)
Definition: nodes.h:586
char identity
Definition: parsenodes.h:657
List * constraints
Definition: parsenodes.h:662
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:1754
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:146
Definition: nodes.h:517
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: heapam.c:1270
AlterTableType subtype
Definition: parsenodes.h:1806
List * list_concat(List *list1, List *list2)
Definition: list.c:321
Form_pg_class rd_rel
Definition: rel.h:84
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:605
DefElem * makeDefElem(char *name, Node *arg, int location)
Definition: makefuncs.c:546
List * options
Definition: parsenodes.h:2495
List * options
Definition: parsenodes.h:2116
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:44
#define list_make1(x1)
Definition: pg_list.h:139
ParseState * pstate
Definition: parse_utilcmd.c:76
Node * cooked_default
Definition: parsenodes.h:656
Oid indexOid
Definition: parsenodes.h:2729
RangeVar * relation
Definition: parse_utilcmd.c:78
IndexStmt * pkey
Definition: parse_utilcmd.c:94
#define ERROR
Definition: elog.h:43
#define lfirst_node(type, lc)
Definition: pg_list.h:109
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3051
#define NoLock
Definition: lockdefs.h:34
AttrNumber get_attnum(Oid relid, const char *attname)
Definition: lsyscache.c:806
const char * p_sourcetext
Definition: parse_node.h:173
Oid get_atttype(Oid relid, AttrNumber attnum)
Definition: lsyscache.c:863
ObjectType relkind
Definition: parsenodes.h:1720
void addRTEtoQuery(ParseState *pstate, RangeTblEntry *rte, bool addToJoinList, bool addToRelNameSpace, bool addToVarNameSpace)
PartitionBoundSpec * partbound
Definition: parse_utilcmd.c:96
Node * raw_default
Definition: parsenodes.h:655
List * lappend(List *list, void *datum)
Definition: list.c:128
List * getOwnedSequences(Oid relid, AttrNumber attnum)
Definition: pg_depend.c:548
TypeName * makeTypeNameFromOid(Oid typeOid, int32 typmod)
Definition: makefuncs.c:471
RangeVar * sequence
Definition: parsenodes.h:2494
int16 attnum
Definition: pg_attribute.h:79
#define makeNode(_type_)
Definition: nodes.h:565
#define lfirst(lc)
Definition: pg_list.h:106
static void transformColumnDefinition(CreateStmtContext *cxt, ColumnDef *column)
PartitionBoundSpec * bound
Definition: parsenodes.h:859
#define linitial_oid(l)
Definition: pg_list.h:113
RangeTblEntry * addRangeTableEntryForRelation(ParseState *pstate, Relation rel, Alias *alias, bool inh, bool inFromCl)
TypeName * typeName
Definition: parsenodes.h:648
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:522
const char * stmtType
Definition: parse_utilcmd.c:77
static void transformExtendedStatistics(CreateStmtContext *cxt)
RangeVar * relation
Definition: parsenodes.h:1718
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1124
bool for_identity
Definition: parsenodes.h:2496
char * defname
Definition: parsenodes.h:730
char * colname
Definition: parsenodes.h:647
#define elog
Definition: elog.h:219
#define copyObject(obj)
Definition: nodes.h:630
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:45
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:421
static void transformCheckConstraints(CreateStmtContext *cxt, bool skipValidation)
Oid typenameTypeId(ParseState *pstate, const TypeName *typeName)
Definition: parse_type.c:274

◆ transformCreateSchemaStmt()

List* transformCreateSchemaStmt ( CreateSchemaStmt stmt)

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

3428 {
3430  List *result;
3431  ListCell *elements;
3432 
3433  cxt.stmtType = "CREATE SCHEMA";
3434  cxt.schemaname = stmt->schemaname;
3435  cxt.authrole = (RoleSpec *) stmt->authrole;
3436  cxt.sequences = NIL;
3437  cxt.tables = NIL;
3438  cxt.views = NIL;
3439  cxt.indexes = NIL;
3440  cxt.triggers = NIL;
3441  cxt.grants = NIL;
3442 
3443  /*
3444  * Run through each schema element in the schema element list. Separate
3445  * statements by type, and do preliminary analysis.
3446  */
3447  foreach(elements, stmt->schemaElts)
3448  {
3449  Node *element = lfirst(elements);
3450 
3451  switch (nodeTag(element))
3452  {
3453  case T_CreateSeqStmt:
3454  {
3455  CreateSeqStmt *elp = (CreateSeqStmt *) element;
3456 
3458  cxt.sequences = lappend(cxt.sequences, element);
3459  }
3460  break;
3461 
3462  case T_CreateStmt:
3463  {
3464  CreateStmt *elp = (CreateStmt *) element;
3465 
3467 
3468  /*
3469  * XXX todo: deal with constraints
3470  */
3471  cxt.tables = lappend(cxt.tables, element);
3472  }
3473  break;
3474 
3475  case T_ViewStmt:
3476  {
3477  ViewStmt *elp = (ViewStmt *) element;
3478 
3479  setSchemaName(cxt.schemaname, &elp->view->schemaname);
3480 
3481  /*
3482  * XXX todo: deal with references between views
3483  */
3484  cxt.views = lappend(cxt.views, element);
3485  }
3486  break;
3487 
3488  case T_IndexStmt:
3489  {
3490  IndexStmt *elp = (IndexStmt *) element;
3491 
3493  cxt.indexes = lappend(cxt.indexes, element);
3494  }
3495  break;
3496 
3497  case T_CreateTrigStmt:
3498  {
3499  CreateTrigStmt *elp = (CreateTrigStmt *) element;
3500 
3502  cxt.triggers = lappend(cxt.triggers, element);
3503  }
3504  break;
3505 
3506  case T_GrantStmt:
3507  cxt.grants = lappend(cxt.grants, element);
3508  break;
3509 
3510  default:
3511  elog(ERROR, "unrecognized node type: %d",
3512  (int) nodeTag(element));
3513  }
3514  }
3515 
3516  result = NIL;
3517  result = list_concat(result, cxt.sequences);
3518  result = list_concat(result, cxt.tables);
3519  result = list_concat(result, cxt.views);
3520  result = list_concat(result, cxt.indexes);
3521  result = list_concat(result, cxt.triggers);
3522  result = list_concat(result, cxt.grants);
3523 
3524  return result;
3525 }
RangeVar * relation
Definition: parsenodes.h:2014
#define NIL
Definition: pg_list.h:69
Definition: nodes.h:517
List * list_concat(List *list1, List *list2)
Definition: list.c:321
RangeVar * view
Definition: parsenodes.h:3043
char * schemaname
Definition: primnodes.h:68
RangeVar * relation
Definition: parsenodes.h:2718
RoleSpec * authrole
Definition: parsenodes.h:1700
#define ERROR
Definition: elog.h:43
List * lappend(List *list, void *datum)
Definition: list.c:128
static chr element(struct vars *v, const chr *startp, const chr *endp)
Definition: regc_locale.c:380
RangeVar * sequence
Definition: parsenodes.h:2484
#define lfirst(lc)
Definition: pg_list.h:106
static void setSchemaName(char *context_schema, char **stmt_schema_name)
#define nodeTag(nodeptr)
Definition: nodes.h:522
RangeVar * relation
Definition: parsenodes.h:2369
#define elog
Definition: elog.h:219
Definition: pg_list.h:45

◆ transformCreateStmt()

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

Definition at line 161 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(), CreateStmtContext::hasoids, CreateStmt::if_not_exists, CreateStmtContext::inh_indexes, CreateStmtContext::inhRelations, CreateStmt::inhRelations, interpretOidsOption(), IsA, CreateStmtContext::isalter, CreateStmtContext::isforeign, CreateStmtContext::ispartitioned, CreateStmtContext::ixconstraints, lappend(), lcons(), lfirst, list_concat(), RangeVar::location, make_parsestate(), makeDefElem(), makeInteger(), NIL, nodeTag, NoLock, NOTICE, CreateStmtContext::ofType, CreateStmt::ofTypename, OidIsValid, CreateStmt::options, 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().

162 {
163  ParseState *pstate;
164  CreateStmtContext cxt;
165  List *result;
166  List *save_alist;
167  ListCell *elements;
168  Oid namespaceid;
169  Oid existing_relid;
170  ParseCallbackState pcbstate;
171  bool like_found = false;
172  bool is_foreign_table = IsA(stmt, CreateForeignTableStmt);
173 
174  /*
175  * We must not scribble on the passed-in CreateStmt, so copy it. (This is
176  * overkill, but easy.)
177  */
178  stmt = copyObject(stmt);
179 
180  /* Set up pstate */
181  pstate = make_parsestate(NULL);
182  pstate->p_sourcetext = queryString;
183 
184  /*
185  * Look up the creation namespace. This also checks permissions on the
186  * target namespace, locks it against concurrent drops, checks for a
187  * preexisting relation in that namespace with the same name, and updates
188  * stmt->relation->relpersistence if the selected namespace is temporary.
189  */
190  setup_parser_errposition_callback(&pcbstate, pstate,
191  stmt->relation->location);
192  namespaceid =
194  &existing_relid);
196 
197  /*
198  * If the relation already exists and the user specified "IF NOT EXISTS",
199  * bail out with a NOTICE.
200  */
201  if (stmt->if_not_exists && OidIsValid(existing_relid))
202  {
203  ereport(NOTICE,
204  (errcode(ERRCODE_DUPLICATE_TABLE),
205  errmsg("relation \"%s\" already exists, skipping",
206  stmt->relation->relname)));
207  return NIL;
208  }
209 
210  /*
211  * If the target relation name isn't schema-qualified, make it so. This
212  * prevents some corner cases in which added-on rewritten commands might
213  * think they should apply to other relations that have the same name and
214  * are earlier in the search path. But a local temp table is effectively
215  * specified to be in pg_temp, so no need for anything extra in that case.
216  */
217  if (stmt->relation->schemaname == NULL
218  && stmt->relation->relpersistence != RELPERSISTENCE_TEMP)
219  stmt->relation->schemaname = get_namespace_name(namespaceid);
220 
221  /* Set up CreateStmtContext */
222  cxt.pstate = pstate;
223  if (IsA(stmt, CreateForeignTableStmt))
224  {
225  cxt.stmtType = "CREATE FOREIGN TABLE";
226  cxt.isforeign = true;
227  }
228  else
229  {
230  cxt.stmtType = "CREATE TABLE";
231  cxt.isforeign = false;
232  }
233  cxt.relation = stmt->relation;
234  cxt.rel = NULL;
235  cxt.inhRelations = stmt->inhRelations;
236  cxt.isalter = false;
237  cxt.columns = NIL;
238  cxt.ckconstraints = NIL;
239  cxt.fkconstraints = NIL;
240  cxt.ixconstraints = NIL;
241  cxt.inh_indexes = NIL;
242  cxt.extstats = NIL;
243  cxt.blist = NIL;
244  cxt.alist = NIL;
245  cxt.pkey = NULL;
246  cxt.ispartitioned = stmt->partspec != NULL;
247  cxt.partbound = stmt->partbound;
248  cxt.ofType = (stmt->ofTypename != NULL);
249 
250  /*
251  * Notice that we allow OIDs here only for plain tables, even though
252  * foreign tables also support them. This is necessary because the
253  * default_with_oids GUC must apply only to plain tables and not any other
254  * relkind; doing otherwise would break existing pg_dump files. We could
255  * allow explicit "WITH OIDS" while not allowing default_with_oids to
256  * affect other relkinds, but it would complicate interpretOidsOption(),
257  * and right now there's no WITH OIDS option in CREATE FOREIGN TABLE
258  * anyway.
259  */
260  cxt.hasoids = interpretOidsOption(stmt->options, !cxt.isforeign);
261 
262  Assert(!stmt->ofTypename || !stmt->inhRelations); /* grammar enforces */
263 
264  if (stmt->ofTypename)
265  transformOfType(&cxt, stmt->ofTypename);
266 
267  if (stmt->partspec)
268  {
269  if (stmt->inhRelations && !stmt->partbound)
270  ereport(ERROR,
271  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
272  errmsg("cannot create partitioned table as inheritance child")));
273  }
274 
275  /*
276  * Run through each primary element in the table creation clause. Separate
277  * column defs from constraints, and do preliminary analysis.
278  */
279  foreach(elements, stmt->tableElts)
280  {
281  Node *element = lfirst(elements);
282 
283  switch (nodeTag(element))
284  {
285  case T_ColumnDef:
286  transformColumnDefinition(&cxt, (ColumnDef *) element);
287  break;
288 
289  case T_Constraint:
290  transformTableConstraint(&cxt, (Constraint *) element);
291  break;
292 
293  case T_TableLikeClause:
294  like_found = true;
295  transformTableLikeClause(&cxt, (TableLikeClause *) element);
296  break;
297 
298  default:
299  elog(ERROR, "unrecognized node type: %d",
300  (int) nodeTag(element));
301  break;
302  }
303  }
304 
305  /*
306  * If we had any LIKE tables, they may require creation of an OID column
307  * even though the command's own WITH clause didn't ask for one (or,
308  * perhaps, even specifically rejected having one). Insert a WITH option
309  * to ensure that happens. We prepend to the list because the first oid
310  * option will be honored, and we want to override anything already there.
311  * (But note that DefineRelation will override this again to add an OID
312  * column if one appears in an inheritance parent table.)
313  */
314  if (like_found && cxt.hasoids)
315  stmt->options = lcons(makeDefElem("oids",
316  (Node *) makeInteger(true), -1),
317  stmt->options);
318 
319  /*
320  * transformIndexConstraints wants cxt.alist to contain only index
321  * statements, so transfer anything we already have into save_alist.
322  */
323  save_alist = cxt.alist;
324  cxt.alist = NIL;
325 
326  Assert(stmt->constraints == NIL);
327 
328  /*
329  * Postprocess constraints that give rise to index definitions.
330  */
332 
333  /*
334  * Postprocess foreign-key constraints.
335  */
336  transformFKConstraints(&cxt, true, false);
337 
338  /*
339  * Postprocess check constraints.
340  */
341  transformCheckConstraints(&cxt, !is_foreign_table ? true : false);
342 
343  /*
344  * Postprocess extended statistics.
345  */
347 
348  /*
349  * Output results.
350  */
351  stmt->tableElts = cxt.columns;
352  stmt->constraints = cxt.ckconstraints;
353 
354  result = lappend(cxt.blist, stmt);
355  result = list_concat(result, cxt.alist);
356  result = list_concat(result, save_alist);
357 
358  return result;
359 }
RangeVar * relation
Definition: parsenodes.h:2014
#define NIL
Definition: pg_list.h:69
List * inhRelations
Definition: parsenodes.h:2016
#define IsA(nodeptr, _type_)
Definition: nodes.h:568
Definition: nodes.h:517
int errcode(int sqlerrcode)
Definition: elog.c:575
List * list_concat(List *list1, List *list2)
Definition: list.c:321
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:605
DefElem * makeDefElem(char *name, Node *arg, int location)
Definition: makefuncs.c:546
char * schemaname
Definition: primnodes.h:68
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:44
List * constraints
Definition: parsenodes.h:2021
bool if_not_exists
Definition: parsenodes.h:2025
int location
Definition: primnodes.h:74
ParseState * pstate
Definition: parse_utilcmd.c:76
PartitionBoundSpec * partbound
Definition: parsenodes.h:2018
char * relname
Definition: primnodes.h:69
RangeVar * relation
Definition: parse_utilcmd.c:78
IndexStmt * pkey
Definition: parse_utilcmd.c:94
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:3051
#define NoLock
Definition: lockdefs.h:34
List * options
Definition: parsenodes.h:2022
const char * p_sourcetext
Definition: parse_node.h:173
#define ereport(elevel, rest)
Definition: elog.h:122
void setup_parser_errposition_callback(ParseCallbackState *pcbstate, ParseState *pstate, int location)
Definition: parse_node.c:145
PartitionBoundSpec * partbound
Definition: parse_utilcmd.c:96
List * lappend(List *list, void *datum)
Definition: list.c:128
static chr element(struct vars *v, const chr *startp, const chr *endp)
Definition: regc_locale.c:380
Value * makeInteger(int i)
Definition: value.c:23
Oid RangeVarGetAndCheckCreationNamespace(RangeVar *relation, LOCKMODE lockmode, Oid *existing_relation_id)
Definition: namespace.c:527
#define NOTICE
Definition: elog.h:37
List * tableElts
Definition: parsenodes.h:2015
List * lcons(void *datum, List *list)
Definition: list.c:259
static void transformOfType(CreateStmtContext *cxt, TypeName *ofTypename)
#define Assert(condition)
Definition: c.h:699
#define lfirst(lc)
Definition: pg_list.h:106
static void transformColumnDefinition(CreateStmtContext *cxt, ColumnDef *column)
static void transformFKConstraints(CreateStmtContext *cxt, bool skipValidation, bool isAddConstraint)
#define nodeTag(nodeptr)
Definition: nodes.h:522
const char * stmtType
Definition: parse_utilcmd.c:77
static void transformExtendedStatistics(CreateStmtContext *cxt)
char relpersistence
Definition: primnodes.h:72
bool interpretOidsOption(List *defList, bool allowOids)
Definition: parse_clause.c:262
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define elog
Definition: elog.h:219
#define copyObject(obj)
Definition: nodes.h:630
static void transformTableConstraint(CreateStmtContext *cxt, Constraint *constraint)
static void transformIndexConstraints(CreateStmtContext *cxt)
PartitionSpec * partspec
Definition: parsenodes.h:2019
Definition: pg_list.h:45
static void transformTableLikeClause(CreateStmtContext *cxt, TableLikeClause *table_like_clause)
TypeName * ofTypename
Definition: parsenodes.h:2020
static void transformCheckConstraints(CreateStmtContext *cxt, bool skipValidation)

◆ transformIndexStmt()

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

Definition at line 2501 of file parse_utilcmd.c.

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

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

2502 {
2503  ParseState *pstate;
2504  RangeTblEntry *rte;
2505  ListCell *l;
2506  Relation rel;
2507 
2508  /* Nothing to do if statement already transformed. */
2509  if (stmt->transformed)
2510  return stmt;
2511 
2512  /*
2513  * We must not scribble on the passed-in IndexStmt, so copy it. (This is
2514  * overkill, but easy.)
2515  */
2516  stmt = copyObject(stmt);
2517 
2518  /* Set up pstate */
2519  pstate = make_parsestate(NULL);
2520  pstate->p_sourcetext = queryString;
2521 
2522  /*
2523  * Put the parent table into the rtable so that the expressions can refer
2524  * to its fields without qualification. Caller is responsible for locking
2525  * relation, but we still need to open it.
2526  */
2527  rel = relation_open(relid, NoLock);
2528  rte = addRangeTableEntryForRelation(pstate, rel, NULL, false, true);
2529 
2530  /* no to join list, yes to namespaces */
2531  addRTEtoQuery(pstate, rte, false, true, true);
2532 
2533  /* take care of the where clause */
2534  if (stmt->whereClause)
2535  {
2536  stmt->whereClause = transformWhereClause(pstate,
2537  stmt->whereClause,
2539  "WHERE");
2540  /* we have to fix its collations too */
2541  assign_expr_collations(pstate, stmt->whereClause);
2542  }
2543 
2544  /* take care of any index expressions */
2545  foreach(l, stmt->indexParams)
2546  {
2547  IndexElem *ielem = (IndexElem *) lfirst(l);
2548 
2549  if (ielem->expr)
2550  {
2551  /* Extract preliminary index col name before transforming expr */
2552  if (ielem->indexcolname == NULL)
2553  ielem->indexcolname = FigureIndexColname(ielem->expr);
2554 
2555  /* Now do parse transformation of the expression */
2556  ielem->expr = transformExpr(pstate, ielem->expr,
2558 
2559  /* We have to fix its collations too */
2560  assign_expr_collations(pstate, ielem->expr);
2561 
2562  /*
2563  * transformExpr() should have already rejected subqueries,
2564  * aggregates, window functions, and SRFs, based on the EXPR_KIND_
2565  * for an index expression.
2566  *
2567  * DefineIndex() will make more checks.
2568  */
2569  }
2570  }
2571 
2572  /*
2573  * Check that only the base rel is mentioned. (This should be dead code
2574  * now that add_missing_from is history.)
2575  */
2576  if (list_length(pstate->p_rtable) != 1)
2577  ereport(ERROR,
2578  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2579  errmsg("index expressions and predicates can refer only to the table being indexed")));
2580 
2581  free_parsestate(pstate);
2582 
2583  /* Close relation */
2584  heap_close(rel, NoLock);
2585 
2586  /* Mark statement as successfully transformed */
2587  stmt->transformed = true;
2588 
2589  return stmt;
2590 }
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:146
Node * whereClause
Definition: parsenodes.h:2726
int errcode(int sqlerrcode)
Definition: elog.c:575
char * FigureIndexColname(Node *node)
#define heap_close(r, l)
Definition: heapam.h:97
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
#define NoLock
Definition: lockdefs.h:34
bool transformed
Definition: parsenodes.h:2736
char * indexcolname
Definition: parsenodes.h:701
const char * p_sourcetext
Definition: parse_node.h:173
#define ereport(elevel, rest)
Definition: elog.h:122
void addRTEtoQuery(ParseState *pstate, RangeTblEntry *rte, bool addToJoinList, bool addToRelNameSpace, bool addToVarNameSpace)
#define lfirst(lc)
Definition: pg_list.h:106
Node * transformWhereClause(ParseState *pstate, Node *clause, ParseExprKind exprKind, const char *constructName)
List * indexParams
Definition: parsenodes.h:2722
static int list_length(const List *l)
Definition: pg_list.h:89
RangeTblEntry * addRangeTableEntryForRelation(ParseState *pstate, Relation rel, Alias *alias, bool inh, bool inFromCl)
int errmsg(const char *fmt,...)
Definition: elog.c:797
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1124
#define copyObject(obj)
Definition: nodes.h:630
void free_parsestate(ParseState *pstate)
Definition: parse_node.c:77
List * p_rtable
Definition: parse_node.h:174

◆ transformPartitionBound()

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

Definition at line 3597 of file parse_utilcmd.c.

References Assert, castNode, Const::constisnull, copyObject, deparse_context_for(), deparse_expression(), elog, equal(), ereport, errcode(), errmsg(), ERROR, exprLocation(), forboth, get_attname(), get_partition_col_typid(), get_partition_col_typmod(), get_partition_exprs(), get_partition_natts(), get_partition_strategy(), i, PartitionBoundSpec::is_default, lappend(), lfirst, linitial, list_length(), list_nth(), PartitionBoundSpec::listdatums, PartitionBoundSpec::lowerdatums, NIL, parser_errposition(), PartitionKeyData::partattrs, PARTITION_STRATEGY_HASH, PARTITION_STRATEGY_LIST, PARTITION_STRATEGY_RANGE, RelationGetPartitionKey, RelationGetRelationName, RelationGetRelid, PartitionBoundSpec::strategy, transformPartitionBoundValue(), PartitionBoundSpec::upperdatums, validateInfiniteBounds(), value, and PartitionRangeDatum::value.

Referenced by DefineRelation(), and transformPartitionCmd().

3599 {
3600  PartitionBoundSpec *result_spec;
3601  PartitionKey key = RelationGetPartitionKey(parent);
3602  char strategy = get_partition_strategy(key);
3603  int partnatts = get_partition_natts(key);
3604  List *partexprs = get_partition_exprs(key);
3605 
3606  /* Avoid scribbling on input */
3607  result_spec = copyObject(spec);
3608 
3609  if (spec->is_default)
3610  {
3611  if (strategy == PARTITION_STRATEGY_HASH)
3612  ereport(ERROR,
3613  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3614  errmsg("a hash-partitioned table may not have a default partition")));
3615 
3616  /*
3617  * In case of the default partition, parser had no way to identify the
3618  * partition strategy. Assign the parent's strategy to the default
3619  * partition bound spec.
3620  */
3621  result_spec->strategy = strategy;
3622 
3623  return result_spec;
3624  }
3625 
3626  if (strategy == PARTITION_STRATEGY_HASH)
3627  {
3628  if (spec->strategy != PARTITION_STRATEGY_HASH)
3629  ereport(ERROR,
3630  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3631  errmsg("invalid bound specification for a hash partition"),
3632  parser_errposition(pstate, exprLocation((Node *) spec))));
3633 
3634  if (spec->modulus <= 0)
3635  ereport(ERROR,
3636  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3637  errmsg("modulus for hash partition must be a positive integer")));
3638 
3639  Assert(spec->remainder >= 0);
3640 
3641  if (spec->remainder >= spec->modulus)
3642  ereport(ERROR,
3643  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3644  errmsg("remainder for hash partition must be less than modulus")));
3645  }
3646  else if (strategy == PARTITION_STRATEGY_LIST)
3647  {
3648  ListCell *cell;
3649  char *colname;
3650  Oid coltype;
3651  int32 coltypmod;
3652 
3653  if (spec->strategy != PARTITION_STRATEGY_LIST)
3654  ereport(ERROR,
3655  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3656  errmsg("invalid bound specification for a list partition"),
3657  parser_errposition(pstate, exprLocation((Node *) spec))));
3658 
3659  /* Get the only column's name in case we need to output an error */
3660  if (key->partattrs[0] != 0)
3661  colname = get_attname(RelationGetRelid(parent),
3662  key->partattrs[0], false);
3663  else
3664  colname = deparse_expression((Node *) linitial(partexprs),
3666  RelationGetRelid(parent)),
3667  false, false);
3668  /* Need its type data too */
3669  coltype = get_partition_col_typid(key, 0);
3670  coltypmod = get_partition_col_typmod(key, 0);
3671 
3672  result_spec->listdatums = NIL;
3673  foreach(cell, spec->listdatums)
3674  {
3675  A_Const *con = castNode(A_Const, lfirst(cell));
3676  Const *value;
3677  ListCell *cell2;
3678  bool duplicate;
3679 
3680  value = transformPartitionBoundValue(pstate, con,
3681  colname, coltype, coltypmod);
3682 
3683  /* Don't add to the result if the value is a duplicate */
3684  duplicate = false;
3685  foreach(cell2, result_spec->listdatums)
3686  {
3687  Const *value2 = castNode(Const, lfirst(cell2));
3688 
3689  if (equal(value, value2))
3690  {
3691  duplicate = true;
3692  break;
3693  }
3694  }
3695  if (duplicate)
3696  continue;
3697 
3698  result_spec->listdatums = lappend(result_spec->listdatums,
3699  value);
3700  }
3701  }
3702  else if (strategy == PARTITION_STRATEGY_RANGE)
3703  {
3704  ListCell *cell1,
3705  *cell2;
3706  int i,
3707  j;
3708 
3709  if (spec->strategy != PARTITION_STRATEGY_RANGE)
3710  ereport(ERROR,
3711  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3712  errmsg("invalid bound specification for a range partition"),
3713  parser_errposition(pstate, exprLocation((Node *) spec))));
3714 
3715  if (list_length(spec->lowerdatums) != partnatts)
3716  ereport(ERROR,
3717  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3718  errmsg("FROM must specify exactly one value per partitioning column")));
3719  if (list_length(spec->upperdatums) != partnatts)
3720  ereport(ERROR,
3721  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3722  errmsg("TO must specify exactly one value per partitioning column")));
3723 
3724  /*
3725  * Once we see MINVALUE or MAXVALUE for one column, the remaining
3726  * columns must be the same.
3727  */
3728  validateInfiniteBounds(pstate, spec->lowerdatums);
3729  validateInfiniteBounds(pstate, spec->upperdatums);
3730 
3731  /* Transform all the constants */
3732  i = j = 0;
3733  result_spec->lowerdatums = result_spec->upperdatums = NIL;
3734  forboth(cell1, spec->lowerdatums, cell2, spec->upperdatums)
3735  {
3736  PartitionRangeDatum *ldatum = (PartitionRangeDatum *) lfirst(cell1);
3737  PartitionRangeDatum *rdatum = (PartitionRangeDatum *) lfirst(cell2);
3738  char *colname;
3739  Oid coltype;
3740  int32 coltypmod;
3741  A_Const *con;
3742  Const *value;
3743 
3744  /* Get the column's name in case we need to output an error */
3745  if (key->partattrs[i] != 0)
3746  colname = get_attname(RelationGetRelid(parent),
3747  key->partattrs[i], false);
3748  else
3749  {
3750  colname = deparse_expression((Node *) list_nth(partexprs, j),
3752  RelationGetRelid(parent)),
3753  false, false);
3754  ++j;
3755  }
3756  /* Need its type data too */
3757  coltype = get_partition_col_typid(key, i);
3758  coltypmod = get_partition_col_typmod(key, i);
3759 
3760  if (ldatum->value)
3761  {
3762  con = castNode(A_Const, ldatum->value);
3763  value = transformPartitionBoundValue(pstate, con,
3764  colname,
3765  coltype, coltypmod);
3766  if (value->constisnull)
3767  ereport(ERROR,
3768  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3769  errmsg("cannot specify NULL in range bound")));
3770  ldatum = copyObject(ldatum); /* don't scribble on input */
3771  ldatum->value = (Node *) value;
3772  }
3773 
3774  if (rdatum->value)
3775  {
3776  con = castNode(A_Const, rdatum->value);
3777  value = transformPartitionBoundValue(pstate, con,
3778  colname,
3779  coltype, coltypmod);
3780  if (value->constisnull)
3781  ereport(ERROR,
3782  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3783  errmsg("cannot specify NULL in range bound")));
3784  rdatum = copyObject(rdatum); /* don't scribble on input */
3785  rdatum->value = (Node *) value;
3786  }
3787 
3788  result_spec->lowerdatums = lappend(result_spec->lowerdatums,
3789  ldatum);
3790  result_spec->upperdatums = lappend(result_spec->upperdatums,
3791  rdatum);
3792 
3793  ++i;
3794  }
3795  }
3796  else
3797  elog(ERROR, "unexpected partition strategy: %d", (int) strategy);
3798 
3799  return result_spec;
3800 }
#define NIL
Definition: pg_list.h:69
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:180
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1186
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:2986
#define castNode(_type_, nodeptr)
Definition: nodes.h:586
static int32 get_partition_col_typmod(PartitionKey key, int col)
Definition: partcache.h:91
static Oid get_partition_col_typid(PartitionKey key, int col)
Definition: partcache.h:85
Definition: nodes.h:517
static int get_partition_natts(PartitionKey key)
Definition: partcache.h:64
int errcode(int sqlerrcode)
Definition: elog.c:575
static Const * transformPartitionBoundValue(ParseState *pstate, A_Const *con, const char *colName, Oid colType, int32 colTypmod)
unsigned int Oid
Definition: postgres_ext.h:31
signed int int32
Definition: c.h:313
static List * get_partition_exprs(PartitionKey key)
Definition: partcache.h:70
#define linitial(l)
Definition: pg_list.h:111
#define ERROR
Definition: elog.h:43
static void validateInfiniteBounds(ParseState *pstate, List *blist)
void * list_nth(const List *list, int n)
Definition: list.c:410
List * deparse_context_for(const char *aliasname, Oid relid)
Definition: ruleutils.c:3130
#define RelationGetRelationName(relation)
Definition: rel.h:441
#define ereport(elevel, rest)
Definition: elog.h:122
List * lappend(List *list, void *datum)
Definition: list.c:128
AttrNumber * partattrs
Definition: partcache.h:28
static struct @131 value
#define PARTITION_STRATEGY_HASH
Definition: parsenodes.h:798
#define Assert(condition)
Definition: c.h:699
#define lfirst(lc)
Definition: pg_list.h:106
char * deparse_expression(Node *expr, List *dpcontext, bool forceprefix, bool showimplicit)
Definition: ruleutils.c:3071
static int list_length(const List *l)
Definition: pg_list.h:89
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:589
#define PARTITION_STRATEGY_RANGE
Definition: parsenodes.h:800
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
char * get_attname(Oid relid, AttrNumber attnum, bool missing_ok)
Definition: lsyscache.c:775
#define elog
Definition: elog.h:219
#define copyObject(obj)
Definition: nodes.h:630
static int get_partition_strategy(PartitionKey key)
Definition: partcache.h:58
Definition: pg_list.h:45
#define RelationGetRelid(relation)
Definition: rel.h:407
bool constisnull
Definition: primnodes.h:198

◆ transformRuleStmt()

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

Definition at line 2606 of file parse_utilcmd.c.

References AccessExclusiveLock, 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(), heap_close, heap_openrv(), 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, transformStmt(), transformWhereClause(), and RuleStmt::whereClause.

Referenced by DefineRule().

2608 {
2609  Relation rel;
2610  ParseState *pstate;
2611  RangeTblEntry *oldrte;
2612  RangeTblEntry *newrte;
2613 
2614  /*
2615  * To avoid deadlock, make sure the first thing we do is grab
2616  * AccessExclusiveLock on the target relation. This will be needed by
2617  * DefineQueryRewrite(), and we don't want to grab a lesser lock
2618  * beforehand.
2619  */
2621 
2622  if (rel->rd_rel->relkind == RELKIND_MATVIEW)
2623  ereport(ERROR,
2624  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2625  errmsg("rules on materialized views are not supported")));
2626 
2627  /* Set up pstate */
2628  pstate = make_parsestate(NULL);
2629  pstate->p_sourcetext = queryString;
2630 
2631  /*
2632  * NOTE: 'OLD' must always have a varno equal to 1 and 'NEW' equal to 2.
2633  * Set up their RTEs in the main pstate for use in parsing the rule
2634  * qualification.
2635  */
2636  oldrte = addRangeTableEntryForRelation(pstate, rel,
2637  makeAlias("old", NIL),
2638  false, false);
2639  newrte = addRangeTableEntryForRelation(pstate, rel,
2640  makeAlias("new", NIL),
2641  false, false);
2642  /* Must override addRangeTableEntry's default access-check flags */
2643  oldrte->requiredPerms = 0;
2644  newrte->requiredPerms = 0;
2645 
2646  /*
2647  * They must be in the namespace too for lookup purposes, but only add the
2648  * one(s) that are relevant for the current kind of rule. In an UPDATE
2649  * rule, quals must refer to OLD.field or NEW.field to be unambiguous, but
2650  * there's no need to be so picky for INSERT & DELETE. We do not add them
2651  * to the joinlist.
2652  */
2653  switch (stmt->event)
2654  {
2655  case CMD_SELECT:
2656  addRTEtoQuery(pstate, oldrte, false, true, true);
2657  break;
2658  case CMD_UPDATE:
2659  addRTEtoQuery(pstate, oldrte, false, true, true);
2660  addRTEtoQuery(pstate, newrte, false, true, true);
2661  break;
2662  case CMD_INSERT:
2663  addRTEtoQuery(pstate, newrte, false, true, true);
2664  break;
2665  case CMD_DELETE:
2666  addRTEtoQuery(pstate, oldrte, false, true, true);
2667  break;
2668  default:
2669  elog(ERROR, "unrecognized event type: %d",
2670  (int) stmt->event);
2671  break;
2672  }
2673 
2674  /* take care of the where clause */
2675  *whereClause = transformWhereClause(pstate,
2676  (Node *) copyObject(stmt->whereClause),
2678  "WHERE");
2679  /* we have to fix its collations too */
2680  assign_expr_collations(pstate, *whereClause);
2681 
2682  /* this is probably dead code without add_missing_from: */
2683  if (list_length(pstate->p_rtable) != 2) /* naughty, naughty... */
2684  ereport(ERROR,
2685  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2686  errmsg("rule WHERE condition cannot contain references to other relations")));
2687 
2688  /*
2689  * 'instead nothing' rules with a qualification need a query rangetable so
2690  * the rewrite handler can add the negated rule qualification to the
2691  * original query. We create a query with the new command type CMD_NOTHING
2692  * here that is treated specially by the rewrite system.
2693  */
2694  if (stmt->actions == NIL)
2695  {
2696  Query *nothing_qry = makeNode(Query);
2697 
2698  nothing_qry->commandType = CMD_NOTHING;
2699  nothing_qry->rtable = pstate->p_rtable;
2700  nothing_qry->jointree = makeFromExpr(NIL, NULL); /* no join wanted */
2701 
2702  *actions = list_make1(nothing_qry);
2703  }
2704  else
2705  {
2706  ListCell *l;
2707  List *newactions = NIL;
2708 
2709  /*
2710  * transform each statement, like parse_sub_analyze()
2711  */
2712  foreach(l, stmt->actions)
2713  {
2714  Node *action = (Node *) lfirst(l);
2715  ParseState *sub_pstate = make_parsestate(NULL);
2716  Query *sub_qry,
2717  *top_subqry;
2718  bool has_old,
2719  has_new;
2720 
2721  /*
2722  * Since outer ParseState isn't parent of inner, have to pass down
2723  * the query text by hand.
2724  */
2725  sub_pstate->p_sourcetext = queryString;
2726 
2727  /*
2728  * Set up OLD/NEW in the rtable for this statement. The entries
2729  * are added only to relnamespace, not varnamespace, because we
2730  * don't want them to be referred to by unqualified field names
2731  * nor "*" in the rule actions. We decide later whether to put
2732  * them in the joinlist.
2733  */
2734  oldrte = addRangeTableEntryForRelation(sub_pstate, rel,
2735  makeAlias("old", NIL),
2736  false, false);
2737  newrte = addRangeTableEntryForRelation(sub_pstate, rel,
2738  makeAlias("new", NIL),
2739  false, false);
2740  oldrte->requiredPerms = 0;
2741  newrte->requiredPerms = 0;
2742  addRTEtoQuery(sub_pstate, oldrte, false, true, false);
2743  addRTEtoQuery(sub_pstate, newrte, false, true, false);
2744 
2745  /* Transform the rule action statement */
2746  top_subqry = transformStmt(sub_pstate,
2747  (Node *) copyObject(action));
2748 
2749  /*
2750  * We cannot support utility-statement actions (eg NOTIFY) with
2751  * nonempty rule WHERE conditions, because there's no way to make
2752  * the utility action execute conditionally.
2753  */
2754  if (top_subqry->commandType == CMD_UTILITY &&
2755  *whereClause != NULL)
2756  ereport(ERROR,
2757  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2758  errmsg("rules with WHERE conditions can only have SELECT, INSERT, UPDATE, or DELETE actions")));
2759 
2760  /*
2761  * If the action is INSERT...SELECT, OLD/NEW have been pushed down
2762  * into the SELECT, and that's what we need to look at. (Ugly
2763  * kluge ... try to fix this when we redesign querytrees.)
2764  */
2765  sub_qry = getInsertSelectQuery(top_subqry, NULL);
2766 
2767  /*
2768  * If the sub_qry is a setop, we cannot attach any qualifications
2769  * to it, because the planner won't notice them. This could
2770  * perhaps be relaxed someday, but for now, we may as well reject
2771  * such a rule immediately.
2772  */
2773  if (sub_qry->setOperations != NULL && *whereClause != NULL)
2774  ereport(ERROR,
2775  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2776  errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
2777 
2778  /*
2779  * Validate action's use of OLD/NEW, qual too
2780  */
2781  has_old =
2782  rangeTableEntry_used((Node *) sub_qry, PRS2_OLD_VARNO, 0) ||
2783  rangeTableEntry_used(*whereClause, PRS2_OLD_VARNO, 0);
2784  has_new =
2785  rangeTableEntry_used((Node *) sub_qry, PRS2_NEW_VARNO, 0) ||
2786  rangeTableEntry_used(*whereClause, PRS2_NEW_VARNO, 0);
2787 
2788  switch (stmt->event)
2789  {
2790  case CMD_SELECT:
2791  if (has_old)
2792  ereport(ERROR,
2793  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2794  errmsg("ON SELECT rule cannot use OLD")));
2795  if (has_new)
2796  ereport(ERROR,
2797  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2798  errmsg("ON SELECT rule cannot use NEW")));
2799  break;
2800  case CMD_UPDATE:
2801  /* both are OK */
2802  break;
2803  case CMD_INSERT:
2804  if (has_old)
2805  ereport(ERROR,
2806  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2807  errmsg("ON INSERT rule cannot use OLD")));
2808  break;
2809  case CMD_DELETE:
2810  if (has_new)
2811  ereport(ERROR,
2812  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2813  errmsg("ON DELETE rule cannot use NEW")));
2814  break;
2815  default:
2816  elog(ERROR, "unrecognized event type: %d",
2817  (int) stmt->event);
2818  break;
2819  }
2820 
2821  /*
2822  * OLD/NEW are not allowed in WITH queries, because they would
2823  * amount to outer references for the WITH, which we disallow.
2824  * However, they were already in the outer rangetable when we
2825  * analyzed the query, so we have to check.
2826  *
2827  * Note that in the INSERT...SELECT case, we need to examine the
2828  * CTE lists of both top_subqry and sub_qry.
2829  *
2830  * Note that we aren't digging into the body of the query looking
2831  * for WITHs in nested sub-SELECTs. A WITH down there can
2832  * legitimately refer to OLD/NEW, because it'd be an
2833  * indirect-correlated outer reference.
2834  */
2835  if (rangeTableEntry_used((Node *) top_subqry->cteList,
2836  PRS2_OLD_VARNO, 0) ||
2837  rangeTableEntry_used((Node *) sub_qry->cteList,
2838  PRS2_OLD_VARNO, 0))
2839  ereport(ERROR,
2840  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2841  errmsg("cannot refer to OLD within WITH query")));
2842  if (rangeTableEntry_used((Node *) top_subqry->cteList,
2843  PRS2_NEW_VARNO, 0) ||
2844  rangeTableEntry_used((Node *) sub_qry->cteList,
2845  PRS2_NEW_VARNO, 0))
2846  ereport(ERROR,
2847  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2848  errmsg("cannot refer to NEW within WITH query")));
2849 
2850  /*
2851  * For efficiency's sake, add OLD to the rule action's jointree
2852  * only if it was actually referenced in the statement or qual.
2853  *
2854  * For INSERT, NEW is not really a relation (only a reference to
2855  * the to-be-inserted tuple) and should never be added to the
2856  * jointree.
2857  *
2858  * For UPDATE, we treat NEW as being another kind of reference to
2859  * OLD, because it represents references to *transformed* tuples
2860  * of the existing relation. It would be wrong to enter NEW
2861  * separately in the jointree, since that would cause a double
2862  * join of the updated relation. It's also wrong to fail to make
2863  * a jointree entry if only NEW and not OLD is mentioned.
2864  */
2865  if (has_old || (has_new && stmt->event == CMD_UPDATE))
2866  {
2867  /*
2868  * If sub_qry is a setop, manipulating its jointree will do no
2869  * good at all, because the jointree is dummy. (This should be
2870  * a can't-happen case because of prior tests.)
2871  */
2872  if (sub_qry->setOperations != NULL)
2873  ereport(ERROR,
2874  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2875  errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
2876  /* hack so we can use addRTEtoQuery() */
2877  sub_pstate->p_rtable = sub_qry->rtable;
2878  sub_pstate->p_joinlist = sub_qry->jointree->fromlist;
2879  addRTEtoQuery(sub_pstate, oldrte, true, false, false);
2880  sub_qry->jointree->fromlist = sub_pstate->p_joinlist;
2881  }
2882 
2883  newactions = lappend(newactions, top_subqry);
2884 
2885  free_parsestate(sub_pstate);
2886  }
2887 
2888  *actions = newactions;
2889  }
2890 
2891  free_parsestate(pstate);
2892 
2893  /* Close relation, but keep the exclusive lock */
2894  heap_close(rel, NoLock);
2895 }
#define NIL
Definition: pg_list.h:69
Query * getInsertSelectQuery(Query *parsetree, Query ***subquery_ptr)
Definition: rewriteManip.c:921
FromExpr * makeFromExpr(List *fromlist, Node *quals)
Definition: makefuncs.c:284
FromExpr * jointree
Definition: parsenodes.h:138
Definition: nodes.h:517
int errcode(int sqlerrcode)
Definition: elog.c:575
List * actions
Definition: parsenodes.h:2919
AclMode requiredPerms
Definition: parsenodes.h:1070
List * fromlist
Definition: primnodes.h:1479
#define heap_close(r, l)
Definition: heapam.h:97
Form_pg_class rd_rel
Definition: rel.h:84
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:44
#define list_make1(x1)
Definition: pg_list.h:139
void assign_expr_collations(ParseState *pstate, Node *expr)
Alias * makeAlias(const char *aliasname, List *colnames)
Definition: makefuncs.c:386
List * rtable
Definition: parsenodes.h:137
#define ERROR
Definition: elog.h:43
#define NoLock
Definition: lockdefs.h:34
const char * p_sourcetext
Definition: parse_node.h:173
#define ereport(elevel, rest)
Definition: elog.h:122
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:128
#define PRS2_OLD_VARNO
Definition: primnodes.h:161
Relation heap_openrv(const RangeVar *relation, LOCKMODE lockmode)
Definition: heapam.c:1323
CmdType commandType
Definition: parsenodes.h:112
#define makeNode(_type_)
Definition: nodes.h:565
CmdType event
Definition: parsenodes.h:2917
#define lfirst(lc)
Definition: pg_list.h:106
Node * transformWhereClause(ParseState *pstate, Node *clause, ParseExprKind exprKind, const char *constructName)
Node * whereClause
Definition: parsenodes.h:2916
static int list_length(const List *l)
Definition: pg_list.h:89
RangeTblEntry * addRangeTableEntryForRelation(ParseState *pstate, Relation rel, Alias *alias, bool inh, bool inFromCl)
#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:797
List * p_joinlist
Definition: parse_node.h:176
bool rangeTableEntry_used(Node *node, int rt_index, int sublevels_up)
Definition: rewriteManip.c:889
#define elog
Definition: elog.h:219
#define copyObject(obj)
Definition: nodes.h:630
RangeVar * relation
Definition: parsenodes.h:2914
void free_parsestate(ParseState *pstate)
Definition: parse_node.c:77
Definition: pg_list.h:45
#define PRS2_NEW_VARNO
Definition: primnodes.h:162
List * p_rtable
Definition: parse_node.h:174