PostgreSQL Source Code  git master
parse_utilcmd.c File Reference
Include dependency graph for parse_utilcmd.c:

Go to the source code of this file.

Data Structures

struct  CreateStmtContext
 
struct  CreateSchemaStmtContext
 

Macros

#define SUPPORTS_ATTRS(node)
 

Functions

static void transformColumnDefinition (CreateStmtContext *cxt, ColumnDef *column)
 
static void transformTableConstraint (CreateStmtContext *cxt, Constraint *constraint)
 
static void transformTableLikeClause (CreateStmtContext *cxt, TableLikeClause *table_like_clause)
 
static void transformOfType (CreateStmtContext *cxt, TypeName *ofTypename)
 
static CreateStatsStmtgenerateClonedExtStatsStmt (RangeVar *heapRel, Oid heapRelid, Oid source_statsid)
 
static Listget_collation (Oid collation, Oid actual_datatype)
 
static Listget_opclass (Oid opclass, Oid actual_datatype)
 
static void transformIndexConstraints (CreateStmtContext *cxt)
 
static IndexStmttransformIndexConstraint (Constraint *constraint, CreateStmtContext *cxt)
 
static void transformExtendedStatistics (CreateStmtContext *cxt)
 
static void transformFKConstraints (CreateStmtContext *cxt, bool skipValidation, bool isAddConstraint)
 
static void transformCheckConstraints (CreateStmtContext *cxt, bool skipValidation)
 
static void transformConstraintAttrs (CreateStmtContext *cxt, List *constraintList)
 
static void transformColumnType (CreateStmtContext *cxt, ColumnDef *column)
 
static void setSchemaName (char *context_schema, char **stmt_schema_name)
 
static void transformPartitionCmd (CreateStmtContext *cxt, PartitionCmd *cmd)
 
static void validateInfiniteBounds (ParseState *pstate, List *blist)
 
static ConsttransformPartitionBoundValue (ParseState *pstate, A_Const *con, const char *colName, Oid colType, int32 colTypmod)
 
ListtransformCreateStmt (CreateStmt *stmt, const char *queryString)
 
static void generateSerialExtraStmts (CreateStmtContext *cxt, ColumnDef *column, Oid seqtypid, List *seqoptions, bool for_identity, char **snamespace_p, char **sname_p)
 
IndexStmtgenerateClonedIndexStmt (RangeVar *heapRel, Oid heapRelid, Relation source_idx, const AttrNumber *attmap, int attmap_length, Oid *constraintOid)
 
IndexStmttransformIndexStmt (Oid relid, IndexStmt *stmt, const char *queryString)
 
void transformRuleStmt (RuleStmt *stmt, const char *queryString, List **actions, Node **whereClause)
 
ListtransformAlterTableStmt (Oid relid, AlterTableStmt *stmt, const char *queryString)
 
ListtransformCreateSchemaStmt (CreateSchemaStmt *stmt)
 
PartitionBoundSpectransformPartitionBound (ParseState *pstate, Relation parent, PartitionBoundSpec *spec)
 

Macro Definition Documentation

◆ SUPPORTS_ATTRS

#define SUPPORTS_ATTRS (   node)
Value:
((node) != NULL && \
((node)->contype == CONSTR_PRIMARY || \
(node)->contype == CONSTR_UNIQUE || \
(node)->contype == CONSTR_EXCLUSION || \
(node)->contype == CONSTR_FOREIGN))

Referenced by transformConstraintAttrs().

Function Documentation

◆ generateClonedExtStatsStmt()

static CreateStatsStmt * generateClonedExtStatsStmt ( RangeVar heapRel,
Oid  heapRelid,
Oid  source_statsid 
)
static

Definition at line 1643 of file parse_utilcmd.c.

References ARR_DATA_PTR, ARR_DIMS, ARR_ELEMTYPE, ARR_HASNULL, ARR_NDIM, Assert, attnum, DatumGetArrayTypeP, CreateStatsStmt::defnames, elog, ERROR, CreateStatsStmt::exprs, ColumnRef::fields, get_attname(), GETSTRUCT, HeapTupleIsValid, i, CreateStatsStmt::if_not_exists, lappend(), list_make1, ColumnRef::location, makeNode, makeString(), NIL, ObjectIdGetDatum, OidIsValid, CreateStatsStmt::relations, ReleaseSysCache(), SearchSysCache1(), CreateStatsStmt::stat_types, STATEXTOID, CreateStatsStmt::stxcomment, and SysCacheGetAttr().

Referenced by transformTableLikeClause().

1645 {
1646  HeapTuple ht_stats;
1647  Form_pg_statistic_ext statsrec;
1648  CreateStatsStmt *stats;
1649  List *stat_types = NIL;
1650  List *def_names = NIL;
1651  bool isnull;
1652  Datum datum;
1653  ArrayType *arr;
1654  char *enabled;
1655  int i;
1656 
1657  Assert(OidIsValid(heapRelid));
1658  Assert(heapRel != NULL);
1659 
1660  /*
1661  * Fetch pg_statistic_ext tuple of source statistics object.
1662  */
1663  ht_stats = SearchSysCache1(STATEXTOID, ObjectIdGetDatum(source_statsid));
1664  if (!HeapTupleIsValid(ht_stats))
1665  elog(ERROR, "cache lookup failed for statistics object %u", source_statsid);
1666  statsrec = (Form_pg_statistic_ext) GETSTRUCT(ht_stats);
1667 
1668  /* Determine which statistics types exist */
1669  datum = SysCacheGetAttr(STATEXTOID, ht_stats,
1670  Anum_pg_statistic_ext_stxkind, &isnull);
1671  Assert(!isnull);
1672  arr = DatumGetArrayTypeP(datum);
1673  if (ARR_NDIM(arr) != 1 ||
1674  ARR_HASNULL(arr) ||
1675  ARR_ELEMTYPE(arr) != CHAROID)
1676  elog(ERROR, "stxkind is not a 1-D char array");
1677  enabled = (char *) ARR_DATA_PTR(arr);
1678  for (i = 0; i < ARR_DIMS(arr)[0]; i++)
1679  {
1680  if (enabled[i] == STATS_EXT_NDISTINCT)
1681  stat_types = lappend(stat_types, makeString("ndistinct"));
1682  else if (enabled[i] == STATS_EXT_DEPENDENCIES)
1683  stat_types = lappend(stat_types, makeString("dependencies"));
1684  else
1685  elog(ERROR, "unrecognized statistics kind %c", enabled[i]);
1686  }
1687 
1688  /* Determine which columns the statistics are on */
1689  for (i = 0; i < statsrec->stxkeys.dim1; i++)
1690  {
1691  ColumnRef *cref = makeNode(ColumnRef);
1692  AttrNumber attnum = statsrec->stxkeys.values[i];
1693 
1694  cref->fields = list_make1(makeString(get_attname(heapRelid,
1695  attnum, false)));
1696  cref->location = -1;
1697 
1698  def_names = lappend(def_names, cref);
1699  }
1700 
1701  /* finally, build the output node */
1702  stats = makeNode(CreateStatsStmt);
1703  stats->defnames = NULL;
1704  stats->stat_types = stat_types;
1705  stats->exprs = def_names;
1706  stats->relations = list_make1(heapRel);
1707  stats->stxcomment = NULL;
1708  stats->if_not_exists = false;
1709 
1710  /* Clean up */
1711  ReleaseSysCache(ht_stats);
1712 
1713  return stats;
1714 }
Value * makeString(char *str)
Definition: value.c:53
#define NIL
Definition: pg_list.h:69
#define GETSTRUCT(TUP)
Definition: htup_details.h:668
#define OidIsValid(objectId)
Definition: c.h:605
int location
Definition: parsenodes.h:237
#define list_make1(x1)
Definition: pg_list.h:139
#define ObjectIdGetDatum(X)
Definition: postgres.h:492
#define ERROR
Definition: elog.h:43
#define ARR_DIMS(a)
Definition: array.h:279
#define ARR_DATA_PTR(a)
Definition: array.h:307
#define ARR_HASNULL(a)
Definition: array.h:276
List * lappend(List *list, void *datum)
Definition: list.c:128
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1112
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
int16 attnum
Definition: pg_attribute.h:79
#define makeNode(_type_)
Definition: nodes.h:565
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:699
#define ARR_NDIM(a)
Definition: array.h:275
int i
char * get_attname(Oid relid, AttrNumber attnum, bool missing_ok)
Definition: lsyscache.c:775
#define elog
Definition: elog.h:219
Definition: pg_list.h:45
#define ARR_ELEMTYPE(a)
Definition: array.h:277
int16 AttrNumber
Definition: attnum.h:21
List * fields
Definition: parsenodes.h:236
FormData_pg_statistic_ext * Form_pg_statistic_ext
#define DatumGetArrayTypeP(X)
Definition: array.h:246

◆ generateClonedIndexStmt()

IndexStmt* generateClonedIndexStmt ( RangeVar heapRel,
Oid  heapRelid,
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

◆ generateSerialExtraStmts()

static void generateSerialExtraStmts ( CreateStmtContext cxt,
ColumnDef column,
Oid  seqtypid,
List seqoptions,
bool  for_identity,
char **  snamespace_p,
char **  sname_p 
)
static

Definition at line 371 of file parse_utilcmd.c.

References CreateStmtContext::alist, DefElem::arg, CreateStmtContext::blist, castNode, ChooseRelationName(), ColumnDef::colname, DEBUG1, DefElem::defname, ereport, errcode(), errmsg(), ERROR, CreateSeqStmt::for_identity, AlterSeqStmt::for_identity, get_namespace_name(), ColumnDef::identitySequence, InvalidOid, lappend(), lcons(), lfirst_node, list_delete_ptr(), list_make1, list_make3, makeDefElem(), makeNode, makeRangeVar(), makeRangeVarFromNameList(), makeString(), makeTypeNameFromOid(), CreateSeqStmt::options, AlterSeqStmt::options, CreateSeqStmt::ownerId, RangeVarAdjustRelationPersistence(), RangeVarGetCreationNamespace(), RelationData::rd_rel, CreateStmtContext::rel, CreateStmtContext::relation, RelationGetNamespace, RangeVar::relname, RangeVar::schemaname, CreateSeqStmt::sequence, AlterSeqStmt::sequence, and CreateStmtContext::stmtType.

Referenced by transformAlterTableStmt(), transformColumnDefinition(), and transformTableLikeClause().

374 {
375  ListCell *option;
376  DefElem *nameEl = NULL;
377  Oid snamespaceid;
378  char *snamespace;
379  char *sname;
380  CreateSeqStmt *seqstmt;
381  AlterSeqStmt *altseqstmt;
382  List *attnamelist;
383 
384  /*
385  * Determine namespace and name to use for the sequence.
386  *
387  * First, check if a sequence name was passed in as an option. This is
388  * used by pg_dump. Else, generate a name.
389  *
390  * Although we use ChooseRelationName, it's not guaranteed that the
391  * selected sequence name won't conflict; given sufficiently long field
392  * names, two different serial columns in the same table could be assigned
393  * the same sequence name, and we'd not notice since we aren't creating
394  * the sequence quite yet. In practice this seems quite unlikely to be a
395  * problem, especially since few people would need two serial columns in
396  * one table.
397  */
398  foreach(option, seqoptions)
399  {
400  DefElem *defel = lfirst_node(DefElem, option);
401 
402  if (strcmp(defel->defname, "sequence_name") == 0)
403  {
404  if (nameEl)
405  ereport(ERROR,
406  (errcode(ERRCODE_SYNTAX_ERROR),
407  errmsg("conflicting or redundant options")));
408  nameEl = defel;
409  }
410  }
411 
412  if (nameEl)
413  {
415 
416  snamespace = rv->schemaname;
417  if (!snamespace)
418  {
419  /* Given unqualified SEQUENCE NAME, select namespace */
420  if (cxt->rel)
421  snamespaceid = RelationGetNamespace(cxt->rel);
422  else
423  snamespaceid = RangeVarGetCreationNamespace(cxt->relation);
424  snamespace = get_namespace_name(snamespaceid);
425  }
426  sname = rv->relname;
427  /* Remove the SEQUENCE NAME item from seqoptions */
428  seqoptions = list_delete_ptr(seqoptions, nameEl);
429  }
430  else
431  {
432  if (cxt->rel)
433  snamespaceid = RelationGetNamespace(cxt->rel);
434  else
435  {
436  snamespaceid = RangeVarGetCreationNamespace(cxt->relation);
437  RangeVarAdjustRelationPersistence(cxt->relation, snamespaceid);
438  }
439  snamespace = get_namespace_name(snamespaceid);
440  sname = ChooseRelationName(cxt->relation->relname,
441  column->colname,
442  "seq",
443  snamespaceid);
444  }
445 
446  ereport(DEBUG1,
447  (errmsg("%s will create implicit sequence \"%s\" for serial column \"%s.%s\"",
448  cxt->stmtType, sname,
449  cxt->relation->relname, column->colname)));
450 
451  /*
452  * Build a CREATE SEQUENCE command to create the sequence object, and add
453  * it to the list of things to be done before this CREATE/ALTER TABLE.
454  */
455  seqstmt = makeNode(CreateSeqStmt);
456  seqstmt->for_identity = for_identity;
457  seqstmt->sequence = makeRangeVar(snamespace, sname, -1);
458  seqstmt->options = seqoptions;
459 
460  /*
461  * If a sequence data type was specified, add it to the options. Prepend
462  * to the list rather than append; in case a user supplied their own AS
463  * clause, the "redundant options" error will point to their occurrence,
464  * not our synthetic one.
465  */
466  if (seqtypid)
467  seqstmt->options = lcons(makeDefElem("as",
468  (Node *) makeTypeNameFromOid(seqtypid, -1),
469  -1),
470  seqstmt->options);
471 
472  /*
473  * If this is ALTER ADD COLUMN, make sure the sequence will be owned by
474  * the table's owner. The current user might be someone else (perhaps a
475  * superuser, or someone who's only a member of the owning role), but the
476  * SEQUENCE OWNED BY mechanisms will bleat unless table and sequence have
477  * exactly the same owning role.
478  */
479  if (cxt->rel)
480  seqstmt->ownerId = cxt->rel->rd_rel->relowner;
481  else
482  seqstmt->ownerId = InvalidOid;
483 
484  cxt->blist = lappend(cxt->blist, seqstmt);
485 
486  /*
487  * Store the identity sequence name that we decided on. ALTER TABLE ...
488  * ADD COLUMN ... IDENTITY needs this so that it can fill the new column
489  * with values from the sequence, while the association of the sequence
490  * with the table is not set until after the ALTER TABLE.
491  */
492  column->identitySequence = seqstmt->sequence;
493 
494  /*
495  * Build an ALTER SEQUENCE ... OWNED BY command to mark the sequence as
496  * owned by this column, and add it to the list of things to be done after
497  * this CREATE/ALTER TABLE.
498  */
499  altseqstmt = makeNode(AlterSeqStmt);
500  altseqstmt->sequence = makeRangeVar(snamespace, sname, -1);
501  attnamelist = list_make3(makeString(snamespace),
502  makeString(cxt->relation->relname),
503  makeString(column->colname));
504  altseqstmt->options = list_make1(makeDefElem("owned_by",
505  (Node *) attnamelist, -1));
506  altseqstmt->for_identity = for_identity;
507 
508  cxt->alist = lappend(cxt->alist, altseqstmt);
509 
510  if (snamespace_p)
511  *snamespace_p = snamespace;
512  if (sname_p)
513  *sname_p = sname;
514 }
Value * makeString(char *str)
Definition: value.c:53
#define list_make3(x1, x2, x3)
Definition: pg_list.h:141
#define DEBUG1
Definition: elog.h:25
#define castNode(_type_, nodeptr)
Definition: nodes.h:586
Definition: nodes.h:517
int errcode(int sqlerrcode)
Definition: elog.c:575
RangeVar * makeRangeVarFromNameList(List *names)
Definition: namespace.c:3042
List * list_delete_ptr(List *list, void *datum)
Definition: list.c:590
Form_pg_class rd_rel
Definition: rel.h:84
unsigned int Oid
Definition: postgres_ext.h:31
DefElem * makeDefElem(char *name, Node *arg, int location)
Definition: makefuncs.c:546
void RangeVarAdjustRelationPersistence(RangeVar *newRelation, Oid nspid)
Definition: namespace.c:634
List * options
Definition: parsenodes.h:2495
char * schemaname
Definition: primnodes.h:68
#define list_make1(x1)
Definition: pg_list.h:139
RangeVar * identitySequence
Definition: parsenodes.h:658
char * relname
Definition: primnodes.h:69
RangeVar * relation
Definition: parse_utilcmd.c:78
#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 ereport(elevel, rest)
Definition: elog.h:122
Node * arg
Definition: parsenodes.h:731
List * lappend(List *list, void *datum)
Definition: list.c:128
TypeName * makeTypeNameFromOid(Oid typeOid, int32 typmod)
Definition: makefuncs.c:471
#define InvalidOid
Definition: postgres_ext.h:36
RangeVar * sequence
Definition: parsenodes.h:2494
RangeVar * sequence
Definition: parsenodes.h:2484
List * lcons(void *datum, List *list)
Definition: list.c:259
#define makeNode(_type_)
Definition: nodes.h:565
const char * stmtType
Definition: parse_utilcmd.c:77
int errmsg(const char *fmt,...)
Definition: elog.c:797
bool for_identity
Definition: parsenodes.h:2496
char * defname
Definition: parsenodes.h:730
char * colname
Definition: parsenodes.h:647
char * ChooseRelationName(const char *name1, const char *name2, const char *label, Oid namespaceid)
Definition: indexcmds.c:1988
Definition: pg_list.h:45
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition: makefuncs.c:421
Oid RangeVarGetCreationNamespace(const RangeVar *newRelation)
Definition: namespace.c:440
List * options
Definition: parsenodes.h:2485
#define RelationGetNamespace(relation)
Definition: rel.h:448

◆ get_collation()

static List * get_collation ( Oid  collation,
Oid  actual_datatype 
)
static

Definition at line 1723 of file parse_utilcmd.c.

References COLLOID, elog, ERROR, get_namespace_name(), get_typcollation(), GETSTRUCT, HeapTupleIsValid, list_make2, makeString(), NameStr, NIL, ObjectIdGetDatum, OidIsValid, pstrdup(), ReleaseSysCache(), and SearchSysCache1().

Referenced by generateClonedIndexStmt().

1724 {
1725  List *result;
1726  HeapTuple ht_coll;
1727  Form_pg_collation coll_rec;
1728  char *nsp_name;
1729  char *coll_name;
1730 
1731  if (!OidIsValid(collation))
1732  return NIL; /* easy case */
1733  if (collation == get_typcollation(actual_datatype))
1734  return NIL; /* just let it default */
1735 
1736  ht_coll = SearchSysCache1(COLLOID, ObjectIdGetDatum(collation));
1737  if (!HeapTupleIsValid(ht_coll))
1738  elog(ERROR, "cache lookup failed for collation %u", collation);
1739  coll_rec = (Form_pg_collation) GETSTRUCT(ht_coll);
1740 
1741  /* For simplicity, we always schema-qualify the name */
1742  nsp_name = get_namespace_name(coll_rec->collnamespace);
1743  coll_name = pstrdup(NameStr(coll_rec->collname));
1744  result = list_make2(makeString(nsp_name), makeString(coll_name));
1745 
1746  ReleaseSysCache(ht_coll);
1747  return result;
1748 }
#define list_make2(x1, x2)
Definition: pg_list.h:140
Value * makeString(char *str)
Definition: value.c:53
#define NIL
Definition: pg_list.h:69
#define GETSTRUCT(TUP)
Definition: htup_details.h:668
char * pstrdup(const char *in)
Definition: mcxt.c:1161
#define OidIsValid(objectId)
Definition: c.h:605
#define ObjectIdGetDatum(X)
Definition: postgres.h:492
#define ERROR
Definition: elog.h:43
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3051
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1112
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
Oid get_typcollation(Oid typid)
Definition: lsyscache.c:2799
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
FormData_pg_collation * Form_pg_collation
Definition: pg_collation.h:49
#define NameStr(name)
Definition: c.h:576
#define elog
Definition: elog.h:219
Definition: pg_list.h:45

◆ get_opclass()

static List * get_opclass ( Oid  opclass,
Oid  actual_datatype 
)
static

Definition at line 1757 of file parse_utilcmd.c.

References CLAOID, elog, ERROR, get_namespace_name(), GetDefaultOpClass(), GETSTRUCT, HeapTupleIsValid, list_make2, makeString(), NameStr, NIL, ObjectIdGetDatum, pstrdup(), ReleaseSysCache(), and SearchSysCache1().

Referenced by generateClonedIndexStmt().

1758 {
1759  List *result = NIL;
1760  HeapTuple ht_opc;
1761  Form_pg_opclass opc_rec;
1762 
1763  ht_opc = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclass));
1764  if (!HeapTupleIsValid(ht_opc))
1765  elog(ERROR, "cache lookup failed for opclass %u", opclass);
1766  opc_rec = (Form_pg_opclass) GETSTRUCT(ht_opc);
1767 
1768  if (GetDefaultOpClass(actual_datatype, opc_rec->opcmethod) != opclass)
1769  {
1770  /* For simplicity, we always schema-qualify the name */
1771  char *nsp_name = get_namespace_name(opc_rec->opcnamespace);
1772  char *opc_name = pstrdup(NameStr(opc_rec->opcname));
1773 
1774  result = list_make2(makeString(nsp_name), makeString(opc_name));
1775  }
1776 
1777  ReleaseSysCache(ht_opc);
1778  return result;
1779 }
#define list_make2(x1, x2)
Definition: pg_list.h:140
Value * makeString(char *str)
Definition: value.c:53
#define NIL
Definition: pg_list.h:69
Oid GetDefaultOpClass(Oid type_id, Oid am_id)
Definition: indexcmds.c:1799
#define GETSTRUCT(TUP)
Definition: htup_details.h:668
char * pstrdup(const char *in)
Definition: mcxt.c:1161
#define ObjectIdGetDatum(X)
Definition: postgres.h:492
#define ERROR
Definition: elog.h:43
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3051
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1112
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define NameStr(name)
Definition: c.h:576
#define elog
Definition: elog.h:219
FormData_pg_opclass * Form_pg_opclass
Definition: pg_opclass.h:81
Definition: pg_list.h:45

◆ setSchemaName()

static void setSchemaName ( char *  context_schema,
char **  stmt_schema_name 
)
static

Definition at line 3532 of file parse_utilcmd.c.

References ereport, errcode(), errmsg(), and ERROR.

Referenced by transformCreateSchemaStmt().

3533 {
3534  if (*stmt_schema_name == NULL)
3535  *stmt_schema_name = context_schema;
3536  else if (strcmp(context_schema, *stmt_schema_name) != 0)
3537  ereport(ERROR,
3538  (errcode(ERRCODE_INVALID_SCHEMA_DEFINITION),
3539  errmsg("CREATE specifies a schema (%s) "
3540  "different from the one being created (%s)",
3541  *stmt_schema_name, context_schema)));
3542 }
int errcode(int sqlerrcode)
Definition: elog.c:575
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:122
int errmsg(const char *fmt,...)
Definition: elog.c:797

◆ 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

◆ transformCheckConstraints()

static void transformCheckConstraints ( CreateStmtContext cxt,
bool  skipValidation 
)
static

Definition at line 2401 of file parse_utilcmd.c.

References CreateStmtContext::ckconstraints, Constraint::initially_valid, lfirst, NIL, and Constraint::skip_validation.

Referenced by transformAlterTableStmt(), and transformCreateStmt().

2402 {
2403  ListCell *ckclist;
2404 
2405  if (cxt->ckconstraints == NIL)
2406  return;
2407 
2408  /*
2409  * If creating a new table (but not a foreign table), we can safely skip
2410  * validation of check constraints, and nonetheless mark them valid. (This
2411  * will override any user-supplied NOT VALID flag.)
2412  */
2413  if (skipValidation)
2414  {
2415  foreach(ckclist, cxt->ckconstraints)
2416  {
2417  Constraint *constraint = (Constraint *) lfirst(ckclist);
2418 
2419  constraint->skip_validation = true;
2420  constraint->initially_valid = true;
2421  }
2422  }
2423 }
#define NIL
Definition: pg_list.h:69
bool initially_valid
Definition: parsenodes.h:2136
#define lfirst(lc)
Definition: pg_list.h:106
bool skip_validation
Definition: parsenodes.h:2135

◆ transformColumnDefinition()

static void transformColumnDefinition ( CreateStmtContext cxt,
ColumnDef column 
)
static

Definition at line 522 of file parse_utilcmd.c.

References CreateStmtContext::alist, TypeCast::arg, TypeName::arrayBounds, Assert, AT_AlterColumnGenericOptions, AlterTableCmd::behavior, CreateStmtContext::ckconstraints, AlterTableStmt::cmds, ColumnDef::colname, CreateStmtContext::columns, CONSTR_ATTR_DEFERRABLE, CONSTR_ATTR_DEFERRED, CONSTR_ATTR_IMMEDIATE, CONSTR_ATTR_NOT_DEFERRABLE, CONSTR_CHECK, CONSTR_DEFAULT, CONSTR_EXCLUSION, CONSTR_FOREIGN, CONSTR_IDENTITY, CONSTR_NOTNULL, CONSTR_NULL, CONSTR_PRIMARY, CONSTR_UNIQUE, ColumnDef::constraints, Constraint::contype, Constraint::cooked_expr, AlterTableCmd::def, DROP_RESTRICT, elog, ereport, errcode(), errmsg(), ERROR, ColumnDef::fdwoptions, Constraint::fk_attrs, CreateStmtContext::fkconstraints, Constraint::generated_when, generateSerialExtraStmts(), HeapTupleGetOid, ColumnDef::identity, ColumnDef::is_not_null, CreateStmtContext::isforeign, CreateStmtContext::ixconstraints, Constraint::keys, lappend(), lfirst_node, linitial, list_length(), list_make1, TypeName::location, A_Const::location, TypeCast::location, Constraint::location, makeFuncCall(), makeNode, makeString(), AlterTableCmd::missing_ok, AlterTableCmd::name, TypeName::names, NIL, OBJECT_FOREIGN_TABLE, CreateStmtContext::ofType, Constraint::options, parser_errposition(), CreateStmtContext::partbound, TypeName::pct_type, CreateStmtContext::pstate, quote_qualified_identifier(), ColumnDef::raw_default, Constraint::raw_expr, CreateStmtContext::relation, AlterTableStmt::relation, ReleaseSysCache(), AlterTableStmt::relkind, RangeVar::relname, Value::ValUnion::str, strVal, AlterTableCmd::subtype, SystemFuncName(), SystemTypeName(), T_String, transformColumnType(), transformConstraintAttrs(), Value::type, TypeCast::typeName, ColumnDef::typeName, typenameType(), TypeName::typeOid, Value::val, and A_Const::val.

Referenced by transformAlterTableStmt(), and transformCreateStmt().

523 {
524  bool is_serial;
525  bool saw_nullable;
526  bool saw_default;
527  bool saw_identity;
528  ListCell *clist;
529 
530  cxt->columns = lappend(cxt->columns, column);
531 
532  /* Check for SERIAL pseudo-types */
533  is_serial = false;
534  if (column->typeName
535  && list_length(column->typeName->names) == 1
536  && !column->typeName->pct_type)
537  {
538  char *typname = strVal(linitial(column->typeName->names));
539 
540  if (strcmp(typname, "smallserial") == 0 ||
541  strcmp(typname, "serial2") == 0)
542  {
543  is_serial = true;
544  column->typeName->names = NIL;
545  column->typeName->typeOid = INT2OID;
546  }
547  else if (strcmp(typname, "serial") == 0 ||
548  strcmp(typname, "serial4") == 0)
549  {
550  is_serial = true;
551  column->typeName->names = NIL;
552  column->typeName->typeOid = INT4OID;
553  }
554  else if (strcmp(typname, "bigserial") == 0 ||
555  strcmp(typname, "serial8") == 0)
556  {
557  is_serial = true;
558  column->typeName->names = NIL;
559  column->typeName->typeOid = INT8OID;
560  }
561 
562  /*
563  * We have to reject "serial[]" explicitly, because once we've set
564  * typeid, LookupTypeName won't notice arrayBounds. We don't need any
565  * special coding for serial(typmod) though.
566  */
567  if (is_serial && column->typeName->arrayBounds != NIL)
568  ereport(ERROR,
569  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
570  errmsg("array of serial is not implemented"),
572  column->typeName->location)));
573  }
574 
575  /* Do necessary work on the column type declaration */
576  if (column->typeName)
577  transformColumnType(cxt, column);
578 
579  /* Special actions for SERIAL pseudo-types */
580  if (is_serial)
581  {
582  char *snamespace;
583  char *sname;
584  char *qstring;
585  A_Const *snamenode;
586  TypeCast *castnode;
587  FuncCall *funccallnode;
588  Constraint *constraint;
589 
590  generateSerialExtraStmts(cxt, column,
591  column->typeName->typeOid, NIL, false,
592  &snamespace, &sname);
593 
594  /*
595  * Create appropriate constraints for SERIAL. We do this in full,
596  * rather than shortcutting, so that we will detect any conflicting
597  * constraints the user wrote (like a different DEFAULT).
598  *
599  * Create an expression tree representing the function call
600  * nextval('sequencename'). We cannot reduce the raw tree to cooked
601  * form until after the sequence is created, but there's no need to do
602  * so.
603  */
604  qstring = quote_qualified_identifier(snamespace, sname);
605  snamenode = makeNode(A_Const);
606  snamenode->val.type = T_String;
607  snamenode->val.val.str = qstring;
608  snamenode->location = -1;
609  castnode = makeNode(TypeCast);
610  castnode->typeName = SystemTypeName("regclass");
611  castnode->arg = (Node *) snamenode;
612  castnode->location = -1;
613  funccallnode = makeFuncCall(SystemFuncName("nextval"),
614  list_make1(castnode),
615  -1);
616  constraint = makeNode(Constraint);
617  constraint->contype = CONSTR_DEFAULT;
618  constraint->location = -1;
619  constraint->raw_expr = (Node *) funccallnode;
620  constraint->cooked_expr = NULL;
621  column->constraints = lappend(column->constraints, constraint);
622 
623  constraint = makeNode(Constraint);
624  constraint->contype = CONSTR_NOTNULL;
625  constraint->location = -1;
626  column->constraints = lappend(column->constraints, constraint);
627  }
628 
629  /* Process column constraints, if any... */
631 
632  saw_nullable = false;
633  saw_default = false;
634  saw_identity = false;
635 
636  foreach(clist, column->constraints)
637  {
638  Constraint *constraint = lfirst_node(Constraint, clist);
639 
640  switch (constraint->contype)
641  {
642  case CONSTR_NULL:
643  if (saw_nullable && column->is_not_null)
644  ereport(ERROR,
645  (errcode(ERRCODE_SYNTAX_ERROR),
646  errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
647  column->colname, cxt->relation->relname),
649  constraint->location)));
650  column->is_not_null = false;
651  saw_nullable = true;
652  break;
653 
654  case CONSTR_NOTNULL:
655  if (saw_nullable && !column->is_not_null)
656  ereport(ERROR,
657  (errcode(ERRCODE_SYNTAX_ERROR),
658  errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
659  column->colname, cxt->relation->relname),
661  constraint->location)));
662  column->is_not_null = true;
663  saw_nullable = true;
664  break;
665 
666  case CONSTR_DEFAULT:
667  if (saw_default)
668  ereport(ERROR,
669  (errcode(ERRCODE_SYNTAX_ERROR),
670  errmsg("multiple default values specified for column \"%s\" of table \"%s\"",
671  column->colname, cxt->relation->relname),
673  constraint->location)));
674  column->raw_default = constraint->raw_expr;
675  Assert(constraint->cooked_expr == NULL);
676  saw_default = true;
677  break;
678 
679  case CONSTR_IDENTITY:
680  {
681  Type ctype;
682  Oid typeOid;
683 
684  if (cxt->ofType)
685  ereport(ERROR,
686  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
687  errmsg("identity columns are not supported on typed tables")));
688  if (cxt->partbound)
689  ereport(ERROR,
690  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
691  errmsg("identity columns are not supported on partitions")));
692 
693  ctype = typenameType(cxt->pstate, column->typeName, NULL);
694  typeOid = HeapTupleGetOid(ctype);
695  ReleaseSysCache(ctype);
696 
697  if (saw_identity)
698  ereport(ERROR,
699  (errcode(ERRCODE_SYNTAX_ERROR),
700  errmsg("multiple identity specifications for column \"%s\" of table \"%s\"",
701  column->colname, cxt->relation->relname),
703  constraint->location)));
704 
705  generateSerialExtraStmts(cxt, column,
706  typeOid, constraint->options, true,
707  NULL, NULL);
708 
709  column->identity = constraint->generated_when;
710  saw_identity = true;
711  column->is_not_null = true;
712  break;
713  }
714 
715  case CONSTR_CHECK:
716  cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
717  break;
718 
719  case CONSTR_PRIMARY:
720  if (cxt->isforeign)
721  ereport(ERROR,
722  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
723  errmsg("primary key constraints are not supported on foreign tables"),
725  constraint->location)));
726  /* FALL THRU */
727 
728  case CONSTR_UNIQUE:
729  if (cxt->isforeign)
730  ereport(ERROR,
731  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
732  errmsg("unique constraints are not supported on foreign tables"),
734  constraint->location)));
735  if (constraint->keys == NIL)
736  constraint->keys = list_make1(makeString(column->colname));
737  cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
738  break;
739 
740  case CONSTR_EXCLUSION:
741  /* grammar does not allow EXCLUDE as a column constraint */
742  elog(ERROR, "column exclusion constraints are not supported");
743  break;
744 
745  case CONSTR_FOREIGN:
746  if (cxt->isforeign)
747  ereport(ERROR,
748  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
749  errmsg("foreign key constraints are not supported on foreign tables"),
751  constraint->location)));
752 
753  /*
754  * Fill in the current attribute's name and throw it into the
755  * list of FK constraints to be processed later.
756  */
757  constraint->fk_attrs = list_make1(makeString(column->colname));
758  cxt->fkconstraints = lappend(cxt->fkconstraints, constraint);
759  break;
760 
765  /* transformConstraintAttrs took care of these */
766  break;
767 
768  default:
769  elog(ERROR, "unrecognized constraint type: %d",
770  constraint->contype);
771  break;
772  }
773 
774  if (saw_default && saw_identity)
775  ereport(ERROR,
776  (errcode(ERRCODE_SYNTAX_ERROR),
777  errmsg("both default and identity specified for column \"%s\" of table \"%s\"",
778  column->colname, cxt->relation->relname),
780  constraint->location)));
781  }
782 
783  /*
784  * If needed, generate ALTER FOREIGN TABLE ALTER COLUMN statement to add
785  * per-column foreign data wrapper options to this column after creation.
786  */
787  if (column->fdwoptions != NIL)
788  {
789  AlterTableStmt *stmt;
790  AlterTableCmd *cmd;
791 
792  cmd = makeNode(AlterTableCmd);
794  cmd->name = column->colname;
795  cmd->def = (Node *) column->fdwoptions;
796  cmd->behavior = DROP_RESTRICT;
797  cmd->missing_ok = false;
798 
799  stmt = makeNode(AlterTableStmt);
800  stmt->relation = cxt->relation;
801  stmt->cmds = NIL;
803  stmt->cmds = lappend(stmt->cmds, cmd);
804 
805  cxt->alist = lappend(cxt->alist, stmt);
806  }
807 }
Value * makeString(char *str)
Definition: value.c:53
#define NIL
Definition: pg_list.h:69
List * SystemFuncName(char *name)
Oid typeOid
Definition: parsenodes.h:211
List * keys
Definition: parsenodes.h:2107
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
Type typenameType(ParseState *pstate, const TypeName *typeName, int32 *typmod_p)
Definition: parse_type.c:247
List * names
Definition: parsenodes.h:210
char identity
Definition: parsenodes.h:657
List * constraints
Definition: parsenodes.h:662
Node * raw_expr
Definition: parsenodes.h:2102
Definition: nodes.h:517
#define strVal(v)
Definition: value.h:54
int errcode(int sqlerrcode)
Definition: elog.c:575
AlterTableType subtype
Definition: parsenodes.h:1806
bool is_not_null
Definition: parsenodes.h:651
unsigned int Oid
Definition: postgres_ext.h:31
List * options
Definition: parsenodes.h:2116
int location
Definition: parsenodes.h:301
#define list_make1(x1)
Definition: pg_list.h:139
ParseState * pstate
Definition: parse_utilcmd.c:76
char * relname
Definition: primnodes.h:69
RangeVar * relation
Definition: parse_utilcmd.c:78
#define linitial(l)
Definition: pg_list.h:111
#define ERROR
Definition: elog.h:43
static void transformConstraintAttrs(CreateStmtContext *cxt, List *constraintList)
#define lfirst_node(type, lc)
Definition: pg_list.h:109
union Value::ValUnion val
List * fdwoptions
Definition: parsenodes.h:663
static void transformColumnType(CreateStmtContext *cxt, ColumnDef *column)
#define ereport(elevel, rest)
Definition: elog.h:122
ObjectType relkind
Definition: parsenodes.h:1720
PartitionBoundSpec * partbound
Definition: parse_utilcmd.c:96
Node * raw_default
Definition: parsenodes.h:655
List * lappend(List *list, void *datum)
Definition: list.c:128
char * quote_qualified_identifier(const char *qualifier, const char *ident)
Definition: ruleutils.c:10574
FuncCall * makeFuncCall(List *name, List *args, int location)
Definition: makefuncs.c:585
TypeName * SystemTypeName(char *name)
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
TypeName * typeName
Definition: parsenodes.h:300
#define makeNode(_type_)
Definition: nodes.h:565
#define Assert(condition)
Definition: c.h:699
int location
Definition: parsenodes.h:290
int location
Definition: parsenodes.h:217
static int list_length(const List *l)
Definition: pg_list.h:89
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
TypeName * typeName
Definition: parsenodes.h:648
List * arrayBounds
Definition: parsenodes.h:216
int errmsg(const char *fmt,...)
Definition: elog.c:797
RangeVar * relation
Definition: parsenodes.h:1718
char * str
Definition: value.h:48
ConstrType contype
Definition: parsenodes.h:2092
DropBehavior behavior
Definition: parsenodes.h:1814
char * colname
Definition: parsenodes.h:647
#define elog
Definition: elog.h:219
char * cooked_expr
Definition: parsenodes.h:2103
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:707
Value val
Definition: parsenodes.h:289
List * fk_attrs
Definition: parsenodes.h:2125
NodeTag type
Definition: value.h:44
bool pct_type
Definition: parsenodes.h:213
Node * arg
Definition: parsenodes.h:299

◆ transformColumnType()

static void transformColumnType ( CreateStmtContext cxt,
ColumnDef column 
)
static

Definition at line 3374 of file parse_utilcmd.c.

References ColumnDef::collClause, CollateClause::collname, ereport, errcode(), errmsg(), ERROR, format_type_be(), GETSTRUCT, HeapTupleGetOid, CollateClause::location, LookupCollation(), OidIsValid, parser_errposition(), CreateStmtContext::pstate, ReleaseSysCache(), ColumnDef::typeName, and typenameType().

Referenced by transformColumnDefinition().

3375 {
3376  /*
3377  * All we really need to do here is verify that the type is valid,
3378  * including any collation spec that might be present.
3379  */
3380  Type ctype = typenameType(cxt->pstate, column->typeName, NULL);
3381 
3382  if (column->collClause)
3383  {
3384  Form_pg_type typtup = (Form_pg_type) GETSTRUCT(ctype);
3385 
3386  LookupCollation(cxt->pstate,
3387  column->collClause->collname,
3388  column->collClause->location);
3389  /* Complain if COLLATE is applied to an uncollatable type */
3390  if (!OidIsValid(typtup->typcollation))
3391  ereport(ERROR,
3392  (errcode(ERRCODE_DATATYPE_MISMATCH),
3393  errmsg("collations are not supported by type %s",
3396  column->collClause->location)));
3397  }
3398 
3399  ReleaseSysCache(ctype);
3400 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:668
Type typenameType(ParseState *pstate, const TypeName *typeName, int32 *typmod_p)
Definition: parse_type.c:247
int errcode(int sqlerrcode)
Definition: elog.c:575
char * format_type_be(Oid type_oid)
Definition: format_type.c:328
#define OidIsValid(objectId)
Definition: c.h:605
ParseState * pstate
Definition: parse_utilcmd.c:76
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:122
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
Oid LookupCollation(ParseState *pstate, List *collnames, int location)
Definition: parse_type.c:496
FormData_pg_type * Form_pg_type
Definition: pg_type.h:247
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
TypeName * typeName
Definition: parsenodes.h:648
CollateClause * collClause
Definition: parsenodes.h:660
List * collname
Definition: parsenodes.h:311
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:707

◆ transformConstraintAttrs()

static void transformConstraintAttrs ( CreateStmtContext cxt,
List constraintList 
)
static

Definition at line 3259 of file parse_utilcmd.c.

References CONSTR_ATTR_DEFERRABLE, CONSTR_ATTR_DEFERRED, CONSTR_ATTR_IMMEDIATE, CONSTR_ATTR_NOT_DEFERRABLE, Constraint::contype, Constraint::deferrable, elog, ereport, errcode(), errmsg(), ERROR, Constraint::initdeferred, IsA, lfirst, Constraint::location, nodeTag, parser_errposition(), CreateStmtContext::pstate, and SUPPORTS_ATTRS.

Referenced by transformColumnDefinition().

3260 {
3261  Constraint *lastprimarycon = NULL;
3262  bool saw_deferrability = false;
3263  bool saw_initially = false;
3264  ListCell *clist;
3265 
3266 #define SUPPORTS_ATTRS(node) \
3267  ((node) != NULL && \
3268  ((node)->contype == CONSTR_PRIMARY || \
3269  (node)->contype == CONSTR_UNIQUE || \
3270  (node)->contype == CONSTR_EXCLUSION || \
3271  (node)->contype == CONSTR_FOREIGN))
3272 
3273  foreach(clist, constraintList)
3274  {
3275  Constraint *con = (Constraint *) lfirst(clist);
3276 
3277  if (!IsA(con, Constraint))
3278  elog(ERROR, "unrecognized node type: %d",
3279  (int) nodeTag(con));
3280  switch (con->contype)
3281  {
3283  if (!SUPPORTS_ATTRS(lastprimarycon))
3284  ereport(ERROR,
3285  (errcode(ERRCODE_SYNTAX_ERROR),
3286  errmsg("misplaced DEFERRABLE clause"),
3287  parser_errposition(cxt->pstate, con->location)));
3288  if (saw_deferrability)
3289  ereport(ERROR,
3290  (errcode(ERRCODE_SYNTAX_ERROR),
3291  errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed"),
3292  parser_errposition(cxt->pstate, con->location)));
3293  saw_deferrability = true;
3294  lastprimarycon->deferrable = true;
3295  break;
3296 
3298  if (!SUPPORTS_ATTRS(lastprimarycon))
3299  ereport(ERROR,
3300  (errcode(ERRCODE_SYNTAX_ERROR),
3301  errmsg("misplaced NOT DEFERRABLE clause"),
3302  parser_errposition(cxt->pstate, con->location)));
3303  if (saw_deferrability)
3304  ereport(ERROR,
3305  (errcode(ERRCODE_SYNTAX_ERROR),
3306  errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed"),
3307  parser_errposition(cxt->pstate, con->location)));
3308  saw_deferrability = true;
3309  lastprimarycon->deferrable = false;
3310  if (saw_initially &&
3311  lastprimarycon->initdeferred)
3312  ereport(ERROR,
3313  (errcode(ERRCODE_SYNTAX_ERROR),
3314  errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
3315  parser_errposition(cxt->pstate, con->location)));
3316  break;
3317 
3318  case CONSTR_ATTR_DEFERRED:
3319  if (!SUPPORTS_ATTRS(lastprimarycon))
3320  ereport(ERROR,
3321  (errcode(ERRCODE_SYNTAX_ERROR),
3322  errmsg("misplaced INITIALLY DEFERRED clause"),
3323  parser_errposition(cxt->pstate, con->location)));
3324  if (saw_initially)
3325  ereport(ERROR,
3326  (errcode(ERRCODE_SYNTAX_ERROR),
3327  errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed"),
3328  parser_errposition(cxt->pstate, con->location)));
3329  saw_initially = true;
3330  lastprimarycon->initdeferred = true;
3331 
3332  /*
3333  * If only INITIALLY DEFERRED appears, assume DEFERRABLE
3334  */
3335  if (!saw_deferrability)
3336  lastprimarycon->deferrable = true;
3337  else if (!lastprimarycon->deferrable)
3338  ereport(ERROR,
3339  (errcode(ERRCODE_SYNTAX_ERROR),
3340  errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
3341  parser_errposition(cxt->pstate, con->location)));
3342  break;
3343 
3344  case CONSTR_ATTR_IMMEDIATE:
3345  if (!SUPPORTS_ATTRS(lastprimarycon))
3346  ereport(ERROR,
3347  (errcode(ERRCODE_SYNTAX_ERROR),
3348  errmsg("misplaced INITIALLY IMMEDIATE clause"),
3349  parser_errposition(cxt->pstate, con->location)));
3350  if (saw_initially)
3351  ereport(ERROR,
3352  (errcode(ERRCODE_SYNTAX_ERROR),
3353  errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed"),
3354  parser_errposition(cxt->pstate, con->location)));
3355  saw_initially = true;
3356  lastprimarycon->initdeferred = false;
3357  break;
3358 
3359  default:
3360  /* Otherwise it's not an attribute */
3361  lastprimarycon = con;
3362  /* reset flags for new primary node */
3363  saw_deferrability = false;
3364  saw_initially = false;
3365  break;
3366  }
3367  }
3368 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:568
int errcode(int sqlerrcode)
Definition: elog.c:575
bool initdeferred
Definition: parsenodes.h:2097
ParseState * pstate
Definition: parse_utilcmd.c:76
#define ERROR
Definition: elog.h:43
bool deferrable
Definition: parsenodes.h:2096
#define ereport(elevel, rest)
Definition: elog.h:122
#define lfirst(lc)
Definition: pg_list.h:106
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
#define nodeTag(nodeptr)
Definition: nodes.h:522
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define SUPPORTS_ATTRS(node)
ConstrType contype
Definition: parsenodes.h:2092
#define elog
Definition: elog.h:219

◆ 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)

◆ transformExtendedStatistics()

static void transformExtendedStatistics ( CreateStmtContext cxt)
static

Definition at line 2386 of file parse_utilcmd.c.

References CreateStmtContext::alist, CreateStmtContext::extstats, and list_concat().

Referenced by transformAlterTableStmt(), and transformCreateStmt().

2387 {
2388  cxt->alist = list_concat(cxt->alist, cxt->extstats);
2389 }
List * list_concat(List *list1, List *list2)
Definition: list.c:321

◆ transformFKConstraints()

static void transformFKConstraints ( CreateStmtContext cxt,
bool  skipValidation,
bool  isAddConstraint 
)
static

Definition at line 2430 of file parse_utilcmd.c.

References CreateStmtContext::alist, AT_ProcessedConstraint, AlterTableStmt::cmds, AlterTableCmd::def, CreateStmtContext::fkconstraints, Constraint::initially_valid, lappend(), lfirst, makeNode, AlterTableCmd::name, NIL, OBJECT_TABLE, CreateStmtContext::relation, AlterTableStmt::relation, AlterTableStmt::relkind, Constraint::skip_validation, and AlterTableCmd::subtype.

Referenced by transformAlterTableStmt(), and transformCreateStmt().

2432 {
2433  ListCell *fkclist;
2434 
2435  if (cxt->fkconstraints == NIL)
2436  return;
2437 
2438  /*
2439  * If CREATE TABLE or adding a column with NULL default, we can safely
2440  * skip validation of FK constraints, and nonetheless mark them valid.
2441  * (This will override any user-supplied NOT VALID flag.)
2442  */
2443  if (skipValidation)
2444  {
2445  foreach(fkclist, cxt->fkconstraints)
2446  {
2447  Constraint *constraint = (Constraint *) lfirst(fkclist);
2448 
2449  constraint->skip_validation = true;
2450  constraint->initially_valid = true;
2451  }
2452  }
2453 
2454  /*
2455  * For CREATE TABLE or ALTER TABLE ADD COLUMN, gin up an ALTER TABLE ADD
2456  * CONSTRAINT command to execute after the basic command is complete. (If
2457  * called from ADD CONSTRAINT, that routine will add the FK constraints to
2458  * its own subcommand list.)
2459  *
2460  * Note: the ADD CONSTRAINT command must also execute after any index
2461  * creation commands. Thus, this should run after
2462  * transformIndexConstraints, so that the CREATE INDEX commands are
2463  * already in cxt->alist.
2464  */
2465  if (!isAddConstraint)
2466  {
2467  AlterTableStmt *alterstmt = makeNode(AlterTableStmt);
2468 
2469  alterstmt->relation = cxt->relation;
2470  alterstmt->cmds = NIL;
2471  alterstmt->relkind = OBJECT_TABLE;
2472 
2473  foreach(fkclist, cxt->fkconstraints)
2474  {
2475  Constraint *constraint = (Constraint *) lfirst(fkclist);
2476  AlterTableCmd *altercmd = makeNode(AlterTableCmd);
2477 
2478  altercmd->subtype = AT_ProcessedConstraint;
2479  altercmd->name = NULL;
2480  altercmd->def = (Node *) constraint;
2481  alterstmt->cmds = lappend(alterstmt->cmds, altercmd);
2482  }
2483 
2484  cxt->alist = lappend(cxt->alist, alterstmt);
2485  }
2486 }
#define NIL
Definition: pg_list.h:69
Definition: nodes.h:517
AlterTableType subtype
Definition: parsenodes.h:1806
RangeVar * relation
Definition: parse_utilcmd.c:78
ObjectType relkind
Definition: parsenodes.h:1720
List * lappend(List *list, void *datum)
Definition: list.c:128
bool initially_valid
Definition: parsenodes.h:2136
#define makeNode(_type_)
Definition: nodes.h:565
#define lfirst(lc)
Definition: pg_list.h:106
RangeVar * relation
Definition: parsenodes.h:1718
bool skip_validation
Definition: parsenodes.h:2135

◆ transformIndexConstraint()

static IndexStmt * transformIndexConstraint ( Constraint constraint,
CreateStmtContext cxt 
)
static

Definition at line 1897 of file parse_utilcmd.c.

References Constraint::access_method, IndexStmt::accessMethod, AccessShareLock, Assert, attname, attnum, castNode, IndexElem::collation, ColumnDef::colname, CreateStmtContext::columns, IndexStmt::concurrent, Constraint::conname, CONSTR_EXCLUSION, CONSTR_PRIMARY, CONSTR_UNIQUE, Constraint::contype, DatumGetPointer, DEFAULT_INDEX_TYPE, Constraint::deferrable, IndexStmt::deferrable, ereport, errcode(), errdetail(), errmsg(), ERROR, IndexStmt::excludeOpNames, Constraint::exclusions, IndexElem::expr, get_index_am_oid(), get_index_constraint(), get_relname_relid(), GetDefaultOpClass(), CreateStmtContext::hasoids, heap_close, heap_openrv(), i, IndexStmt::idxcomment, IndexStmt::idxname, IndexStmt::if_not_exists, Constraint::including, index_open(), IndexElem::indexcolname, IndexStmt::indexIncludingParams, IndexIsValid, Constraint::indexname, IndexStmt::indexOid, IndexStmt::indexParams, INDEXRELID, Constraint::indexspace, CreateStmtContext::inhRelations, Constraint::initdeferred, IndexStmt::initdeferred, InvalidOid, ColumnDef::is_not_null, CreateStmtContext::isalter, IndexStmt::isconstraint, Constraint::keys, lappend(), lfirst, lfirst_node, linitial_node, list_length(), Constraint::location, lsecond_node, makeNode, makeString(), IndexElem::name, NameStr, tupleDesc::natts, NIL, NoLock, IndexElem::nulls_ordering, OidIsValid, IndexStmt::oldNode, IndexElem::opclass, Constraint::options, IndexStmt::options, IndexElem::ordering, parser_errposition(), CreateStmtContext::pkey, IndexStmt::primary, CreateStmtContext::pstate, pstrdup(), RelationData::rd_att, RelationData::rd_index, RelationData::rd_indextuple, RelationData::rd_indoption, RelationData::rd_rel, CreateStmtContext::rel, CreateStmtContext::relation, IndexStmt::relation, relation_close(), RelationGetIndexExpressions(), RelationGetIndexPredicate(), RelationGetNamespace, RelationGetRelationName, RelationGetRelid, RangeVar::relname, SORTBY_DEFAULT, SORTBY_NULLS_DEFAULT, strVal, SysCacheGetAttr(), SystemAttributeByName(), SystemAttributeDefinition(), IndexStmt::tableSpace, IndexStmt::transformed, TupleDescAttr, IndexStmt::unique, oidvector::values, Constraint::where_clause, and IndexStmt::whereClause.

Referenced by transformIndexConstraints().

1898 {
1899  IndexStmt *index;
1900  ListCell *lc;
1901 
1902  index = makeNode(IndexStmt);
1903 
1904  index->unique = (constraint->contype != CONSTR_EXCLUSION);
1905  index->primary = (constraint->contype == CONSTR_PRIMARY);
1906  if (index->primary)
1907  {
1908  if (cxt->pkey != NULL)
1909  ereport(ERROR,
1910  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1911  errmsg("multiple primary keys for table \"%s\" are not allowed",
1912  cxt->relation->relname),
1913  parser_errposition(cxt->pstate, constraint->location)));
1914  cxt->pkey = index;
1915 
1916  /*
1917  * In ALTER TABLE case, a primary index might already exist, but
1918  * DefineIndex will check for it.
1919  */
1920  }
1921  index->isconstraint = true;
1922  index->deferrable = constraint->deferrable;
1923  index->initdeferred = constraint->initdeferred;
1924 
1925  if (constraint->conname != NULL)
1926  index->idxname = pstrdup(constraint->conname);
1927  else
1928  index->idxname = NULL; /* DefineIndex will choose name */
1929 
1930  index->relation = cxt->relation;
1931  index->accessMethod = constraint->access_method ? constraint->access_method : DEFAULT_INDEX_TYPE;
1932  index->options = constraint->options;
1933  index->tableSpace = constraint->indexspace;
1934  index->whereClause = constraint->where_clause;
1935  index->indexParams = NIL;
1936  index->indexIncludingParams = NIL;
1937  index->excludeOpNames = NIL;
1938  index->idxcomment = NULL;
1939  index->indexOid = InvalidOid;
1940  index->oldNode = InvalidOid;
1941  index->transformed = false;
1942  index->concurrent = false;
1943  index->if_not_exists = false;
1944 
1945  /*
1946  * If it's ALTER TABLE ADD CONSTRAINT USING INDEX, look up the index and
1947  * verify it's usable, then extract the implied column name list. (We
1948  * will not actually need the column name list at runtime, but we need it
1949  * now to check for duplicate column entries below.)
1950  */
1951  if (constraint->indexname != NULL)
1952  {
1953  char *index_name = constraint->indexname;
1954  Relation heap_rel = cxt->rel;
1955  Oid index_oid;
1956  Relation index_rel;
1957  Form_pg_index index_form;
1958  oidvector *indclass;
1959  Datum indclassDatum;
1960  bool isnull;
1961  int i;
1962 
1963  /* Grammar should not allow this with explicit column list */
1964  Assert(constraint->keys == NIL);
1965 
1966  /* Grammar should only allow PRIMARY and UNIQUE constraints */
1967  Assert(constraint->contype == CONSTR_PRIMARY ||
1968  constraint->contype == CONSTR_UNIQUE);
1969 
1970  /* Must be ALTER, not CREATE, but grammar doesn't enforce that */
1971  if (!cxt->isalter)
1972  ereport(ERROR,
1973  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1974  errmsg("cannot use an existing index in CREATE TABLE"),
1975  parser_errposition(cxt->pstate, constraint->location)));
1976 
1977  /* Look for the index in the same schema as the table */
1978  index_oid = get_relname_relid(index_name, RelationGetNamespace(heap_rel));
1979 
1980  if (!OidIsValid(index_oid))
1981  ereport(ERROR,
1982  (errcode(ERRCODE_UNDEFINED_OBJECT),
1983  errmsg("index \"%s\" does not exist", index_name),
1984  parser_errposition(cxt->pstate, constraint->location)));
1985 
1986  /* Open the index (this will throw an error if it is not an index) */
1987  index_rel = index_open(index_oid, AccessShareLock);
1988  index_form = index_rel->rd_index;
1989 
1990  /* Check that it does not have an associated constraint already */
1991  if (OidIsValid(get_index_constraint(index_oid)))
1992  ereport(ERROR,
1993  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1994  errmsg("index \"%s\" is already associated with a constraint",
1995  index_name),
1996  parser_errposition(cxt->pstate, constraint->location)));
1997 
1998  /* Perform validity checks on the index */
1999  if (index_form->indrelid != RelationGetRelid(heap_rel))
2000  ereport(ERROR,
2001  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2002  errmsg("index \"%s\" does not belong to table \"%s\"",
2003  index_name, RelationGetRelationName(heap_rel)),
2004  parser_errposition(cxt->pstate, constraint->location)));
2005 
2006  if (!IndexIsValid(index_form))
2007  ereport(ERROR,
2008  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2009  errmsg("index \"%s\" is not valid", index_name),
2010  parser_errposition(cxt->pstate, constraint->location)));
2011 
2012  if (!index_form->indisunique)
2013  ereport(ERROR,
2014  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2015  errmsg("\"%s\" is not a unique index", index_name),
2016  errdetail("Cannot create a primary key or unique constraint using such an index."),
2017  parser_errposition(cxt->pstate, constraint->location)));
2018 
2019  if (RelationGetIndexExpressions(index_rel) != NIL)
2020  ereport(ERROR,
2021  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2022  errmsg("index \"%s\" contains expressions", index_name),
2023  errdetail("Cannot create a primary key or unique constraint using such an index."),
2024  parser_errposition(cxt->pstate, constraint->location)));
2025 
2026  if (RelationGetIndexPredicate(index_rel) != NIL)
2027  ereport(ERROR,
2028  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2029  errmsg("\"%s\" is a partial index", index_name),
2030  errdetail("Cannot create a primary key or unique constraint using such an index."),
2031  parser_errposition(cxt->pstate, constraint->location)));
2032 
2033  /*
2034  * It's probably unsafe to change a deferred index to non-deferred. (A
2035  * non-constraint index couldn't be deferred anyway, so this case
2036  * should never occur; no need to sweat, but let's check it.)
2037  */
2038  if (!index_form->indimmediate && !constraint->deferrable)
2039  ereport(ERROR,
2040  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2041  errmsg("\"%s\" is a deferrable index", index_name),
2042  errdetail("Cannot create a non-deferrable constraint using a deferrable index."),
2043  parser_errposition(cxt->pstate, constraint->location)));
2044 
2045  /*
2046  * Insist on it being a btree. That's the only kind that supports
2047  * uniqueness at the moment anyway; but we must have an index that
2048  * exactly matches what you'd get from plain ADD CONSTRAINT syntax,
2049  * else dump and reload will produce a different index (breaking
2050  * pg_upgrade in particular).
2051  */
2052  if (index_rel->rd_rel->relam != get_index_am_oid(DEFAULT_INDEX_TYPE, false))
2053  ereport(ERROR,
2054  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2055  errmsg("index \"%s\" is not a btree", index_name),
2056  parser_errposition(cxt->pstate, constraint->location)));
2057 
2058  /* Must get indclass the hard way */
2059  indclassDatum = SysCacheGetAttr(INDEXRELID, index_rel->rd_indextuple,
2060  Anum_pg_index_indclass, &isnull);
2061  Assert(!isnull);
2062  indclass = (oidvector *) DatumGetPointer(indclassDatum);
2063 
2064  for (i = 0; i < index_form->indnatts; i++)
2065  {
2066  int16 attnum = index_form->indkey.values[i];
2067  Form_pg_attribute attform;
2068  char *attname;
2069  Oid defopclass;
2070 
2071  /*
2072  * We shouldn't see attnum == 0 here, since we already rejected
2073  * expression indexes. If we do, SystemAttributeDefinition will
2074  * throw an error.
2075  */
2076  if (attnum > 0)
2077  {
2078  Assert(attnum <= heap_rel->rd_att->natts);
2079  attform = TupleDescAttr(heap_rel->rd_att, attnum - 1);
2080  }
2081  else
2082  attform = SystemAttributeDefinition(attnum,
2083  heap_rel->rd_rel->relhasoids);
2084  attname = pstrdup(NameStr(attform->attname));
2085 
2086  if (i < index_form->indnkeyatts)
2087  {
2088  /*
2089  * Insist on default opclass and sort options. While the
2090  * index would still work as a constraint with non-default
2091  * settings, it might not provide exactly the same uniqueness
2092  * semantics as you'd get from a normally-created constraint;
2093  * and there's also the dump/reload problem mentioned above.
2094  */
2095  defopclass = GetDefaultOpClass(attform->atttypid,
2096  index_rel->rd_rel->relam);
2097  if (indclass->values[i] != defopclass ||
2098  index_rel->rd_indoption[i] != 0)
2099  ereport(ERROR,
2100  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2101  errmsg("index \"%s\" does not have default sorting behavior", index_name),
2102  errdetail("Cannot create a primary key or unique constraint using such an index."),
2103  parser_errposition(cxt->pstate, constraint->location)));
2104 
2105  constraint->keys = lappend(constraint->keys, makeString(attname));
2106  }
2107  else
2108  constraint->including = lappend(constraint->including, makeString(attname));
2109  }
2110 
2111  /* Close the index relation but keep the lock */
2112  relation_close(index_rel, NoLock);
2113 
2114  index->indexOid = index_oid;
2115  }
2116 
2117  /*
2118  * If it's an EXCLUDE constraint, the grammar returns a list of pairs of
2119  * IndexElems and operator names. We have to break that apart into
2120  * separate lists.
2121  */
2122  if (constraint->contype == CONSTR_EXCLUSION)
2123  {
2124  foreach(lc, constraint->exclusions)
2125  {
2126  List *pair = (List *) lfirst(lc);
2127  IndexElem *elem;
2128  List *opname;
2129 
2130  Assert(list_length(pair) == 2);
2131  elem = linitial_node(IndexElem, pair);
2132  opname = lsecond_node(List, pair);
2133 
2134  index->indexParams = lappend(index->indexParams, elem);
2135  index->excludeOpNames = lappend(index->excludeOpNames, opname);
2136  }
2137  }
2138 
2139  /*
2140  * For UNIQUE and PRIMARY KEY, we just have a list of column names.
2141  *
2142  * Make sure referenced keys exist. If we are making a PRIMARY KEY index,
2143  * also make sure they are NOT NULL, if possible. (Although we could leave
2144  * it to DefineIndex to mark the columns NOT NULL, it's more efficient to
2145  * get it right the first time.)
2146  */
2147  else
2148  {
2149  foreach(lc, constraint->keys)
2150  {
2151  char *key = strVal(lfirst(lc));
2152  bool found = false;
2153  ColumnDef *column = NULL;
2154  ListCell *columns;
2155  IndexElem *iparam;
2156 
2157  /* Make sure referenced column exist. */
2158  foreach(columns, cxt->columns)
2159  {
2160  column = castNode(ColumnDef, lfirst(columns));
2161  if (strcmp(column->colname, key) == 0)
2162  {
2163  found = true;
2164  break;
2165  }
2166  }
2167  if (found)
2168  {
2169  /* found column in the new table; force it to be NOT NULL */
2170  if (constraint->contype == CONSTR_PRIMARY)
2171  column->is_not_null = true;
2172  }
2173  else if (SystemAttributeByName(key, cxt->hasoids) != NULL)
2174  {
2175  /*
2176  * column will be a system column in the new table, so accept
2177  * it. System columns can't ever be null, so no need to worry
2178  * about PRIMARY/NOT NULL constraint.
2179  */
2180  found = true;
2181  }
2182  else if (cxt->inhRelations)
2183  {
2184  /* try inherited tables */
2185  ListCell *inher;
2186 
2187  foreach(inher, cxt->inhRelations)
2188  {
2189  RangeVar *inh = castNode(RangeVar, lfirst(inher));
2190  Relation rel;
2191  int count;
2192 
2193  rel = heap_openrv(inh, AccessShareLock);
2194  /* check user requested inheritance from valid relkind */
2195  if (rel->rd_rel->relkind != RELKIND_RELATION &&
2196  rel->rd_rel->relkind != RELKIND_FOREIGN_TABLE &&
2197  rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
2198  ereport(ERROR,
2199  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2200  errmsg("inherited relation \"%s\" is not a table or foreign table",
2201  inh->relname)));
2202  for (count = 0; count < rel->rd_att->natts; count++)
2203  {
2204  Form_pg_attribute inhattr = TupleDescAttr(rel->rd_att,
2205  count);
2206  char *inhname = NameStr(inhattr->attname);
2207 
2208  if (inhattr->attisdropped)
2209  continue;
2210  if (strcmp(key, inhname) == 0)
2211  {
2212  found = true;
2213 
2214  /*
2215  * We currently have no easy way to force an
2216  * inherited column to be NOT NULL at creation, if
2217  * its parent wasn't so already. We leave it to
2218  * DefineIndex to fix things up in this case.
2219  */
2220  break;
2221  }
2222  }
2223  heap_close(rel, NoLock);
2224  if (found)
2225  break;
2226  }
2227  }
2228 
2229  /*
2230  * In the ALTER TABLE case, don't complain about index keys not
2231  * created in the command; they may well exist already.
2232  * DefineIndex will complain about them if not, and will also take
2233  * care of marking them NOT NULL.
2234  */
2235  if (!found && !cxt->isalter)
2236  ereport(ERROR,
2237  (errcode(ERRCODE_UNDEFINED_COLUMN),
2238  errmsg("column \"%s\" named in key does not exist", key),
2239  parser_errposition(cxt->pstate, constraint->location)));
2240 
2241  /* Check for PRIMARY KEY(foo, foo) */
2242  foreach(columns, index->indexParams)
2243  {
2244  iparam = (IndexElem *) lfirst(columns);
2245  if (iparam->name && strcmp(key, iparam->name) == 0)
2246  {
2247  if (index->primary)
2248  ereport(ERROR,
2249  (errcode(ERRCODE_DUPLICATE_COLUMN),
2250  errmsg("column \"%s\" appears twice in primary key constraint",
2251  key),
2252  parser_errposition(cxt->pstate, constraint->location)));
2253  else
2254  ereport(ERROR,
2255  (errcode(ERRCODE_DUPLICATE_COLUMN),
2256  errmsg("column \"%s\" appears twice in unique constraint",
2257  key),
2258  parser_errposition(cxt->pstate, constraint->location)));
2259  }
2260  }
2261 
2262  /* OK, add it to the index definition */
2263  iparam = makeNode(IndexElem);
2264  iparam->name = pstrdup(key);
2265  iparam->expr = NULL;
2266  iparam->indexcolname = NULL;
2267  iparam->collation = NIL;
2268  iparam->opclass = NIL;
2269  iparam->ordering = SORTBY_DEFAULT;
2271  index->indexParams = lappend(index->indexParams, iparam);
2272  }
2273  }
2274 
2275  /* Add included columns to index definition */
2276  foreach(lc, constraint->including)
2277  {
2278  char *key = strVal(lfirst(lc));
2279  bool found = false;
2280  ColumnDef *column = NULL;
2281  ListCell *columns;
2282  IndexElem *iparam;
2283 
2284  foreach(columns, cxt->columns)
2285  {
2286  column = lfirst_node(ColumnDef, columns);
2287  if (strcmp(column->colname, key) == 0)
2288  {
2289  found = true;
2290  break;
2291  }
2292  }
2293 
2294  if (!found)
2295  {
2296  if (SystemAttributeByName(key, cxt->hasoids) != NULL)
2297  {
2298  /*
2299  * column will be a system column in the new table, so accept
2300  * it. System columns can't ever be null, so no need to worry
2301  * about PRIMARY/NOT NULL constraint.
2302  */
2303  found = true;
2304  }
2305  else if (cxt->inhRelations)
2306  {
2307  /* try inherited tables */
2308  ListCell *inher;
2309 
2310  foreach(inher, cxt->inhRelations)
2311  {
2312  RangeVar *inh = lfirst_node(RangeVar, inher);
2313  Relation rel;
2314  int count;
2315 
2316  rel = heap_openrv(inh, AccessShareLock);
2317  /* check user requested inheritance from valid relkind */
2318  if (rel->rd_rel->relkind != RELKIND_RELATION &&
2319  rel->rd_rel->relkind != RELKIND_FOREIGN_TABLE &&
2320  rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
2321  ereport(ERROR,
2322  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2323  errmsg("inherited relation \"%s\" is not a table or foreign table",
2324  inh->relname)));
2325  for (count = 0; count < rel->rd_att->natts; count++)
2326  {
2327  Form_pg_attribute inhattr = TupleDescAttr(rel->rd_att,
2328  count);
2329  char *inhname = NameStr(inhattr->attname);
2330 
2331  if (inhattr->attisdropped)
2332  continue;
2333  if (strcmp(key, inhname) == 0)
2334  {
2335  found = true;
2336 
2337  /*
2338  * We currently have no easy way to force an
2339  * inherited column to be NOT NULL at creation, if
2340  * its parent wasn't so already. We leave it to
2341  * DefineIndex to fix things up in this case.
2342  */
2343  break;
2344  }
2345  }
2346  heap_close(rel, NoLock);
2347  if (found)
2348  break;
2349  }
2350  }
2351  }
2352 
2353  /*
2354  * In the ALTER TABLE case, don't complain about index keys not
2355  * created in the command; they may well exist already. DefineIndex
2356  * will complain about them if not, and will also take care of marking
2357  * them NOT NULL.
2358  */
2359  if (!found && !cxt->isalter)
2360  ereport(ERROR,
2361  (errcode(ERRCODE_UNDEFINED_COLUMN),
2362  errmsg("column \"%s\" named in key does not exist", key),
2363  parser_errposition(cxt->pstate, constraint->location)));
2364 
2365  /* OK, add it to the index definition */
2366  iparam = makeNode(IndexElem);
2367  iparam->name = pstrdup(key);
2368  iparam->expr = NULL;
2369  iparam->indexcolname = NULL;
2370  iparam->collation = NIL;
2371  iparam->opclass = NIL;
2372  index->indexIncludingParams = lappend(index->indexIncludingParams, iparam);
2373  }
2374 
2375  return index;
2376 }
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
Definition: c.h:555
bool primary
Definition: parsenodes.h:2732
List * keys
Definition: parsenodes.h:2107
List * exclusions
Definition: parsenodes.h:2113
int16 * rd_indoption
Definition: rel.h:158
Oid GetDefaultOpClass(Oid type_id, Oid am_id)
Definition: indexcmds.c:1799
SortByDir ordering
Definition: parsenodes.h:704
List * options
Definition: parsenodes.h:2725
#define IndexIsValid(indexForm)
Definition: pg_index.h:85
#define castNode(_type_, nodeptr)
Definition: nodes.h:586
char * tableSpace
Definition: parsenodes.h:2721
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:93
char * pstrdup(const char *in)
Definition: mcxt.c:1161
Node * whereClause
Definition: parsenodes.h:2726
Form_pg_attribute SystemAttributeByName(const char *attname, bool relhasoids)
Definition: heap.c:217
#define AccessShareLock
Definition: lockdefs.h:36
#define strVal(v)
Definition: value.h:54
int errcode(int sqlerrcode)
Definition: elog.c:575
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: heapam.c:1270
bool initdeferred
Definition: parsenodes.h:2097
#define heap_close(r, l)
Definition: heapam.h:97
char * conname
Definition: parsenodes.h:2095
bool is_not_null
Definition: parsenodes.h:651
Form_pg_class rd_rel
Definition: rel.h:84
unsigned int Oid
Definition: postgres_ext.h:31
#define linitial_node(type, l)
Definition: pg_list.h:114
#define OidIsValid(objectId)
Definition: c.h:605
int natts
Definition: tupdesc.h:82
List * options
Definition: parsenodes.h:2116
List * RelationGetIndexPredicate(Relation relation)
Definition: relcache.c:4608
struct HeapTupleData * rd_indextuple
Definition: rel.h:133
List * indexIncludingParams
Definition: parsenodes.h:2723
Definition: type.h:89
ParseState * pstate
Definition: parse_utilcmd.c:76
char * relname
Definition: primnodes.h:69
Oid indexOid
Definition: parsenodes.h:2729
Node * expr
Definition: parsenodes.h:700
RangeVar * relation
Definition: parse_utilcmd.c:78
RangeVar * relation
Definition: parsenodes.h:2718
IndexStmt * pkey
Definition: parse_utilcmd.c:94
Form_pg_index rd_index
Definition: rel.h:131
SortByNulls nulls_ordering
Definition: parsenodes.h:705
#define ERROR
Definition: elog.h:43
NameData attname
Definition: pg_attribute.h:40
bool deferrable
Definition: parsenodes.h:2096
Oid get_relname_relid(const char *relname, Oid relnamespace)
Definition: lsyscache.c:1687
#define lfirst_node(type, lc)
Definition: pg_list.h:109
Oid get_index_am_oid(const char *amname, bool missing_ok)
Definition: amcmds.c:183
#define NoLock
Definition: lockdefs.h:34
List * RelationGetIndexExpressions(Relation relation)
Definition: relcache.c:4546
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 DEFAULT_INDEX_TYPE
Definition: index.h:21
#define RelationGetRelationName(relation)
Definition: rel.h:441
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:197
Oid get_index_constraint(Oid indexId)
Definition: pg_depend.c:689
#define ereport(elevel, rest)
Definition: elog.h:122
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
bool if_not_exists
Definition: parsenodes.h:2738
#define lsecond_node(type, l)
Definition: pg_list.h:119
uintptr_t Datum
Definition: postgres.h:367
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1368
bool unique
Definition: parsenodes.h:2731
TupleDesc rd_att
Definition: rel.h:85
char * accessMethod
Definition: parsenodes.h:2720
Relation heap_openrv(const RangeVar *relation, LOCKMODE lockmode)
Definition: heapam.c:1323
Form_pg_attribute SystemAttributeDefinition(AttrNumber attno, bool relhasoids)
Definition: heap.c:203
#define InvalidOid
Definition: postgres_ext.h:36
int16 attnum
Definition: pg_attribute.h:79
List * opclass
Definition: parsenodes.h:703
Node * where_clause
Definition: parsenodes.h:2121
#define makeNode(_type_)
Definition: nodes.h:565
#define Assert(condition)
Definition: c.h:699
#define lfirst(lc)
Definition: pg_list.h:106
List * indexParams
Definition: parsenodes.h:2722
List * excludeOpNames
Definition: parsenodes.h:2727
static int list_length(const List *l)
Definition: pg_list.h:89
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
bool initdeferred
Definition: parsenodes.h:2735
char * name
Definition: parsenodes.h:699
char * idxcomment
Definition: parsenodes.h:2728
#define DatumGetPointer(X)
Definition: postgres.h:534
bool concurrent
Definition: parsenodes.h:2737
bool isconstraint
Definition: parsenodes.h:2733
char * indexname
Definition: parsenodes.h:2117
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
#define NameStr(name)
Definition: c.h:576
ConstrType contype
Definition: parsenodes.h:2092
List * collation
Definition: parsenodes.h:702
char * colname
Definition: parsenodes.h:647
List * including
Definition: parsenodes.h:2109
Definition: pg_list.h:45
#define RelationGetRelid(relation)
Definition: rel.h:407
char * access_method
Definition: parsenodes.h:2120
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:150
char * indexspace
Definition: parsenodes.h:2118
#define RelationGetNamespace(relation)
Definition: rel.h:448

◆ transformIndexConstraints()

static void transformIndexConstraints ( CreateStmtContext cxt)
static

Definition at line 1789 of file parse_utilcmd.c.

References IndexStmt::accessMethod, CreateStmtContext::alist, Assert, CONSTR_EXCLUSION, CONSTR_PRIMARY, CONSTR_UNIQUE, Constraint::contype, IndexStmt::deferrable, equal(), ereport, errcode(), errmsg(), ERROR, IndexStmt::excludeOpNames, IndexStmt::idxname, IndexStmt::indexIncludingParams, IndexStmt::indexParams, CreateStmtContext::inh_indexes, IndexStmt::initdeferred, CreateStmtContext::ixconstraints, lappend(), lfirst, lfirst_node, list_make1, NIL, CreateStmtContext::pkey, IndexStmt::primary, CreateStmtContext::relation, RangeVar::relname, transformIndexConstraint(), IndexStmt::unique, and IndexStmt::whereClause.

Referenced by transformAlterTableStmt(), and transformCreateStmt().

1790 {
1791  IndexStmt *index;
1792  List *indexlist = NIL;
1793  ListCell *lc;
1794 
1795  /*
1796  * Run through the constraints that need to generate an index. For PRIMARY
1797  * KEY, mark each column as NOT NULL and create an index. For UNIQUE or
1798  * EXCLUDE, create an index as for PRIMARY KEY, but do not insist on NOT
1799  * NULL.
1800  */
1801  foreach(lc, cxt->ixconstraints)
1802  {
1803  Constraint *constraint = lfirst_node(Constraint, lc);
1804 
1805  Assert(constraint->contype == CONSTR_PRIMARY ||
1806  constraint->contype == CONSTR_UNIQUE ||
1807  constraint->contype == CONSTR_EXCLUSION);
1808 
1809  index = transformIndexConstraint(constraint, cxt);
1810 
1811  indexlist = lappend(indexlist, index);
1812  }
1813 
1814  /* Add in any indexes defined by LIKE ... INCLUDING INDEXES */
1815  foreach(lc, cxt->inh_indexes)
1816  {
1817  index = (IndexStmt *) lfirst(lc);
1818 
1819  if (index->primary)
1820  {
1821  if (cxt->pkey != NULL)
1822  ereport(ERROR,
1823  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1824  errmsg("multiple primary keys for table \"%s\" are not allowed",
1825  cxt->relation->relname)));
1826  cxt->pkey = index;
1827  }
1828 
1829  indexlist = lappend(indexlist, index);
1830  }
1831 
1832  /*
1833  * Scan the index list and remove any redundant index specifications. This
1834  * can happen if, for instance, the user writes UNIQUE PRIMARY KEY. A
1835  * strict reading of SQL would suggest raising an error instead, but that
1836  * strikes me as too anal-retentive. - tgl 2001-02-14
1837  *
1838  * XXX in ALTER TABLE case, it'd be nice to look for duplicate
1839  * pre-existing indexes, too.
1840  */
1841  Assert(cxt->alist == NIL);
1842  if (cxt->pkey != NULL)
1843  {
1844  /* Make sure we keep the PKEY index in preference to others... */
1845  cxt->alist = list_make1(cxt->pkey);
1846  }
1847 
1848  foreach(lc, indexlist)
1849  {
1850  bool keep = true;
1851  ListCell *k;
1852 
1853  index = lfirst(lc);
1854 
1855  /* if it's pkey, it's already in cxt->alist */
1856  if (index == cxt->pkey)
1857  continue;
1858 
1859  foreach(k, cxt->alist)
1860  {
1861  IndexStmt *priorindex = lfirst(k);
1862 
1863  if (equal(index->indexParams, priorindex->indexParams) &&
1864  equal(index->indexIncludingParams, priorindex->indexIncludingParams) &&
1865  equal(index->whereClause, priorindex->whereClause) &&
1866  equal(index->excludeOpNames, priorindex->excludeOpNames) &&
1867  strcmp(index->accessMethod, priorindex->accessMethod) == 0 &&
1868  index->deferrable == priorindex->deferrable &&
1869  index->initdeferred == priorindex->initdeferred)
1870  {
1871  priorindex->unique |= index->unique;
1872 
1873  /*
1874  * If the prior index is as yet unnamed, and this one is
1875  * named, then transfer the name to the prior index. This
1876  * ensures that if we have named and unnamed constraints,
1877  * we'll use (at least one of) the names for the index.
1878  */
1879  if (priorindex->idxname == NULL)
1880  priorindex->idxname = index->idxname;
1881  keep = false;
1882  break;
1883  }
1884  }
1885 
1886  if (keep)
1887  cxt->alist = lappend(cxt->alist, index);
1888  }
1889 }
bool deferrable
Definition: parsenodes.h:2734
#define NIL
Definition: pg_list.h:69
bool primary
Definition: parsenodes.h:2732
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:2986
Node * whereClause
Definition: parsenodes.h:2726
int errcode(int sqlerrcode)
Definition: elog.c:575
List * indexIncludingParams
Definition: parsenodes.h:2723
Definition: type.h:89
#define list_make1(x1)
Definition: pg_list.h:139
char * relname
Definition: primnodes.h:69
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
#define ereport(elevel, rest)
Definition: elog.h:122
List * lappend(List *list, void *datum)
Definition: list.c:128
char * idxname
Definition: parsenodes.h:2717
static IndexStmt * transformIndexConstraint(Constraint *constraint, CreateStmtContext *cxt)
bool unique
Definition: parsenodes.h:2731
char * accessMethod
Definition: parsenodes.h:2720
#define Assert(condition)
Definition: c.h:699
#define lfirst(lc)
Definition: pg_list.h:106
List * indexParams
Definition: parsenodes.h:2722
List * excludeOpNames
Definition: parsenodes.h:2727
bool initdeferred
Definition: parsenodes.h:2735
int errmsg(const char *fmt,...)
Definition: elog.c:797
ConstrType contype
Definition: parsenodes.h:2092
Definition: pg_list.h:45

◆ 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

◆ transformOfType()

static void transformOfType ( CreateStmtContext cxt,
TypeName ofTypename 
)
static

Definition at line 1237 of file parse_utilcmd.c.

References AssertArg, check_of_type(), ColumnDef::collClause, ColumnDef::collOid, ColumnDef::colname, CreateStmtContext::columns, ColumnDef::constraints, ColumnDef::cooked_default, DecrTupleDescRefCount(), HeapTupleGetOid, i, ColumnDef::inhcount, ColumnDef::is_from_parent, ColumnDef::is_from_type, ColumnDef::is_local, ColumnDef::is_not_null, lappend(), ColumnDef::location, lookup_rowtype_tupdesc(), makeNode, makeTypeNameFromOid(), NameStr, tupleDesc::natts, NIL, pstrdup(), ColumnDef::raw_default, ReleaseSysCache(), ColumnDef::storage, TupleDescAttr, ColumnDef::typeName, typenameType(), and TypeName::typeOid.

Referenced by transformCreateStmt().

1238 {
1239  HeapTuple tuple;
1240  TupleDesc tupdesc;
1241  int i;
1242  Oid ofTypeId;
1243 
1244  AssertArg(ofTypename);
1245 
1246  tuple = typenameType(NULL, ofTypename, NULL);
1247  check_of_type(tuple);
1248  ofTypeId = HeapTupleGetOid(tuple);
1249  ofTypename->typeOid = ofTypeId; /* cached for later */
1250 
1251  tupdesc = lookup_rowtype_tupdesc(ofTypeId, -1);
1252  for (i = 0; i < tupdesc->natts; i++)
1253  {
1254  Form_pg_attribute attr = TupleDescAttr(tupdesc, i);
1255  ColumnDef *n;
1256 
1257  if (attr->attisdropped)
1258  continue;
1259 
1260  n = makeNode(ColumnDef);
1261  n->colname = pstrdup(NameStr(attr->attname));
1262  n->typeName = makeTypeNameFromOid(attr->atttypid, attr->atttypmod);
1263  n->inhcount = 0;
1264  n->is_local = true;
1265  n->is_not_null = false;
1266  n->is_from_type = true;
1267  n->is_from_parent = false;
1268  n->storage = 0;
1269  n->raw_default = NULL;
1270  n->cooked_default = NULL;
1271  n->collClause = NULL;
1272  n->collOid = attr->attcollation;
1273  n->constraints = NIL;
1274  n->location = -1;
1275  cxt->columns = lappend(cxt->columns, n);
1276  }
1277  DecrTupleDescRefCount(tupdesc);
1278 
1279  ReleaseSysCache(tuple);
1280 }
#define NIL
Definition: pg_list.h:69
Oid typeOid
Definition: parsenodes.h:211
Type typenameType(ParseState *pstate, const TypeName *typeName, int32 *typmod_p)
Definition: parse_type.c:247
char storage
Definition: parsenodes.h:654
TupleDesc lookup_rowtype_tupdesc(Oid type_id, int32 typmod)
Definition: typcache.c:1641
bool is_local
Definition: parsenodes.h:650
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:93
List * constraints
Definition: parsenodes.h:662
char * pstrdup(const char *in)
Definition: mcxt.c:1161
bool is_from_parent
Definition: parsenodes.h:653
bool is_not_null
Definition: parsenodes.h:651
unsigned int Oid
Definition: postgres_ext.h:31
int natts
Definition: tupdesc.h:82
Node * cooked_default
Definition: parsenodes.h:656
void check_of_type(HeapTuple typetuple)
Definition: tablecmds.c:5274
Oid collOid
Definition: parsenodes.h:661
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:197
int location
Definition: parsenodes.h:664
#define AssertArg(condition)
Definition: c.h:701
Node * raw_default
Definition: parsenodes.h:655
List * lappend(List *list, void *datum)
Definition: list.c:128
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
TypeName * makeTypeNameFromOid(Oid typeOid, int32 typmod)
Definition: makefuncs.c:471
bool is_from_type
Definition: parsenodes.h:652
#define makeNode(_type_)
Definition: nodes.h:565
void DecrTupleDescRefCount(TupleDesc tupdesc)
Definition: tupdesc.c:391
TypeName * typeName
Definition: parsenodes.h:648
CollateClause * collClause
Definition: parsenodes.h:660
int i
int inhcount
Definition: parsenodes.h:649
#define NameStr(name)
Definition: c.h:576
char * colname
Definition: parsenodes.h:647
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:707

◆ 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

◆ transformPartitionBoundValue()

static Const * transformPartitionBoundValue ( ParseState pstate,
A_Const con,
const char *  colName,
Oid  colType,
int32  colTypmod 
)
static

Definition at line 3848 of file parse_utilcmd.c.

References COERCE_IMPLICIT_CAST, coerce_to_target_type(), COERCION_ASSIGNMENT, ereport, errcode(), errdetail(), errhint(), errmsg(), ERROR, expression_planner(), exprType(), format_type_be(), IsA, A_Const::location, make_const(), parser_errposition(), A_Const::val, and value.

Referenced by transformPartitionBound().

3850 {
3851  Node *value;
3852 
3853  /* Make it into a Const */
3854  value = (Node *) make_const(pstate, &con->val, con->location);
3855 
3856  /* Coerce to correct type */
3857  value = coerce_to_target_type(pstate,
3858  value, exprType(value),
3859  colType,
3860  colTypmod,
3863  -1);
3864 
3865  if (value == NULL)
3866  ereport(ERROR,
3867  (errcode(ERRCODE_DATATYPE_MISMATCH),
3868  errmsg("specified value cannot be cast to type %s for column \"%s\"",
3869  format_type_be(colType), colName),
3870  parser_errposition(pstate, con->location)));
3871 
3872  /* Simplify the expression, in case we had a coercion */
3873  if (!IsA(value, Const))
3874  value = (Node *) expression_planner((Expr *) value);
3875 
3876  /* Fail if we don't have a constant (i.e., non-immutable coercion) */
3877  if (!IsA(value, Const))
3878  ereport(ERROR,
3879  (errcode(ERRCODE_DATATYPE_MISMATCH),
3880  errmsg("specified value cannot be cast to type %s for column \"%s\"",
3881  format_type_be(colType), colName),
3882  errdetail("The cast requires a non-immutable conversion."),
3883  errhint("Try putting the literal value in single quotes."),
3884  parser_errposition(pstate, con->location)));
3885 
3886  return (Const *) value;
3887 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:568
int errhint(const char *fmt,...)
Definition: elog.c:987
Expr * expression_planner(Expr *expr)
Definition: planner.c:5888
Definition: nodes.h:517
int errcode(int sqlerrcode)
Definition: elog.c:575
char * format_type_be(Oid type_oid)
Definition: format_type.c:328
Const * make_const(ParseState *pstate, Value *value, int location)
Definition: parse_node.c:470
#define ERROR
Definition: elog.h:43
Node * coerce_to_target_type(ParseState *pstate, Node *expr, Oid exprtype, Oid targettype, int32 targettypmod, CoercionContext ccontext, CoercionForm cformat, int location)
Definition: parse_coerce.c:78
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define ereport(elevel, rest)
Definition: elog.h:122
static struct @131 value
int location
Definition: parsenodes.h:290
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
int errmsg(const char *fmt,...)
Definition: elog.c:797
Value val
Definition: parsenodes.h:289

◆ transformPartitionCmd()

static void transformPartitionCmd ( CreateStmtContext cxt,
PartitionCmd cmd 
)
static

Definition at line 3552 of file parse_utilcmd.c.

References Assert, PartitionCmd::bound, elog, ereport, errcode(), errmsg(), ERROR, CreateStmtContext::partbound, CreateStmtContext::pstate, RelationData::rd_rel, CreateStmtContext::rel, RelationGetPartitionKey, RelationGetRelationName, and transformPartitionBound().

Referenced by transformAlterTableStmt().

3553 {
3554  Relation parentRel = cxt->rel;
3555 
3556  switch (parentRel->rd_rel->relkind)
3557  {
3558  case RELKIND_PARTITIONED_TABLE:
3559  /* transform the partition bound, if any */
3560  Assert(RelationGetPartitionKey(parentRel) != NULL);
3561  if (cmd->bound != NULL)
3562  cxt->partbound = transformPartitionBound(cxt->pstate, parentRel,
3563  cmd->bound);
3564  break;
3565  case RELKIND_PARTITIONED_INDEX:
3566  /* nothing to check */
3567  Assert(cmd->bound == NULL);
3568  break;
3569  case RELKIND_RELATION:
3570  /* the table must be partitioned */
3571  ereport(ERROR,
3572  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3573  errmsg("table \"%s\" is not partitioned",
3574  RelationGetRelationName(parentRel))));
3575  break;
3576  case RELKIND_INDEX:
3577  /* the index must be partitioned */
3578  ereport(ERROR,
3579  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3580  errmsg("index \"%s\" is not partitioned",
3581  RelationGetRelationName(parentRel))));
3582  break;
3583  default:
3584  /* parser shouldn't let this case through */
3585  elog(ERROR, "\"%s\" is not a partitioned table or index",
3586  RelationGetRelationName(parentRel));
3587  break;
3588  }
3589 }
int errcode(int sqlerrcode)
Definition: elog.c:575
Form_pg_class rd_rel
Definition: rel.h:84
PartitionBoundSpec * transformPartitionBound(ParseState *pstate, Relation parent, PartitionBoundSpec *spec)
ParseState * pstate
Definition: parse_utilcmd.c:76
#define ERROR
Definition: elog.h:43
#define RelationGetRelationName(relation)
Definition: rel.h:441
#define ereport(elevel, rest)
Definition: elog.h:122
PartitionBoundSpec * partbound
Definition: parse_utilcmd.c:96
#define Assert(condition)
Definition: c.h:699
PartitionBoundSpec * bound
Definition: parsenodes.h:859
#define RelationGetPartitionKey(relation)
Definition: rel.h:589
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define elog
Definition: elog.h:219

◆ 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