PostgreSQL Source Code  git master
parse_utilcmd.c File Reference
#include "postgres.h"
#include "access/amapi.h"
#include "access/htup_details.h"
#include "access/relation.h"
#include "access/reloptions.h"
#include "access/table.h"
#include "catalog/dependency.h"
#include "catalog/heap.h"
#include "catalog/index.h"
#include "catalog/namespace.h"
#include "catalog/pg_am.h"
#include "catalog/pg_collation.h"
#include "catalog/pg_constraint.h"
#include "catalog/pg_opclass.h"
#include "catalog/pg_operator.h"
#include "catalog/pg_statistic_ext.h"
#include "catalog/pg_type.h"
#include "commands/comment.h"
#include "commands/defrem.h"
#include "commands/sequence.h"
#include "commands/tablecmds.h"
#include "commands/tablespace.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "optimizer/optimizer.h"
#include "parser/analyze.h"
#include "parser/parse_clause.h"
#include "parser/parse_coerce.h"
#include "parser/parse_collate.h"
#include "parser/parse_expr.h"
#include "parser/parse_relation.h"
#include "parser/parse_target.h"
#include "parser/parse_type.h"
#include "parser/parse_utilcmd.h"
#include "parser/parser.h"
#include "rewrite/rewriteManip.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/lsyscache.h"
#include "utils/partcache.h"
#include "utils/rel.h"
#include "utils/ruleutils.h"
#include "utils/syscache.h"
#include "utils/typcache.h"
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 ListtransformPartitionRangeBounds (ParseState *pstate, List *blist, Relation parent)
 
static void validateInfiniteBounds (ParseState *pstate, List *blist)
 
static ConsttransformPartitionBoundValue (ParseState *pstate, Node *con, const char *colName, Oid colType, int32 colTypmod, Oid partCollation)
 
ListtransformCreateStmt (CreateStmt *stmt, const char *queryString)
 
static void generateSerialExtraStmts (CreateStmtContext *cxt, ColumnDef *column, Oid seqtypid, List *seqoptions, bool for_identity, bool col_exists, char **snamespace_p, char **sname_p)
 
IndexStmtgenerateClonedIndexStmt (RangeVar *heapRel, Relation source_idx, const AttrMap *attmap, Oid *constraintOid)
 
IndexStmttransformIndexStmt (Oid relid, IndexStmt *stmt, const char *queryString)
 
void transformRuleStmt (RuleStmt *stmt, const char *queryString, List **actions, Node **whereClause)
 
AlterTableStmttransformAlterTableStmt (Oid relid, AlterTableStmt *stmt, const char *queryString, List **beforeStmts, List **afterStmts)
 
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 1726 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().

1728 {
1729  HeapTuple ht_stats;
1730  Form_pg_statistic_ext statsrec;
1731  CreateStatsStmt *stats;
1732  List *stat_types = NIL;
1733  List *def_names = NIL;
1734  bool isnull;
1735  Datum datum;
1736  ArrayType *arr;
1737  char *enabled;
1738  int i;
1739 
1740  Assert(OidIsValid(heapRelid));
1741  Assert(heapRel != NULL);
1742 
1743  /*
1744  * Fetch pg_statistic_ext tuple of source statistics object.
1745  */
1746  ht_stats = SearchSysCache1(STATEXTOID, ObjectIdGetDatum(source_statsid));
1747  if (!HeapTupleIsValid(ht_stats))
1748  elog(ERROR, "cache lookup failed for statistics object %u", source_statsid);
1749  statsrec = (Form_pg_statistic_ext) GETSTRUCT(ht_stats);
1750 
1751  /* Determine which statistics types exist */
1752  datum = SysCacheGetAttr(STATEXTOID, ht_stats,
1753  Anum_pg_statistic_ext_stxkind, &isnull);
1754  Assert(!isnull);
1755  arr = DatumGetArrayTypeP(datum);
1756  if (ARR_NDIM(arr) != 1 ||
1757  ARR_HASNULL(arr) ||
1758  ARR_ELEMTYPE(arr) != CHAROID)
1759  elog(ERROR, "stxkind is not a 1-D char array");
1760  enabled = (char *) ARR_DATA_PTR(arr);
1761  for (i = 0; i < ARR_DIMS(arr)[0]; i++)
1762  {
1763  if (enabled[i] == STATS_EXT_NDISTINCT)
1764  stat_types = lappend(stat_types, makeString("ndistinct"));
1765  else if (enabled[i] == STATS_EXT_DEPENDENCIES)
1766  stat_types = lappend(stat_types, makeString("dependencies"));
1767  else if (enabled[i] == STATS_EXT_MCV)
1768  stat_types = lappend(stat_types, makeString("mcv"));
1769  else
1770  elog(ERROR, "unrecognized statistics kind %c", enabled[i]);
1771  }
1772 
1773  /* Determine which columns the statistics are on */
1774  for (i = 0; i < statsrec->stxkeys.dim1; i++)
1775  {
1776  ColumnRef *cref = makeNode(ColumnRef);
1777  AttrNumber attnum = statsrec->stxkeys.values[i];
1778 
1779  cref->fields = list_make1(makeString(get_attname(heapRelid,
1780  attnum, false)));
1781  cref->location = -1;
1782 
1783  def_names = lappend(def_names, cref);
1784  }
1785 
1786  /* finally, build the output node */
1787  stats = makeNode(CreateStatsStmt);
1788  stats->defnames = NULL;
1789  stats->stat_types = stat_types;
1790  stats->exprs = def_names;
1791  stats->relations = list_make1(heapRel);
1792  stats->stxcomment = NULL;
1793  stats->if_not_exists = false;
1794 
1795  /* Clean up */
1796  ReleaseSysCache(ht_stats);
1797 
1798  return stats;
1799 }
Value * makeString(char *str)
Definition: value.c:53
#define NIL
Definition: pg_list.h:65
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
#define OidIsValid(objectId)
Definition: c.h:651
int location
Definition: parsenodes.h:237
#define list_make1(x1)
Definition: pg_list.h:227
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
#define ARR_DIMS(a)
Definition: array.h:282
#define ARR_DATA_PTR(a)
Definition: array.h:310
#define ARR_HASNULL(a)
Definition: array.h:279
List * lappend(List *list, void *datum)
Definition: list.c:321
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1116
uintptr_t Datum
Definition: postgres.h:367
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1377
int16 attnum
Definition: pg_attribute.h:79
#define makeNode(_type_)
Definition: nodes.h:577
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:745
#define ARR_NDIM(a)
Definition: array.h:278
#define elog(elevel,...)
Definition: elog.h:214
int i
char * get_attname(Oid relid, AttrNumber attnum, bool missing_ok)
Definition: lsyscache.c:825
Definition: pg_list.h:50
#define ARR_ELEMTYPE(a)
Definition: array.h:280
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:249

◆ generateClonedIndexStmt()

IndexStmt* generateClonedIndexStmt ( RangeVar heapRel,
Relation  source_idx,
const AttrMap attmap,
Oid constraintOid 
)

Definition at line 1367 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_attoptions(), 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, InvalidSubTransactionId, IndexStmt::isconstraint, lappend(), lfirst, list_head(), list_make2, lnext(), makeNode, makeString(), map_variable_attnos(), IndexElem::name, NameStr, NIL, IndexElem::nulls_ordering, ObjectIdGetDatum, OidIsValid, IndexStmt::oldCreateSubid, IndexStmt::oldFirstRelfilenodeSubid, IndexStmt::oldNode, IndexElem::opclass, IndexElem::opclassopts, OPEROID, IndexStmt::options, IndexElem::ordering, IndexStmt::primary, pstrdup(), RelationData::rd_indam, RelationData::rd_indextuple, RelationData::rd_indoption, IndexStmt::relation, RelationGetDescr, RelationGetRelationName, RelationGetRelid, ReleaseSysCache(), RELOID, IndexStmt::reset_default_tblspc, SearchSysCache1(), SORTBY_DEFAULT, SORTBY_DESC, SORTBY_NULLS_DEFAULT, SORTBY_NULLS_FIRST, SORTBY_NULLS_LAST, stringToNode(), SysCacheGetAttr(), IndexStmt::tableSpace, TextDatumGetCString, IndexStmt::transformed, TupleDescAttr, IndexStmt::unique, untransformRelOptions(), oidvector::values, and IndexStmt::whereClause.

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

1370 {
1371  Oid source_relid = RelationGetRelid(source_idx);
1372  HeapTuple ht_idxrel;
1373  HeapTuple ht_idx;
1374  HeapTuple ht_am;
1375  Form_pg_class idxrelrec;
1376  Form_pg_index idxrec;
1377  Form_pg_am amrec;
1378  oidvector *indcollation;
1379  oidvector *indclass;
1380  IndexStmt *index;
1381  List *indexprs;
1382  ListCell *indexpr_item;
1383  Oid indrelid;
1384  int keyno;
1385  Oid keycoltype;
1386  Datum datum;
1387  bool isnull;
1388 
1389  if (constraintOid)
1390  *constraintOid = InvalidOid;
1391 
1392  /*
1393  * Fetch pg_class tuple of source index. We can't use the copy in the
1394  * relcache entry because it doesn't include optional fields.
1395  */
1396  ht_idxrel = SearchSysCache1(RELOID, ObjectIdGetDatum(source_relid));
1397  if (!HeapTupleIsValid(ht_idxrel))
1398  elog(ERROR, "cache lookup failed for relation %u", source_relid);
1399  idxrelrec = (Form_pg_class) GETSTRUCT(ht_idxrel);
1400 
1401  /* Fetch pg_index tuple for source index from relcache entry */
1402  ht_idx = source_idx->rd_indextuple;
1403  idxrec = (Form_pg_index) GETSTRUCT(ht_idx);
1404  indrelid = idxrec->indrelid;
1405 
1406  /* Fetch the pg_am tuple of the index' access method */
1407  ht_am = SearchSysCache1(AMOID, ObjectIdGetDatum(idxrelrec->relam));
1408  if (!HeapTupleIsValid(ht_am))
1409  elog(ERROR, "cache lookup failed for access method %u",
1410  idxrelrec->relam);
1411  amrec = (Form_pg_am) GETSTRUCT(ht_am);
1412 
1413  /* Extract indcollation from the pg_index tuple */
1414  datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1415  Anum_pg_index_indcollation, &isnull);
1416  Assert(!isnull);
1417  indcollation = (oidvector *) DatumGetPointer(datum);
1418 
1419  /* Extract indclass from the pg_index tuple */
1420  datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1421  Anum_pg_index_indclass, &isnull);
1422  Assert(!isnull);
1423  indclass = (oidvector *) DatumGetPointer(datum);
1424 
1425  /* Begin building the IndexStmt */
1426  index = makeNode(IndexStmt);
1427  index->relation = heapRel;
1428  index->accessMethod = pstrdup(NameStr(amrec->amname));
1429  if (OidIsValid(idxrelrec->reltablespace))
1430  index->tableSpace = get_tablespace_name(idxrelrec->reltablespace);
1431  else
1432  index->tableSpace = NULL;
1433  index->excludeOpNames = NIL;
1434  index->idxcomment = NULL;
1435  index->indexOid = InvalidOid;
1436  index->oldNode = InvalidOid;
1439  index->unique = idxrec->indisunique;
1440  index->primary = idxrec->indisprimary;
1441  index->transformed = true; /* don't need transformIndexStmt */
1442  index->concurrent = false;
1443  index->if_not_exists = false;
1444  index->reset_default_tblspc = false;
1445 
1446  /*
1447  * We don't try to preserve the name of the source index; instead, just
1448  * let DefineIndex() choose a reasonable name. (If we tried to preserve
1449  * the name, we'd get duplicate-relation-name failures unless the source
1450  * table was in a different schema.)
1451  */
1452  index->idxname = NULL;
1453 
1454  /*
1455  * If the index is marked PRIMARY or has an exclusion condition, it's
1456  * certainly from a constraint; else, if it's not marked UNIQUE, it
1457  * certainly isn't. If it is or might be from a constraint, we have to
1458  * fetch the pg_constraint record.
1459  */
1460  if (index->primary || index->unique || idxrec->indisexclusion)
1461  {
1462  Oid constraintId = get_index_constraint(source_relid);
1463 
1464  if (OidIsValid(constraintId))
1465  {
1466  HeapTuple ht_constr;
1467  Form_pg_constraint conrec;
1468 
1469  if (constraintOid)
1470  *constraintOid = constraintId;
1471 
1472  ht_constr = SearchSysCache1(CONSTROID,
1473  ObjectIdGetDatum(constraintId));
1474  if (!HeapTupleIsValid(ht_constr))
1475  elog(ERROR, "cache lookup failed for constraint %u",
1476  constraintId);
1477  conrec = (Form_pg_constraint) GETSTRUCT(ht_constr);
1478 
1479  index->isconstraint = true;
1480  index->deferrable = conrec->condeferrable;
1481  index->initdeferred = conrec->condeferred;
1482 
1483  /* If it's an exclusion constraint, we need the operator names */
1484  if (idxrec->indisexclusion)
1485  {
1486  Datum *elems;
1487  int nElems;
1488  int i;
1489 
1490  Assert(conrec->contype == CONSTRAINT_EXCLUSION);
1491  /* Extract operator OIDs from the pg_constraint tuple */
1492  datum = SysCacheGetAttr(CONSTROID, ht_constr,
1493  Anum_pg_constraint_conexclop,
1494  &isnull);
1495  if (isnull)
1496  elog(ERROR, "null conexclop for constraint %u",
1497  constraintId);
1498 
1500  OIDOID, sizeof(Oid), true, TYPALIGN_INT,
1501  &elems, NULL, &nElems);
1502 
1503  for (i = 0; i < nElems; i++)
1504  {
1505  Oid operid = DatumGetObjectId(elems[i]);
1506  HeapTuple opertup;
1507  Form_pg_operator operform;
1508  char *oprname;
1509  char *nspname;
1510  List *namelist;
1511 
1512  opertup = SearchSysCache1(OPEROID,
1513  ObjectIdGetDatum(operid));
1514  if (!HeapTupleIsValid(opertup))
1515  elog(ERROR, "cache lookup failed for operator %u",
1516  operid);
1517  operform = (Form_pg_operator) GETSTRUCT(opertup);
1518  oprname = pstrdup(NameStr(operform->oprname));
1519  /* For simplicity we always schema-qualify the op name */
1520  nspname = get_namespace_name(operform->oprnamespace);
1521  namelist = list_make2(makeString(nspname),
1522  makeString(oprname));
1523  index->excludeOpNames = lappend(index->excludeOpNames,
1524  namelist);
1525  ReleaseSysCache(opertup);
1526  }
1527  }
1528 
1529  ReleaseSysCache(ht_constr);
1530  }
1531  else
1532  index->isconstraint = false;
1533  }
1534  else
1535  index->isconstraint = false;
1536 
1537  /* Get the index expressions, if any */
1538  datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1539  Anum_pg_index_indexprs, &isnull);
1540  if (!isnull)
1541  {
1542  char *exprsString;
1543 
1544  exprsString = TextDatumGetCString(datum);
1545  indexprs = (List *) stringToNode(exprsString);
1546  }
1547  else
1548  indexprs = NIL;
1549 
1550  /* Build the list of IndexElem */
1551  index->indexParams = NIL;
1552  index->indexIncludingParams = NIL;
1553 
1554  indexpr_item = list_head(indexprs);
1555  for (keyno = 0; keyno < idxrec->indnkeyatts; keyno++)
1556  {
1557  IndexElem *iparam;
1558  AttrNumber attnum = idxrec->indkey.values[keyno];
1560  keyno);
1561  int16 opt = source_idx->rd_indoption[keyno];
1562 
1563  iparam = makeNode(IndexElem);
1564 
1565  if (AttributeNumberIsValid(attnum))
1566  {
1567  /* Simple index column */
1568  char *attname;
1569 
1570  attname = get_attname(indrelid, attnum, false);
1571  keycoltype = get_atttype(indrelid, attnum);
1572 
1573  iparam->name = attname;
1574  iparam->expr = NULL;
1575  }
1576  else
1577  {
1578  /* Expressional index */
1579  Node *indexkey;
1580  bool found_whole_row;
1581 
1582  if (indexpr_item == NULL)
1583  elog(ERROR, "too few entries in indexprs list");
1584  indexkey = (Node *) lfirst(indexpr_item);
1585  indexpr_item = lnext(indexprs, indexpr_item);
1586 
1587  /* Adjust Vars to match new table's column numbering */
1588  indexkey = map_variable_attnos(indexkey,
1589  1, 0,
1590  attmap,
1591  InvalidOid, &found_whole_row);
1592 
1593  /* As in transformTableLikeClause, reject whole-row variables */
1594  if (found_whole_row)
1595  ereport(ERROR,
1596  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1597  errmsg("cannot convert whole-row table reference"),
1598  errdetail("Index \"%s\" contains a whole-row table reference.",
1599  RelationGetRelationName(source_idx))));
1600 
1601  iparam->name = NULL;
1602  iparam->expr = indexkey;
1603 
1604  keycoltype = exprType(indexkey);
1605  }
1606 
1607  /* Copy the original index column name */
1608  iparam->indexcolname = pstrdup(NameStr(attr->attname));
1609 
1610  /* Add the collation name, if non-default */
1611  iparam->collation = get_collation(indcollation->values[keyno], keycoltype);
1612 
1613  /* Add the operator class name, if non-default */
1614  iparam->opclass = get_opclass(indclass->values[keyno], keycoltype);
1615  iparam->opclassopts =
1616  untransformRelOptions(get_attoptions(source_relid, keyno + 1));
1617 
1618  iparam->ordering = SORTBY_DEFAULT;
1620 
1621  /* Adjust options if necessary */
1622  if (source_idx->rd_indam->amcanorder)
1623  {
1624  /*
1625  * If it supports sort ordering, copy DESC and NULLS opts. Don't
1626  * set non-default settings unnecessarily, though, so as to
1627  * improve the chance of recognizing equivalence to constraint
1628  * indexes.
1629  */
1630  if (opt & INDOPTION_DESC)
1631  {
1632  iparam->ordering = SORTBY_DESC;
1633  if ((opt & INDOPTION_NULLS_FIRST) == 0)
1635  }
1636  else
1637  {
1638  if (opt & INDOPTION_NULLS_FIRST)
1640  }
1641  }
1642 
1643  index->indexParams = lappend(index->indexParams, iparam);
1644  }
1645 
1646  /* Handle included columns separately */
1647  for (keyno = idxrec->indnkeyatts; keyno < idxrec->indnatts; keyno++)
1648  {
1649  IndexElem *iparam;
1650  AttrNumber attnum = idxrec->indkey.values[keyno];
1652  keyno);
1653 
1654  iparam = makeNode(IndexElem);
1655 
1656  if (AttributeNumberIsValid(attnum))
1657  {
1658  /* Simple index column */
1659  char *attname;
1660 
1661  attname = get_attname(indrelid, attnum, false);
1662  keycoltype = get_atttype(indrelid, attnum);
1663 
1664  iparam->name = attname;
1665  iparam->expr = NULL;
1666  }
1667  else
1668  ereport(ERROR,
1669  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1670  errmsg("expressions are not supported in included columns")));
1671 
1672  /* Copy the original index column name */
1673  iparam->indexcolname = pstrdup(NameStr(attr->attname));
1674 
1675  index->indexIncludingParams = lappend(index->indexIncludingParams, iparam);
1676  }
1677  /* Copy reloptions if any */
1678  datum = SysCacheGetAttr(RELOID, ht_idxrel,
1679  Anum_pg_class_reloptions, &isnull);
1680  if (!isnull)
1681  index->options = untransformRelOptions(datum);
1682 
1683  /* If it's a partial index, decompile and append the predicate */
1684  datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1685  Anum_pg_index_indpred, &isnull);
1686  if (!isnull)
1687  {
1688  char *pred_str;
1689  Node *pred_tree;
1690  bool found_whole_row;
1691 
1692  /* Convert text string to node tree */
1693  pred_str = TextDatumGetCString(datum);
1694  pred_tree = (Node *) stringToNode(pred_str);
1695 
1696  /* Adjust Vars to match new table's column numbering */
1697  pred_tree = map_variable_attnos(pred_tree,
1698  1, 0,
1699  attmap,
1700  InvalidOid, &found_whole_row);
1701 
1702  /* As in transformTableLikeClause, reject whole-row variables */
1703  if (found_whole_row)
1704  ereport(ERROR,
1705  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1706  errmsg("cannot convert whole-row table reference"),
1707  errdetail("Index \"%s\" contains a whole-row table reference.",
1708  RelationGetRelationName(source_idx))));
1709 
1710  index->whereClause = pred_tree;
1711  }
1712 
1713  /* Clean up */
1714  ReleaseSysCache(ht_idxrel);
1715  ReleaseSysCache(ht_am);
1716 
1717  return index;
1718 }
#define list_make2(x1, x2)
Definition: pg_list.h:229
bool deferrable
Definition: parsenodes.h:2794
Value * makeString(char *str)
Definition: value.c:53
signed short int16
Definition: c.h:361
#define NIL
Definition: pg_list.h:65
static List * get_opclass(Oid opclass, Oid actual_datatype)
Definition: c.h:601
bool primary
Definition: parsenodes.h:2792
struct IndexAmRoutine * rd_indam
Definition: rel.h:188
int16 * rd_indoption
Definition: rel.h:193
SortByDir ordering
Definition: parsenodes.h:706
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
Definition: syscache.h:36
List * options
Definition: parsenodes.h:2782
SubTransactionId oldCreateSubid
Definition: parsenodes.h:2788
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:321
#define RelationGetDescr(relation)
Definition: rel.h:482
char * tableSpace
Definition: parsenodes.h:2778
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
#define DatumGetObjectId(X)
Definition: postgres.h:500
char * pstrdup(const char *in)
Definition: mcxt.c:1186
Node * whereClause
Definition: parsenodes.h:2783
Definition: nodes.h:529
int errcode(int sqlerrcode)
Definition: elog.c:610
void * stringToNode(const char *str)
Definition: read.c:89
Node * map_variable_attnos(Node *node, int target_varno, int sublevels_up, const AttrMap *attno_map, Oid to_rowtype, bool *found_whole_row)
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:651
List * opclassopts
Definition: parsenodes.h:705
struct HeapTupleData * rd_indextuple
Definition: rel.h:176
List * indexIncludingParams
Definition: parsenodes.h:2780
Definition: type.h:89
Oid indexOid
Definition: parsenodes.h:2786
Node * expr
Definition: parsenodes.h:701
RangeVar * relation
Definition: parsenodes.h:2776
Datum get_attoptions(Oid relid, int16 attnum)
Definition: lsyscache.c:968
SortByNulls nulls_ordering
Definition: parsenodes.h:707
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
NameData attname
Definition: pg_attribute.h:40
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3191
Oid values[FLEXIBLE_ARRAY_MEMBER]
Definition: c.h:609
bool transformed
Definition: parsenodes.h:2796
int errdetail(const char *fmt,...)
Definition: elog.c:957
char * indexcolname
Definition: parsenodes.h:702
#define RelationGetRelationName(relation)
Definition: rel.h:490
static ListCell * list_head(const List *l)
Definition: pg_list.h:125
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:193
Oid get_index_constraint(Oid indexId)
Definition: pg_depend.c:965
SubTransactionId oldFirstRelfilenodeSubid
Definition: parsenodes.h:2789
Oid get_atttype(Oid relid, AttrNumber attnum)
Definition: lsyscache.c:911
List * lappend(List *list, void *datum)
Definition: list.c:321
char * idxname
Definition: parsenodes.h:2775
FormData_pg_index * Form_pg_index
Definition: pg_index.h:68
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1116
#define AttributeNumberIsValid(attributeNumber)
Definition: attnum.h:34
#define TextDatumGetCString(d)
Definition: builtins.h:88
bool reset_default_tblspc
Definition: parsenodes.h:2799
bool if_not_exists
Definition: parsenodes.h:2798
uintptr_t Datum
Definition: postgres.h:367
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1377
bool unique
Definition: parsenodes.h:2791
List * untransformRelOptions(Datum options)
Definition: reloptions.c:1308
char * accessMethod
Definition: parsenodes.h:2777
#define InvalidOid
Definition: postgres_ext.h:36
int16 attnum
Definition: pg_attribute.h:79
#define ereport(elevel,...)
Definition: elog.h:144
List * opclass
Definition: parsenodes.h:704
#define makeNode(_type_)
Definition: nodes.h:577
FormData_pg_constraint * Form_pg_constraint
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:745
#define lfirst(lc)
Definition: pg_list.h:190
List * indexParams
Definition: parsenodes.h:2779
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
List * excludeOpNames
Definition: parsenodes.h:2784
bool initdeferred
Definition: parsenodes.h:2795
bool amcanorder
Definition: amapi.h:219
char * name
Definition: parsenodes.h:700
char * idxcomment
Definition: parsenodes.h:2785
#define InvalidSubTransactionId
Definition: c.h:526
FormData_pg_operator * Form_pg_operator
Definition: pg_operator.h:83
#define DatumGetPointer(X)
Definition: postgres.h:549
void deconstruct_array(ArrayType *array, Oid elmtype, int elmlen, bool elmbyval, char elmalign, Datum **elemsp, bool **nullsp, int *nelemsp)
Definition: arrayfuncs.c:3483
FormData_pg_class * Form_pg_class
Definition: pg_class.h:153
bool concurrent
Definition: parsenodes.h:2797
bool isconstraint
Definition: parsenodes.h:2793
FormData_pg_am * Form_pg_am
Definition: pg_am.h:48
int errmsg(const char *fmt,...)
Definition: elog.c:824
char * get_tablespace_name(Oid spc_oid)
Definition: tablespace.c:1467
#define elog(elevel,...)
Definition: elog.h:214
int i
#define NameStr(name)
Definition: c.h:622
List * collation
Definition: parsenodes.h:703
char * get_attname(Oid relid, AttrNumber attnum, bool missing_ok)
Definition: lsyscache.c:825
static List * get_collation(Oid collation, Oid actual_datatype)
Definition: pg_list.h:50
int16 AttrNumber
Definition: attnum.h:21
#define RelationGetRelid(relation)
Definition: rel.h:456
#define DatumGetArrayTypeP(X)
Definition: array.h:249

◆ generateSerialExtraStmts()

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

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

353 {
354  ListCell *option;
355  DefElem *nameEl = NULL;
356  Oid snamespaceid;
357  char *snamespace;
358  char *sname;
359  CreateSeqStmt *seqstmt;
360  AlterSeqStmt *altseqstmt;
361  List *attnamelist;
362 
363  /*
364  * Determine namespace and name to use for the sequence.
365  *
366  * First, check if a sequence name was passed in as an option. This is
367  * used by pg_dump. Else, generate a name.
368  *
369  * Although we use ChooseRelationName, it's not guaranteed that the
370  * selected sequence name won't conflict; given sufficiently long field
371  * names, two different serial columns in the same table could be assigned
372  * the same sequence name, and we'd not notice since we aren't creating
373  * the sequence quite yet. In practice this seems quite unlikely to be a
374  * problem, especially since few people would need two serial columns in
375  * one table.
376  */
377  foreach(option, seqoptions)
378  {
379  DefElem *defel = lfirst_node(DefElem, option);
380 
381  if (strcmp(defel->defname, "sequence_name") == 0)
382  {
383  if (nameEl)
384  ereport(ERROR,
385  (errcode(ERRCODE_SYNTAX_ERROR),
386  errmsg("conflicting or redundant options")));
387  nameEl = defel;
388  }
389  }
390 
391  if (nameEl)
392  {
394 
395  snamespace = rv->schemaname;
396  if (!snamespace)
397  {
398  /* Given unqualified SEQUENCE NAME, select namespace */
399  if (cxt->rel)
400  snamespaceid = RelationGetNamespace(cxt->rel);
401  else
402  snamespaceid = RangeVarGetCreationNamespace(cxt->relation);
403  snamespace = get_namespace_name(snamespaceid);
404  }
405  sname = rv->relname;
406  /* Remove the SEQUENCE NAME item from seqoptions */
407  seqoptions = list_delete_ptr(seqoptions, nameEl);
408  }
409  else
410  {
411  if (cxt->rel)
412  snamespaceid = RelationGetNamespace(cxt->rel);
413  else
414  {
415  snamespaceid = RangeVarGetCreationNamespace(cxt->relation);
416  RangeVarAdjustRelationPersistence(cxt->relation, snamespaceid);
417  }
418  snamespace = get_namespace_name(snamespaceid);
419  sname = ChooseRelationName(cxt->relation->relname,
420  column->colname,
421  "seq",
422  snamespaceid,
423  false);
424  }
425 
426  ereport(DEBUG1,
427  (errmsg("%s will create implicit sequence \"%s\" for serial column \"%s.%s\"",
428  cxt->stmtType, sname,
429  cxt->relation->relname, column->colname)));
430 
431  /*
432  * Build a CREATE SEQUENCE command to create the sequence object, and add
433  * it to the list of things to be done before this CREATE/ALTER TABLE.
434  */
435  seqstmt = makeNode(CreateSeqStmt);
436  seqstmt->for_identity = for_identity;
437  seqstmt->sequence = makeRangeVar(snamespace, sname, -1);
438  seqstmt->options = seqoptions;
439 
440  /*
441  * If a sequence data type was specified, add it to the options. Prepend
442  * to the list rather than append; in case a user supplied their own AS
443  * clause, the "redundant options" error will point to their occurrence,
444  * not our synthetic one.
445  */
446  if (seqtypid)
447  seqstmt->options = lcons(makeDefElem("as",
448  (Node *) makeTypeNameFromOid(seqtypid, -1),
449  -1),
450  seqstmt->options);
451 
452  /*
453  * If this is ALTER ADD COLUMN, make sure the sequence will be owned by
454  * the table's owner. The current user might be someone else (perhaps a
455  * superuser, or someone who's only a member of the owning role), but the
456  * SEQUENCE OWNED BY mechanisms will bleat unless table and sequence have
457  * exactly the same owning role.
458  */
459  if (cxt->rel)
460  seqstmt->ownerId = cxt->rel->rd_rel->relowner;
461  else
462  seqstmt->ownerId = InvalidOid;
463 
464  cxt->blist = lappend(cxt->blist, seqstmt);
465 
466  /*
467  * Store the identity sequence name that we decided on. ALTER TABLE ...
468  * ADD COLUMN ... IDENTITY needs this so that it can fill the new column
469  * with values from the sequence, while the association of the sequence
470  * with the table is not set until after the ALTER TABLE.
471  */
472  column->identitySequence = seqstmt->sequence;
473 
474  /*
475  * Build an ALTER SEQUENCE ... OWNED BY command to mark the sequence as
476  * owned by this column, and add it to the appropriate list of things to
477  * be done along with this CREATE/ALTER TABLE. In a CREATE or ALTER ADD
478  * COLUMN, it must be done after the statement because we don't know the
479  * column's attnum yet. But if we do have the attnum (in AT_AddIdentity),
480  * we can do the marking immediately, which improves some ALTER TABLE
481  * behaviors.
482  */
483  altseqstmt = makeNode(AlterSeqStmt);
484  altseqstmt->sequence = makeRangeVar(snamespace, sname, -1);
485  attnamelist = list_make3(makeString(snamespace),
486  makeString(cxt->relation->relname),
487  makeString(column->colname));
488  altseqstmt->options = list_make1(makeDefElem("owned_by",
489  (Node *) attnamelist, -1));
490  altseqstmt->for_identity = for_identity;
491 
492  if (col_exists)
493  cxt->blist = lappend(cxt->blist, altseqstmt);
494  else
495  cxt->alist = lappend(cxt->alist, altseqstmt);
496 
497  if (snamespace_p)
498  *snamespace_p = snamespace;
499  if (sname_p)
500  *sname_p = sname;
501 }
Value * makeString(char *str)
Definition: value.c:53
#define list_make3(x1, x2, x3)
Definition: pg_list.h:231
#define DEBUG1
Definition: elog.h:25
#define castNode(_type_, nodeptr)
Definition: nodes.h:598
Definition: nodes.h:529
int errcode(int sqlerrcode)
Definition: elog.c:610
RangeVar * makeRangeVarFromNameList(List *names)
Definition: namespace.c:3062
List * list_delete_ptr(List *list, void *datum)
Definition: list.c:796
char * ChooseRelationName(const char *name1, const char *name2, const char *label, Oid namespaceid, bool isconstraint)
Definition: indexcmds.c:2240
Form_pg_class rd_rel
Definition: rel.h:109
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:641
List * options
Definition: parsenodes.h:2556
char * schemaname
Definition: primnodes.h:67
#define list_make1(x1)
Definition: pg_list.h:227
RangeVar * identitySequence
Definition: parsenodes.h:657
char * relname
Definition: primnodes.h:68
RangeVar * relation
Definition: parse_utilcmd.c:80
#define ERROR
Definition: elog.h:43
#define lfirst_node(type, lc)
Definition: pg_list.h:193
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3191
Node * arg
Definition: parsenodes.h:733
List * lappend(List *list, void *datum)
Definition: list.c:321
TypeName * makeTypeNameFromOid(Oid typeOid, int32 typmod)
Definition: makefuncs.c:472
#define InvalidOid
Definition: postgres_ext.h:36
RangeVar * sequence
Definition: parsenodes.h:2555
#define ereport(elevel,...)
Definition: elog.h:144
RangeVar * sequence
Definition: parsenodes.h:2545
List * lcons(void *datum, List *list)
Definition: list.c:453
#define makeNode(_type_)
Definition: nodes.h:577
const char * stmtType
Definition: parse_utilcmd.c:79
int errmsg(const char *fmt,...)
Definition: elog.c:824
bool for_identity
Definition: parsenodes.h:2557
char * defname
Definition: parsenodes.h:732
char * colname
Definition: parsenodes.h:647
Definition: pg_list.h:50
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition: makefuncs.c:422
Oid RangeVarGetCreationNamespace(const RangeVar *newRelation)
Definition: namespace.c:449
List * options
Definition: parsenodes.h:2546
#define RelationGetNamespace(relation)
Definition: rel.h:497

◆ get_collation()

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

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

1809 {
1810  List *result;
1811  HeapTuple ht_coll;
1812  Form_pg_collation coll_rec;
1813  char *nsp_name;
1814  char *coll_name;
1815 
1816  if (!OidIsValid(collation))
1817  return NIL; /* easy case */
1818  if (collation == get_typcollation(actual_datatype))
1819  return NIL; /* just let it default */
1820 
1821  ht_coll = SearchSysCache1(COLLOID, ObjectIdGetDatum(collation));
1822  if (!HeapTupleIsValid(ht_coll))
1823  elog(ERROR, "cache lookup failed for collation %u", collation);
1824  coll_rec = (Form_pg_collation) GETSTRUCT(ht_coll);
1825 
1826  /* For simplicity, we always schema-qualify the name */
1827  nsp_name = get_namespace_name(coll_rec->collnamespace);
1828  coll_name = pstrdup(NameStr(coll_rec->collname));
1829  result = list_make2(makeString(nsp_name), makeString(coll_name));
1830 
1831  ReleaseSysCache(ht_coll);
1832  return result;
1833 }
#define list_make2(x1, x2)
Definition: pg_list.h:229
Value * makeString(char *str)
Definition: value.c:53
#define NIL
Definition: pg_list.h:65
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
char * pstrdup(const char *in)
Definition: mcxt.c:1186
#define OidIsValid(objectId)
Definition: c.h:651
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3191
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1116
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
Oid get_typcollation(Oid typid)
Definition: lsyscache.c:2933
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
FormData_pg_collation * Form_pg_collation
Definition: pg_collation.h:51
#define elog(elevel,...)
Definition: elog.h:214
#define NameStr(name)
Definition: c.h:622
Definition: pg_list.h:50

◆ get_opclass()

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

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

1843 {
1844  List *result = NIL;
1845  HeapTuple ht_opc;
1846  Form_pg_opclass opc_rec;
1847 
1848  ht_opc = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclass));
1849  if (!HeapTupleIsValid(ht_opc))
1850  elog(ERROR, "cache lookup failed for opclass %u", opclass);
1851  opc_rec = (Form_pg_opclass) GETSTRUCT(ht_opc);
1852 
1853  if (GetDefaultOpClass(actual_datatype, opc_rec->opcmethod) != opclass)
1854  {
1855  /* For simplicity, we always schema-qualify the name */
1856  char *nsp_name = get_namespace_name(opc_rec->opcnamespace);
1857  char *opc_name = pstrdup(NameStr(opc_rec->opcname));
1858 
1859  result = list_make2(makeString(nsp_name), makeString(opc_name));
1860  }
1861 
1862  ReleaseSysCache(ht_opc);
1863  return result;
1864 }
#define list_make2(x1, x2)
Definition: pg_list.h:229
Value * makeString(char *str)
Definition: value.c:53
#define NIL
Definition: pg_list.h:65
Oid GetDefaultOpClass(Oid type_id, Oid am_id)
Definition: indexcmds.c:2045
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
char * pstrdup(const char *in)
Definition: mcxt.c:1186
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3191
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1116
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define elog(elevel,...)
Definition: elog.h:214
#define NameStr(name)
Definition: c.h:622
FormData_pg_opclass * Form_pg_opclass
Definition: pg_opclass.h:83
Definition: pg_list.h:50

◆ setSchemaName()

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

Definition at line 3701 of file parse_utilcmd.c.

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

Referenced by transformCreateSchemaStmt().

3702 {
3703  if (*stmt_schema_name == NULL)
3704  *stmt_schema_name = context_schema;
3705  else if (strcmp(context_schema, *stmt_schema_name) != 0)
3706  ereport(ERROR,
3707  (errcode(ERRCODE_INVALID_SCHEMA_DEFINITION),
3708  errmsg("CREATE specifies a schema (%s) "
3709  "different from the one being created (%s)",
3710  *stmt_schema_name, context_schema)));
3711 }
int errcode(int sqlerrcode)
Definition: elog.c:610
#define ERROR
Definition: elog.h:43
#define ereport(elevel,...)
Definition: elog.h:144
int errmsg(const char *fmt,...)
Definition: elog.c:824

◆ transformAlterTableStmt()

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

Definition at line 3061 of file parse_utilcmd.c.

References AccessShareLock, addNSItemToQuery(), addRangeTableEntryForRelation(), CreateStmtContext::alist, AT_AddColumn, AT_AddColumnRecurse, AT_AddConstraint, AT_AddConstraintRecurse, AT_AddIdentity, AT_AddIndex, AT_AddIndexConstraint, AT_AlterColumnType, AT_AttachPartition, AT_DetachPartition, 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, ereport, errcode(), errmsg(), ERROR, EXPR_KIND_ALTER_COL_TRANSFORM, CreateStmtContext::extstats, CreateStmtContext::fkconstraints, AlterSeqStmt::for_identity, Constraint::generated_when, generateSerialExtraStmts(), get_attnum(), get_atttype(), get_namespace_name(), get_rel_name(), get_rel_namespace(), getIdentitySequence(), ColumnDef::identity, IndexStmt::indexOid, CreateStmtContext::inh_indexes, CreateStmtContext::inhRelations, InvalidAttrNumber, IsA, CreateStmtContext::isalter, CreateStmtContext::isforeign, CreateStmtContext::ispartitioned, CreateStmtContext::ixconstraints, lappend(), lfirst, lfirst_node, list_concat(), list_make1, make_parsestate(), makeDefElem(), makeNode, makeRangeVar(), makeTypeNameFromOid(), AlterSeqStmt::missing_ok, AlterTableCmd::name, NIL, nodeTag, NoLock, CreateStmtContext::ofType, OidIsValid, Constraint::options, AlterSeqStmt::options, ParseState::p_sourcetext, CreateStmtContext::partbound, CreateStmtContext::pkey, CreateStmtContext::pstate, ColumnDef::raw_default, RelationData::rd_rel, CreateStmtContext::rel, CreateStmtContext::relation, AlterTableStmt::relation, relation_close(), relation_open(), RelationGetDescr, RelationGetRelationName, AlterSeqStmt::sequence, CreateStmtContext::stmtType, AlterTableCmd::subtype, transformCheckConstraints(), transformColumnDefinition(), transformExpr(), transformExtendedStatistics(), transformFKConstraints(), transformIndexConstraints(), transformIndexStmt(), transformPartitionCmd(), transformTableConstraint(), TupleDescAttr, ColumnDef::typeName, and typenameTypeId().

Referenced by ATParseTransformCmd(), and ATPostAlterTypeParse().

3064 {
3065  Relation rel;
3066  TupleDesc tupdesc;
3067  ParseState *pstate;
3068  CreateStmtContext cxt;
3069  List *save_alist;
3070  ListCell *lcmd,
3071  *l;
3072  List *newcmds = NIL;
3073  bool skipValidation = true;
3074  AlterTableCmd *newcmd;
3075  ParseNamespaceItem *nsitem;
3076 
3077  /*
3078  * We must not scribble on the passed-in AlterTableStmt, so copy it. (This
3079  * is overkill, but easy.)
3080  */
3081  stmt = copyObject(stmt);
3082 
3083  /* Caller is responsible for locking the relation */
3084  rel = relation_open(relid, NoLock);
3085  tupdesc = RelationGetDescr(rel);
3086 
3087  /* Set up pstate */
3088  pstate = make_parsestate(NULL);
3089  pstate->p_sourcetext = queryString;
3090  nsitem = addRangeTableEntryForRelation(pstate,
3091  rel,
3093  NULL,
3094  false,
3095  true);
3096  addNSItemToQuery(pstate, nsitem, false, true, true);
3097 
3098  /* Set up CreateStmtContext */
3099  cxt.pstate = pstate;
3100  if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
3101  {
3102  cxt.stmtType = "ALTER FOREIGN TABLE";
3103  cxt.isforeign = true;
3104  }
3105  else
3106  {
3107  cxt.stmtType = "ALTER TABLE";
3108  cxt.isforeign = false;
3109  }
3110  cxt.relation = stmt->relation;
3111  cxt.rel = rel;
3112  cxt.inhRelations = NIL;
3113  cxt.isalter = true;
3114  cxt.columns = NIL;
3115  cxt.ckconstraints = NIL;
3116  cxt.fkconstraints = NIL;
3117  cxt.ixconstraints = NIL;
3118  cxt.inh_indexes = NIL;
3119  cxt.extstats = NIL;
3120  cxt.blist = NIL;
3121  cxt.alist = NIL;
3122  cxt.pkey = NULL;
3123  cxt.ispartitioned = (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
3124  cxt.partbound = NULL;
3125  cxt.ofType = false;
3126 
3127  /*
3128  * Transform ALTER subcommands that need it (most don't). These largely
3129  * re-use code from CREATE TABLE.
3130  */
3131  foreach(lcmd, stmt->cmds)
3132  {
3133  AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
3134 
3135  switch (cmd->subtype)
3136  {
3137  case AT_AddColumn:
3138  case AT_AddColumnRecurse:
3139  {
3140  ColumnDef *def = castNode(ColumnDef, cmd->def);
3141 
3142  transformColumnDefinition(&cxt, def);
3143 
3144  /*
3145  * If the column has a non-null default, we can't skip
3146  * validation of foreign keys.
3147  */
3148  if (def->raw_default != NULL)
3149  skipValidation = false;
3150 
3151  /*
3152  * All constraints are processed in other ways. Remove the
3153  * original list
3154  */
3155  def->constraints = NIL;
3156 
3157  newcmds = lappend(newcmds, cmd);
3158  break;
3159  }
3160 
3161  case AT_AddConstraint:
3163 
3164  /*
3165  * The original AddConstraint cmd node doesn't go to newcmds
3166  */
3167  if (IsA(cmd->def, Constraint))
3168  {
3169  transformTableConstraint(&cxt, (Constraint *) cmd->def);
3170  if (((Constraint *) cmd->def)->contype == CONSTR_FOREIGN)
3171  skipValidation = false;
3172  }
3173  else
3174  elog(ERROR, "unrecognized node type: %d",
3175  (int) nodeTag(cmd->def));
3176  break;
3177 
3178  case AT_AlterColumnType:
3179  {
3180  ColumnDef *def = castNode(ColumnDef, cmd->def);
3182 
3183  /*
3184  * For ALTER COLUMN TYPE, transform the USING clause if
3185  * one was specified.
3186  */
3187  if (def->raw_default)
3188  {
3189  def->cooked_default =
3190  transformExpr(pstate, def->raw_default,
3192  }
3193 
3194  /*
3195  * For identity column, create ALTER SEQUENCE command to
3196  * change the data type of the sequence.
3197  */
3198  attnum = get_attnum(relid, cmd->name);
3199  if (attnum == InvalidAttrNumber)
3200  ereport(ERROR,
3201  (errcode(ERRCODE_UNDEFINED_COLUMN),
3202  errmsg("column \"%s\" of relation \"%s\" does not exist",
3203  cmd->name, RelationGetRelationName(rel))));
3204 
3205  if (TupleDescAttr(tupdesc, attnum - 1)->attidentity)
3206  {
3207  Oid seq_relid = getIdentitySequence(relid, attnum, false);
3208  Oid typeOid = typenameTypeId(pstate, def->typeName);
3209  AlterSeqStmt *altseqstmt = makeNode(AlterSeqStmt);
3210 
3211  altseqstmt->sequence = makeRangeVar(get_namespace_name(get_rel_namespace(seq_relid)),
3212  get_rel_name(seq_relid),
3213  -1);
3214  altseqstmt->options = list_make1(makeDefElem("as", (Node *) makeTypeNameFromOid(typeOid, -1), -1));
3215  altseqstmt->for_identity = true;
3216  cxt.blist = lappend(cxt.blist, altseqstmt);
3217  }
3218 
3219  newcmds = lappend(newcmds, cmd);
3220  break;
3221  }
3222 
3223  case AT_AddIdentity:
3224  {
3225  Constraint *def = castNode(Constraint, cmd->def);
3226  ColumnDef *newdef = makeNode(ColumnDef);
3228 
3229  newdef->colname = cmd->name;
3230  newdef->identity = def->generated_when;
3231  cmd->def = (Node *) newdef;
3232 
3233  attnum = get_attnum(relid, cmd->name);
3234  if (attnum == InvalidAttrNumber)
3235  ereport(ERROR,
3236  (errcode(ERRCODE_UNDEFINED_COLUMN),
3237  errmsg("column \"%s\" of relation \"%s\" does not exist",
3238  cmd->name, RelationGetRelationName(rel))));
3239 
3240  generateSerialExtraStmts(&cxt, newdef,
3241  get_atttype(relid, attnum),
3242  def->options, true, true,
3243  NULL, NULL);
3244 
3245  newcmds = lappend(newcmds, cmd);
3246  break;
3247  }
3248 
3249  case AT_SetIdentity:
3250  {
3251  /*
3252  * Create an ALTER SEQUENCE statement for the internal
3253  * sequence of the identity column.
3254  */
3255  ListCell *lc;
3256  List *newseqopts = NIL;
3257  List *newdef = NIL;
3259  Oid seq_relid;
3260 
3261  /*
3262  * Split options into those handled by ALTER SEQUENCE and
3263  * those for ALTER TABLE proper.
3264  */
3265  foreach(lc, castNode(List, cmd->def))
3266  {
3267  DefElem *def = lfirst_node(DefElem, lc);
3268 
3269  if (strcmp(def->defname, "generated") == 0)
3270  newdef = lappend(newdef, def);
3271  else
3272  newseqopts = lappend(newseqopts, def);
3273  }
3274 
3275  attnum = get_attnum(relid, cmd->name);
3276  if (attnum == InvalidAttrNumber)
3277  ereport(ERROR,
3278  (errcode(ERRCODE_UNDEFINED_COLUMN),
3279  errmsg("column \"%s\" of relation \"%s\" does not exist",
3280  cmd->name, RelationGetRelationName(rel))));
3281 
3282  seq_relid = getIdentitySequence(relid, attnum, true);
3283 
3284  if (seq_relid)
3285  {
3286  AlterSeqStmt *seqstmt;
3287 
3288  seqstmt = makeNode(AlterSeqStmt);
3290  get_rel_name(seq_relid), -1);
3291  seqstmt->options = newseqopts;
3292  seqstmt->for_identity = true;
3293  seqstmt->missing_ok = false;
3294 
3295  cxt.blist = lappend(cxt.blist, seqstmt);
3296  }
3297 
3298  /*
3299  * If column was not an identity column, we just let the
3300  * ALTER TABLE command error out later. (There are cases
3301  * this fails to cover, but we'll need to restructure
3302  * where creation of the sequence dependency linkage
3303  * happens before we can fix it.)
3304  */
3305 
3306  cmd->def = (Node *) newdef;
3307  newcmds = lappend(newcmds, cmd);
3308  break;
3309  }
3310 
3311  case AT_AttachPartition:
3312  case AT_DetachPartition:
3313  {
3314  PartitionCmd *partcmd = (PartitionCmd *) cmd->def;
3315 
3316  transformPartitionCmd(&cxt, partcmd);
3317  /* assign transformed value of the partition bound */
3318  partcmd->bound = cxt.partbound;
3319  }
3320 
3321  newcmds = lappend(newcmds, cmd);
3322  break;
3323 
3324  default:
3325 
3326  /*
3327  * Currently, we shouldn't actually get here for subcommand
3328  * types that don't require transformation; but if we do, just
3329  * emit them unchanged.
3330  */
3331  newcmds = lappend(newcmds, cmd);
3332  break;
3333  }
3334  }
3335 
3336  /*
3337  * Transfer anything we already have in cxt.alist into save_alist, to keep
3338  * it separate from the output of transformIndexConstraints.
3339  */
3340  save_alist = cxt.alist;
3341  cxt.alist = NIL;
3342 
3343  /* Postprocess constraints */
3345  transformFKConstraints(&cxt, skipValidation, true);
3346  transformCheckConstraints(&cxt, false);
3347 
3348  /*
3349  * Push any index-creation commands into the ALTER, so that they can be
3350  * scheduled nicely by tablecmds.c. Note that tablecmds.c assumes that
3351  * the IndexStmt attached to an AT_AddIndex or AT_AddIndexConstraint
3352  * subcommand has already been through transformIndexStmt.
3353  */
3354  foreach(l, cxt.alist)
3355  {
3356  Node *istmt = (Node *) lfirst(l);
3357 
3358  /*
3359  * We assume here that cxt.alist contains only IndexStmts and possibly
3360  * ALTER TABLE SET NOT NULL statements generated from primary key
3361  * constraints. We absorb the subcommands of the latter directly.
3362  */
3363  if (IsA(istmt, IndexStmt))
3364  {
3365  IndexStmt *idxstmt = (IndexStmt *) istmt;
3366 
3367  idxstmt = transformIndexStmt(relid, idxstmt, queryString);
3368  newcmd = makeNode(AlterTableCmd);
3370  newcmd->def = (Node *) idxstmt;
3371  newcmds = lappend(newcmds, newcmd);
3372  }
3373  else if (IsA(istmt, AlterTableStmt))
3374  {
3375  AlterTableStmt *alterstmt = (AlterTableStmt *) istmt;
3376 
3377  newcmds = list_concat(newcmds, alterstmt->cmds);
3378  }
3379  else
3380  elog(ERROR, "unexpected stmt type %d", (int) nodeTag(istmt));
3381  }
3382  cxt.alist = NIL;
3383 
3384  /* Append any CHECK or FK constraints to the commands list */
3385  foreach(l, cxt.ckconstraints)
3386  {
3387  newcmd = makeNode(AlterTableCmd);
3388  newcmd->subtype = AT_AddConstraint;
3389  newcmd->def = (Node *) lfirst(l);
3390  newcmds = lappend(newcmds, newcmd);
3391  }
3392  foreach(l, cxt.fkconstraints)
3393  {
3394  newcmd = makeNode(AlterTableCmd);
3395  newcmd->subtype = AT_AddConstraint;
3396  newcmd->def = (Node *) lfirst(l);
3397  newcmds = lappend(newcmds, newcmd);
3398  }
3399 
3400  /* Append extended statistic objects */
3402 
3403  /* Close rel */
3404  relation_close(rel, NoLock);
3405 
3406  /*
3407  * Output results.
3408  */
3409  stmt->cmds = newcmds;
3410 
3411  *beforeStmts = cxt.blist;
3412  *afterStmts = list_concat(cxt.alist, save_alist);
3413 
3414  return stmt;
3415 }
#define NIL
Definition: pg_list.h:65
#define IsA(nodeptr, _type_)
Definition: nodes.h:580
char generated_when
Definition: parsenodes.h:2164
static void generateSerialExtraStmts(CreateStmtContext *cxt, ColumnDef *column, Oid seqtypid, List *seqoptions, bool for_identity, bool col_exists, char **snamespace_p, char **sname_p)
#define RelationGetDescr(relation)
Definition: rel.h:482
#define castNode(_type_, nodeptr)
Definition: nodes.h:598
char identity
Definition: parsenodes.h:656
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
List * constraints
Definition: parsenodes.h:662
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:1864
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:145
#define AccessShareLock
Definition: lockdefs.h:36
void addNSItemToQuery(ParseState *pstate, ParseNamespaceItem *nsitem, bool addToJoinList, bool addToRelNameSpace, bool addToVarNameSpace)
Definition: nodes.h:529
List * list_concat(List *list1, const List *list2)
Definition: list.c:515
int errcode(int sqlerrcode)
Definition: elog.c:610
AlterTableType subtype
Definition: parsenodes.h:1863
Form_pg_class rd_rel
Definition: rel.h:109
unsigned int Oid
Definition: postgres_ext.h:31
Oid getIdentitySequence(Oid relid, AttrNumber attnum, bool missing_ok)
Definition: pg_depend.c:872
#define OidIsValid(objectId)
Definition: c.h:651
DefElem * makeDefElem(char *name, Node *arg, int location)
Definition: makefuncs.c:546
List * options
Definition: parsenodes.h:2556
List * options
Definition: parsenodes.h:2176
ParseNamespaceItem * addRangeTableEntryForRelation(ParseState *pstate, Relation rel, int lockmode, Alias *alias, bool inh, bool inFromCl)
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:43
#define list_make1(x1)
Definition: pg_list.h:227
ParseState * pstate
Definition: parse_utilcmd.c:78
Node * cooked_default
Definition: parsenodes.h:655
Oid indexOid
Definition: parsenodes.h:2786
RangeVar * relation
Definition: parse_utilcmd.c:80
IndexStmt * pkey
Definition: parse_utilcmd.c:95
#define ERROR
Definition: elog.h:43
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:48
#define lfirst_node(type, lc)
Definition: pg_list.h:193
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3191
#define NoLock
Definition: lockdefs.h:34
AttrNumber get_attnum(Oid relid, const char *attname)
Definition: lsyscache.c:856
#define RelationGetRelationName(relation)
Definition: rel.h:490
const char * p_sourcetext
Definition: parse_node.h:179
Oid get_atttype(Oid relid, AttrNumber attnum)
Definition: lsyscache.c:911
PartitionBoundSpec * partbound
Definition: parse_utilcmd.c:97
Node * raw_default
Definition: parsenodes.h:654
List * lappend(List *list, void *datum)
Definition: list.c:321
TypeName * makeTypeNameFromOid(Oid typeOid, int32 typmod)
Definition: makefuncs.c:472
RangeVar * sequence
Definition: parsenodes.h:2555
int16 attnum
Definition: pg_attribute.h:79
#define ereport(elevel,...)
Definition: elog.h:144
#define makeNode(_type_)
Definition: nodes.h:577
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:206
#define lfirst(lc)
Definition: pg_list.h:190
static void transformColumnDefinition(CreateStmtContext *cxt, ColumnDef *column)
PartitionBoundSpec * bound
Definition: parsenodes.h:861
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:534
const char * stmtType
Definition: parse_utilcmd.c:79
static void transformExtendedStatistics(CreateStmtContext *cxt)
int errmsg(const char *fmt,...)
Definition: elog.c:824
RangeVar * relation
Definition: parsenodes.h:1777
#define elog(elevel,...)
Definition: elog.h:214
bool for_identity
Definition: parsenodes.h:2557
char * defname
Definition: parsenodes.h:732
char * colname
Definition: parsenodes.h:647
#define copyObject(obj)
Definition: nodes.h:645
static void transformTableConstraint(CreateStmtContext *cxt, Constraint *constraint)
static void transformIndexConstraints(CreateStmtContext *cxt)
IndexStmt * transformIndexStmt(Oid relid, IndexStmt *stmt, const char *queryString)
Definition: pg_list.h:50
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1840
int16 AttrNumber
Definition: attnum.h:21
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition: makefuncs.c:422
static void transformCheckConstraints(CreateStmtContext *cxt, bool skipValidation)
Oid typenameTypeId(ParseState *pstate, const TypeName *typeName)
Definition: parse_type.c:291

◆ transformCheckConstraints()

static void transformCheckConstraints ( CreateStmtContext cxt,
bool  skipValidation 
)
static

Definition at line 2543 of file parse_utilcmd.c.

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

Referenced by transformAlterTableStmt(), and transformCreateStmt().

2544 {
2545  ListCell *ckclist;
2546 
2547  if (cxt->ckconstraints == NIL)
2548  return;
2549 
2550  /*
2551  * If creating a new table (but not a foreign table), we can safely skip
2552  * validation of check constraints, and nonetheless mark them valid. (This
2553  * will override any user-supplied NOT VALID flag.)
2554  */
2555  if (skipValidation)
2556  {
2557  foreach(ckclist, cxt->ckconstraints)
2558  {
2559  Constraint *constraint = (Constraint *) lfirst(ckclist);
2560 
2561  constraint->skip_validation = true;
2562  constraint->initially_valid = true;
2563  }
2564  }
2565 }
#define NIL
Definition: pg_list.h:65
bool initially_valid
Definition: parsenodes.h:2198
#define lfirst(lc)
Definition: pg_list.h:190
bool skip_validation
Definition: parsenodes.h:2197

◆ transformColumnDefinition()

static void transformColumnDefinition ( CreateStmtContext cxt,
ColumnDef column 
)
static

Definition at line 509 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_GENERATED, 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, ColumnDef::generated, Constraint::generated_when, generateSerialExtraStmts(), GETSTRUCT, 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, AlterTableStmt::objtype, 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(), RangeVar::relname, Value::ValUnion::str, strVal, AlterTableCmd::subtype, SystemFuncName(), SystemTypeName(), T_String, transformColumnType(), transformConstraintAttrs(), Value::type, TypeCast::typeName, ColumnDef::typeName, typenameType(), TypeName::typeOid, typname, Value::val, and A_Const::val.

Referenced by transformAlterTableStmt(), and transformCreateStmt().

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

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

Referenced by transformColumnDefinition().

3544 {
3545  /*
3546  * All we really need to do here is verify that the type is valid,
3547  * including any collation spec that might be present.
3548  */
3549  Type ctype = typenameType(cxt->pstate, column->typeName, NULL);
3550 
3551  if (column->collClause)
3552  {
3553  Form_pg_type typtup = (Form_pg_type) GETSTRUCT(ctype);
3554 
3555  LookupCollation(cxt->pstate,
3556  column->collClause->collname,
3557  column->collClause->location);
3558  /* Complain if COLLATE is applied to an uncollatable type */
3559  if (!OidIsValid(typtup->typcollation))
3560  ereport(ERROR,
3561  (errcode(ERRCODE_DATATYPE_MISMATCH),
3562  errmsg("collations are not supported by type %s",
3563  format_type_be(typtup->oid)),
3565  column->collClause->location)));
3566  }
3567 
3568  ReleaseSysCache(ctype);
3569 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
Type typenameType(ParseState *pstate, const TypeName *typeName, int32 *typmod_p)
Definition: parse_type.c:264
int errcode(int sqlerrcode)
Definition: elog.c:610
char * format_type_be(Oid type_oid)
Definition: format_type.c:339
#define OidIsValid(objectId)
Definition: c.h:651
ParseState * pstate
Definition: parse_utilcmd.c:78
#define ERROR
Definition: elog.h:43
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
Oid LookupCollation(ParseState *pstate, List *collnames, int location)
Definition: parse_type.c:513
#define ereport(elevel,...)
Definition: elog.h:144
FormData_pg_type * Form_pg_type
Definition: pg_type.h:255
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110
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:824

◆ transformConstraintAttrs()

static void transformConstraintAttrs ( CreateStmtContext cxt,
List constraintList 
)
static

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

3429 {
3430  Constraint *lastprimarycon = NULL;
3431  bool saw_deferrability = false;
3432  bool saw_initially = false;
3433  ListCell *clist;
3434 
3435 #define SUPPORTS_ATTRS(node) \
3436  ((node) != NULL && \
3437  ((node)->contype == CONSTR_PRIMARY || \
3438  (node)->contype == CONSTR_UNIQUE || \
3439  (node)->contype == CONSTR_EXCLUSION || \
3440  (node)->contype == CONSTR_FOREIGN))
3441 
3442  foreach(clist, constraintList)
3443  {
3444  Constraint *con = (Constraint *) lfirst(clist);
3445 
3446  if (!IsA(con, Constraint))
3447  elog(ERROR, "unrecognized node type: %d",
3448  (int) nodeTag(con));
3449  switch (con->contype)
3450  {
3452  if (!SUPPORTS_ATTRS(lastprimarycon))
3453  ereport(ERROR,
3454  (errcode(ERRCODE_SYNTAX_ERROR),
3455  errmsg("misplaced DEFERRABLE clause"),
3456  parser_errposition(cxt->pstate, con->location)));
3457  if (saw_deferrability)
3458  ereport(ERROR,
3459  (errcode(ERRCODE_SYNTAX_ERROR),
3460  errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed"),
3461  parser_errposition(cxt->pstate, con->location)));
3462  saw_deferrability = true;
3463  lastprimarycon->deferrable = true;
3464  break;
3465 
3467  if (!SUPPORTS_ATTRS(lastprimarycon))
3468  ereport(ERROR,
3469  (errcode(ERRCODE_SYNTAX_ERROR),
3470  errmsg("misplaced NOT DEFERRABLE clause"),
3471  parser_errposition(cxt->pstate, con->location)));
3472  if (saw_deferrability)
3473  ereport(ERROR,
3474  (errcode(ERRCODE_SYNTAX_ERROR),
3475  errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed"),
3476  parser_errposition(cxt->pstate, con->location)));
3477  saw_deferrability = true;
3478  lastprimarycon->deferrable = false;
3479  if (saw_initially &&
3480  lastprimarycon->initdeferred)
3481  ereport(ERROR,
3482  (errcode(ERRCODE_SYNTAX_ERROR),
3483  errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
3484  parser_errposition(cxt->pstate, con->location)));
3485  break;
3486 
3487  case CONSTR_ATTR_DEFERRED:
3488  if (!SUPPORTS_ATTRS(lastprimarycon))
3489  ereport(ERROR,
3490  (errcode(ERRCODE_SYNTAX_ERROR),
3491  errmsg("misplaced INITIALLY DEFERRED clause"),
3492  parser_errposition(cxt->pstate, con->location)));
3493  if (saw_initially)
3494  ereport(ERROR,
3495  (errcode(ERRCODE_SYNTAX_ERROR),
3496  errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed"),
3497  parser_errposition(cxt->pstate, con->location)));
3498  saw_initially = true;
3499  lastprimarycon->initdeferred = true;
3500 
3501  /*
3502  * If only INITIALLY DEFERRED appears, assume DEFERRABLE
3503  */
3504  if (!saw_deferrability)
3505  lastprimarycon->deferrable = true;
3506  else if (!lastprimarycon->deferrable)
3507  ereport(ERROR,
3508  (errcode(ERRCODE_SYNTAX_ERROR),
3509  errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
3510  parser_errposition(cxt->pstate, con->location)));
3511  break;
3512 
3513  case CONSTR_ATTR_IMMEDIATE:
3514  if (!SUPPORTS_ATTRS(lastprimarycon))
3515  ereport(ERROR,
3516  (errcode(ERRCODE_SYNTAX_ERROR),
3517  errmsg("misplaced INITIALLY IMMEDIATE clause"),
3518  parser_errposition(cxt->pstate, con->location)));
3519  if (saw_initially)
3520  ereport(ERROR,
3521  (errcode(ERRCODE_SYNTAX_ERROR),
3522  errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed"),
3523  parser_errposition(cxt->pstate, con->location)));
3524  saw_initially = true;
3525  lastprimarycon->initdeferred = false;
3526  break;
3527 
3528  default:
3529  /* Otherwise it's not an attribute */
3530  lastprimarycon = con;
3531  /* reset flags for new primary node */
3532  saw_deferrability = false;
3533  saw_initially = false;
3534  break;
3535  }
3536  }
3537 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:580
int errcode(int sqlerrcode)
Definition: elog.c:610
bool initdeferred
Definition: parsenodes.h:2157
ParseState * pstate
Definition: parse_utilcmd.c:78
#define ERROR
Definition: elog.h:43
bool deferrable
Definition: parsenodes.h:2156
#define ereport(elevel,...)
Definition: elog.h:144
#define lfirst(lc)
Definition: pg_list.h:190
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110
#define nodeTag(nodeptr)
Definition: nodes.h:534
int errmsg(const char *fmt,...)
Definition: elog.c:824
#define SUPPORTS_ATTRS(node)
#define elog(elevel,...)
Definition: elog.h:214
ConstrType contype
Definition: parsenodes.h:2152

◆ transformCreateSchemaStmt()

List* transformCreateSchemaStmt ( CreateSchemaStmt stmt)

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

3597 {
3599  List *result;
3600  ListCell *elements;
3601 
3602  cxt.stmtType = "CREATE SCHEMA";
3603  cxt.schemaname = stmt->schemaname;
3604  cxt.authrole = (RoleSpec *) stmt->authrole;
3605  cxt.sequences = NIL;
3606  cxt.tables = NIL;
3607  cxt.views = NIL;
3608  cxt.indexes = NIL;
3609  cxt.triggers = NIL;
3610  cxt.grants = NIL;
3611 
3612  /*
3613  * Run through each schema element in the schema element list. Separate
3614  * statements by type, and do preliminary analysis.
3615  */
3616  foreach(elements, stmt->schemaElts)
3617  {
3618  Node *element = lfirst(elements);
3619 
3620  switch (nodeTag(element))
3621  {
3622  case T_CreateSeqStmt:
3623  {
3624  CreateSeqStmt *elp = (CreateSeqStmt *) element;
3625 
3627  cxt.sequences = lappend(cxt.sequences, element);
3628  }
3629  break;
3630 
3631  case T_CreateStmt:
3632  {
3633  CreateStmt *elp = (CreateStmt *) element;
3634 
3636 
3637  /*
3638  * XXX todo: deal with constraints
3639  */
3640  cxt.tables = lappend(cxt.tables, element);
3641  }
3642  break;
3643 
3644  case T_ViewStmt:
3645  {
3646  ViewStmt *elp = (ViewStmt *) element;
3647 
3648  setSchemaName(cxt.schemaname, &elp->view->schemaname);
3649 
3650  /*
3651  * XXX todo: deal with references between views
3652  */
3653  cxt.views = lappend(cxt.views, element);
3654  }
3655  break;
3656 
3657  case T_IndexStmt:
3658  {
3659  IndexStmt *elp = (IndexStmt *) element;
3660 
3662  cxt.indexes = lappend(cxt.indexes, element);
3663  }
3664  break;
3665 
3666  case T_CreateTrigStmt:
3667  {
3668  CreateTrigStmt *elp = (CreateTrigStmt *) element;
3669 
3671  cxt.triggers = lappend(cxt.triggers, element);
3672  }
3673  break;
3674 
3675  case T_GrantStmt:
3676  cxt.grants = lappend(cxt.grants, element);
3677  break;
3678 
3679  default:
3680  elog(ERROR, "unrecognized node type: %d",
3681  (int) nodeTag(element));
3682  }
3683  }
3684 
3685  result = NIL;
3686  result = list_concat(result, cxt.sequences);
3687  result = list_concat(result, cxt.tables);
3688  result = list_concat(result, cxt.views);
3689  result = list_concat(result, cxt.indexes);
3690  result = list_concat(result, cxt.triggers);
3691  result = list_concat(result, cxt.grants);
3692 
3693  return result;
3694 }
RangeVar * relation
Definition: parsenodes.h:2072
#define NIL
Definition: pg_list.h:65
Definition: nodes.h:529
List * list_concat(List *list1, const List *list2)
Definition: list.c:515
RangeVar * view
Definition: parsenodes.h:3128
char * schemaname
Definition: primnodes.h:67
RangeVar * relation
Definition: parsenodes.h:2776
RoleSpec * authrole
Definition: parsenodes.h:1759
#define ERROR
Definition: elog.h:43
List * lappend(List *list, void *datum)
Definition: list.c:321
static chr element(struct vars *v, const chr *startp, const chr *endp)
Definition: regc_locale.c:380
RangeVar * sequence
Definition: parsenodes.h:2545
#define lfirst(lc)
Definition: pg_list.h:190
static void setSchemaName(char *context_schema, char **stmt_schema_name)
#define nodeTag(nodeptr)
Definition: nodes.h:534
#define elog(elevel,...)
Definition: elog.h:214
RangeVar * relation
Definition: parsenodes.h:2431
Definition: pg_list.h:50

◆ transformCreateStmt()

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

Definition at line 165 of file parse_utilcmd.c.

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

Referenced by ProcessUtilitySlow().

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

◆ transformExtendedStatistics()

static void transformExtendedStatistics ( CreateStmtContext cxt)
static

Definition at line 2528 of file parse_utilcmd.c.

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

Referenced by transformAlterTableStmt(), and transformCreateStmt().

2529 {
2530  cxt->alist = list_concat(cxt->alist, cxt->extstats);
2531 }
List * list_concat(List *list1, const List *list2)
Definition: list.c:515

◆ transformFKConstraints()

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

Definition at line 2572 of file parse_utilcmd.c.

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

Referenced by transformAlterTableStmt(), and transformCreateStmt().

2574 {
2575  ListCell *fkclist;
2576 
2577  if (cxt->fkconstraints == NIL)
2578  return;
2579 
2580  /*
2581  * If CREATE TABLE or adding a column with NULL default, we can safely
2582  * skip validation of FK constraints, and nonetheless mark them valid.
2583  * (This will override any user-supplied NOT VALID flag.)
2584  */
2585  if (skipValidation)
2586  {
2587  foreach(fkclist, cxt->fkconstraints)
2588  {
2589  Constraint *constraint = (Constraint *) lfirst(fkclist);
2590 
2591  constraint->skip_validation = true;
2592  constraint->initially_valid = true;
2593  }
2594  }
2595 
2596  /*
2597  * For CREATE TABLE or ALTER TABLE ADD COLUMN, gin up an ALTER TABLE ADD
2598  * CONSTRAINT command to execute after the basic command is complete. (If
2599  * called from ADD CONSTRAINT, that routine will add the FK constraints to
2600  * its own subcommand list.)
2601  *
2602  * Note: the ADD CONSTRAINT command must also execute after any index
2603  * creation commands. Thus, this should run after
2604  * transformIndexConstraints, so that the CREATE INDEX commands are
2605  * already in cxt->alist.
2606  */
2607  if (!isAddConstraint)
2608  {
2609  AlterTableStmt *alterstmt = makeNode(AlterTableStmt);
2610 
2611  alterstmt->relation = cxt->relation;
2612  alterstmt->cmds = NIL;
2613  alterstmt->objtype = OBJECT_TABLE;
2614 
2615  foreach(fkclist, cxt->fkconstraints)
2616  {
2617  Constraint *constraint = (Constraint *) lfirst(fkclist);
2618  AlterTableCmd *altercmd = makeNode(AlterTableCmd);
2619 
2620  altercmd->subtype = AT_AddConstraint;
2621  altercmd->name = NULL;
2622  altercmd->def = (Node *) constraint;
2623  alterstmt->cmds = lappend(alterstmt->cmds, altercmd);
2624  }
2625 
2626  cxt->alist = lappend(cxt->alist, alterstmt);
2627  }
2628 }
#define NIL
Definition: pg_list.h:65
Definition: nodes.h:529
AlterTableType subtype
Definition: parsenodes.h:1863
RangeVar * relation
Definition: parse_utilcmd.c:80
ObjectType objtype
Definition: parsenodes.h:1779
List * lappend(List *list, void *datum)
Definition: list.c:321
bool initially_valid
Definition: parsenodes.h:2198
#define makeNode(_type_)
Definition: nodes.h:577
#define lfirst(lc)
Definition: pg_list.h:190
RangeVar * relation
Definition: parsenodes.h:1777
bool skip_validation
Definition: parsenodes.h:2197

◆ transformIndexConstraint()

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

Definition at line 1994 of file parse_utilcmd.c.

References Constraint::access_method, IndexStmt::accessMethod, AccessShareLock, CreateStmtContext::alist, Assert, AT_SetNotNull, attname, attnum, castNode, AlterTableStmt::cmds, IndexElem::collation, ColumnDef::colname, CreateStmtContext::columns, IndexStmt::concurrent, Constraint::conname, CONSTR_EXCLUSION, CONSTR_PRIMARY, CONSTR_UNIQUE, Constraint::contype, copyObject, DatumGetPointer, DEFAULT_INDEX_TYPE, Constraint::deferrable, IndexStmt::deferrable, ereport, errcode(), errdetail(), errmsg(), ERROR, IndexStmt::excludeOpNames, Constraint::exclusions, IndexElem::expr, FormData_pg_attribute, get_attoptions(), get_index_am_oid(), get_index_constraint(), get_relname_relid(), GetDefaultOpClass(), i, IndexStmt::idxcomment, IndexStmt::idxname, IndexStmt::if_not_exists, Constraint::including, index_open(), IndexElem::indexcolname, IndexStmt::indexIncludingParams, Constraint::indexname, IndexStmt::indexOid, IndexStmt::indexParams, INDEXRELID, Constraint::indexspace, CreateStmtContext::inhRelations, Constraint::initdeferred, IndexStmt::initdeferred, InvalidOid, InvalidSubTransactionId, ColumnDef::is_from_type, ColumnDef::is_not_null, CreateStmtContext::isalter, IndexStmt::isconstraint, sort-test::key, Constraint::keys, lappend(), lfirst, lfirst_node, linitial_node, list_length(), Constraint::location, lsecond_node, makeNode, makeString(), AlterTableStmt::missing_ok, IndexElem::name, AlterTableCmd::name, NameStr, TupleDescData::natts, NIL, NoLock, IndexElem::nulls_ordering, OBJECT_TABLE, AlterTableStmt::objtype, OidIsValid, IndexStmt::oldCreateSubid, IndexStmt::oldFirstRelfilenodeSubid, IndexStmt::oldNode, IndexElem::opclass, IndexElem::opclassopts, Constraint::options, IndexStmt::options, IndexElem::ordering, parser_errposition(), CreateStmtContext::pkey, IndexStmt::primary, CreateStmtContext::pstate, pstrdup(), RelationData::rd_att, RelationData::rd_indcollation, RelationData::rd_index, RelationData::rd_indextuple, RelationData::rd_indoption, RelationData::rd_rel, CreateStmtContext::rel, CreateStmtContext::relation, AlterTableStmt::relation, IndexStmt::relation, relation_close(), RelationGetIndexExpressions(), RelationGetIndexPredicate(), RelationGetNamespace, RelationGetRelationName, RelationGetRelid, RangeVar::relname, Constraint::reset_default_tblspc, IndexStmt::reset_default_tblspc, SORTBY_DEFAULT, SORTBY_NULLS_DEFAULT, strVal, AlterTableCmd::subtype, SysCacheGetAttr(), SystemAttributeByName(), SystemAttributeDefinition(), table_close(), table_openrv(), IndexStmt::tableSpace, IndexStmt::transformed, TupleDescAttr, IndexStmt::unique, oidvector::values, Constraint::where_clause, and IndexStmt::whereClause.

Referenced by transformIndexConstraints().

1995 {
1996  IndexStmt *index;
1997  List *notnullcmds = NIL;
1998  ListCell *lc;
1999 
2000  index = makeNode(IndexStmt);
2001 
2002  index->unique = (constraint->contype != CONSTR_EXCLUSION);
2003  index->primary = (constraint->contype == CONSTR_PRIMARY);
2004  if (index->primary)
2005  {
2006  if (cxt->pkey != NULL)
2007  ereport(ERROR,
2008  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
2009  errmsg("multiple primary keys for table \"%s\" are not allowed",
2010  cxt->relation->relname),
2011  parser_errposition(cxt->pstate, constraint->location)));
2012  cxt->pkey = index;
2013 
2014  /*
2015  * In ALTER TABLE case, a primary index might already exist, but
2016  * DefineIndex will check for it.
2017  */
2018  }
2019  index->isconstraint = true;
2020  index->deferrable = constraint->deferrable;
2021  index->initdeferred = constraint->initdeferred;
2022 
2023  if (constraint->conname != NULL)
2024  index->idxname = pstrdup(constraint->conname);
2025  else
2026  index->idxname = NULL; /* DefineIndex will choose name */
2027 
2028  index->relation = cxt->relation;
2029  index->accessMethod = constraint->access_method ? constraint->access_method : DEFAULT_INDEX_TYPE;
2030  index->options = constraint->options;
2031  index->tableSpace = constraint->indexspace;
2032  index->whereClause = constraint->where_clause;
2033  index->indexParams = NIL;
2034  index->indexIncludingParams = NIL;
2035  index->excludeOpNames = NIL;
2036  index->idxcomment = NULL;
2037  index->indexOid = InvalidOid;
2038  index->oldNode = InvalidOid;
2041  index->transformed = false;
2042  index->concurrent = false;
2043  index->if_not_exists = false;
2044  index->reset_default_tblspc = constraint->reset_default_tblspc;
2045 
2046  /*
2047  * If it's ALTER TABLE ADD CONSTRAINT USING INDEX, look up the index and
2048  * verify it's usable, then extract the implied column name list. (We
2049  * will not actually need the column name list at runtime, but we need it
2050  * now to check for duplicate column entries below.)
2051  */
2052  if (constraint->indexname != NULL)
2053  {
2054  char *index_name = constraint->indexname;
2055  Relation heap_rel = cxt->rel;
2056  Oid index_oid;
2057  Relation index_rel;
2058  Form_pg_index index_form;
2059  oidvector *indclass;
2060  Datum indclassDatum;
2061  bool isnull;
2062  int i;
2063 
2064  /* Grammar should not allow this with explicit column list */
2065  Assert(constraint->keys == NIL);
2066 
2067  /* Grammar should only allow PRIMARY and UNIQUE constraints */
2068  Assert(constraint->contype == CONSTR_PRIMARY ||
2069  constraint->contype == CONSTR_UNIQUE);
2070 
2071  /* Must be ALTER, not CREATE, but grammar doesn't enforce that */
2072  if (!cxt->isalter)
2073  ereport(ERROR,
2074  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2075  errmsg("cannot use an existing index in CREATE TABLE"),
2076  parser_errposition(cxt->pstate, constraint->location)));
2077 
2078  /* Look for the index in the same schema as the table */
2079  index_oid = get_relname_relid(index_name, RelationGetNamespace(heap_rel));
2080 
2081  if (!OidIsValid(index_oid))
2082  ereport(ERROR,
2083  (errcode(ERRCODE_UNDEFINED_OBJECT),
2084  errmsg("index \"%s\" does not exist", index_name),
2085  parser_errposition(cxt->pstate, constraint->location)));
2086 
2087  /* Open the index (this will throw an error if it is not an index) */
2088  index_rel = index_open(index_oid, AccessShareLock);
2089  index_form = index_rel->rd_index;
2090 
2091  /* Check that it does not have an associated constraint already */
2092  if (OidIsValid(get_index_constraint(index_oid)))
2093  ereport(ERROR,
2094  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2095  errmsg("index \"%s\" is already associated with a constraint",
2096  index_name),
2097  parser_errposition(cxt->pstate, constraint->location)));
2098 
2099  /* Perform validity checks on the index */
2100  if (index_form->indrelid != RelationGetRelid(heap_rel))
2101  ereport(ERROR,
2102  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2103  errmsg("index \"%s\" does not belong to table \"%s\"",
2104  index_name, RelationGetRelationName(heap_rel)),
2105  parser_errposition(cxt->pstate, constraint->location)));
2106 
2107  if (!index_form->indisvalid)
2108  ereport(ERROR,
2109  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2110  errmsg("index \"%s\" is not valid", index_name),
2111  parser_errposition(cxt->pstate, constraint->location)));
2112 
2113  if (!index_form->indisunique)
2114  ereport(ERROR,
2115  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2116  errmsg("\"%s\" is not a unique index", index_name),
2117  errdetail("Cannot create a primary key or unique constraint using such an index."),
2118  parser_errposition(cxt->pstate, constraint->location)));
2119 
2120  if (RelationGetIndexExpressions(index_rel) != NIL)
2121  ereport(ERROR,
2122  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2123  errmsg("index \"%s\" contains expressions", index_name),
2124  errdetail("Cannot create a primary key or unique constraint using such an index."),
2125  parser_errposition(cxt->pstate, constraint->location)));
2126 
2127  if (RelationGetIndexPredicate(index_rel) != NIL)
2128  ereport(ERROR,
2129  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2130  errmsg("\"%s\" is a partial index", index_name),
2131  errdetail("Cannot create a primary key or unique constraint using such an index."),
2132  parser_errposition(cxt->pstate, constraint->location)));
2133 
2134  /*
2135  * It's probably unsafe to change a deferred index to non-deferred. (A
2136  * non-constraint index couldn't be deferred anyway, so this case
2137  * should never occur; no need to sweat, but let's check it.)
2138  */
2139  if (!index_form->indimmediate && !constraint->deferrable)
2140  ereport(ERROR,
2141  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2142  errmsg("\"%s\" is a deferrable index", index_name),
2143  errdetail("Cannot create a non-deferrable constraint using a deferrable index."),
2144  parser_errposition(cxt->pstate, constraint->location)));
2145 
2146  /*
2147  * Insist on it being a btree. That's the only kind that supports
2148  * uniqueness at the moment anyway; but we must have an index that
2149  * exactly matches what you'd get from plain ADD CONSTRAINT syntax,
2150  * else dump and reload will produce a different index (breaking
2151  * pg_upgrade in particular).
2152  */
2153  if (index_rel->rd_rel->relam != get_index_am_oid(DEFAULT_INDEX_TYPE, false))
2154  ereport(ERROR,
2155  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2156  errmsg("index \"%s\" is not a btree", index_name),
2157  parser_errposition(cxt->pstate, constraint->location)));
2158 
2159  /* Must get indclass the hard way */
2160  indclassDatum = SysCacheGetAttr(INDEXRELID, index_rel->rd_indextuple,
2161  Anum_pg_index_indclass, &isnull);
2162  Assert(!isnull);
2163  indclass = (oidvector *) DatumGetPointer(indclassDatum);
2164 
2165  for (i = 0; i < index_form->indnatts; i++)
2166  {
2167  int16 attnum = index_form->indkey.values[i];
2168  const FormData_pg_attribute *attform;
2169  char *attname;
2170  Oid defopclass;
2171 
2172  /*
2173  * We shouldn't see attnum == 0 here, since we already rejected
2174  * expression indexes. If we do, SystemAttributeDefinition will
2175  * throw an error.
2176  */
2177  if (attnum > 0)
2178  {
2179  Assert(attnum <= heap_rel->rd_att->natts);
2180  attform = TupleDescAttr(heap_rel->rd_att, attnum - 1);
2181  }
2182  else
2183  attform = SystemAttributeDefinition(attnum);
2184  attname = pstrdup(NameStr(attform->attname));
2185 
2186  if (i < index_form->indnkeyatts)
2187  {
2188  /*
2189  * Insist on default opclass, collation, and sort options.
2190  * While the index would still work as a constraint with
2191  * non-default settings, it might not provide exactly the same
2192  * uniqueness semantics as you'd get from a normally-created
2193  * constraint; and there's also the dump/reload problem
2194  * mentioned above.
2195  */
2196  Datum attoptions =
2197  get_attoptions(RelationGetRelid(index_rel), i + 1);
2198 
2199  defopclass = GetDefaultOpClass(attform->atttypid,
2200  index_rel->rd_rel->relam);
2201  if (indclass->values[i] != defopclass ||
2202  attform->attcollation != index_rel->rd_indcollation[i] ||
2203  attoptions != (Datum) 0 ||
2204  index_rel->rd_indoption[i] != 0)
2205  ereport(ERROR,
2206  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2207  errmsg("index \"%s\" column number %d does not have default sorting behavior", index_name, i + 1),
2208  errdetail("Cannot create a primary key or unique constraint using such an index."),
2209  parser_errposition(cxt->pstate, constraint->location)));
2210 
2211  constraint->keys = lappend(constraint->keys, makeString(attname));
2212  }
2213  else
2214  constraint->including = lappend(constraint->including, makeString(attname));
2215  }
2216 
2217  /* Close the index relation but keep the lock */
2218  relation_close(index_rel, NoLock);
2219 
2220  index->indexOid = index_oid;
2221  }
2222 
2223  /*
2224  * If it's an EXCLUDE constraint, the grammar returns a list of pairs of
2225  * IndexElems and operator names. We have to break that apart into
2226  * separate lists.
2227  */
2228  if (constraint->contype == CONSTR_EXCLUSION)
2229  {
2230  foreach(lc, constraint->exclusions)
2231  {
2232  List *pair = (List *) lfirst(lc);
2233  IndexElem *elem;
2234  List *opname;
2235 
2236  Assert(list_length(pair) == 2);
2237  elem = linitial_node(IndexElem, pair);
2238  opname = lsecond_node(List, pair);
2239 
2240  index->indexParams = lappend(index->indexParams, elem);
2241  index->excludeOpNames = lappend(index->excludeOpNames, opname);
2242  }
2243  }
2244 
2245  /*
2246  * For UNIQUE and PRIMARY KEY, we just have a list of column names.
2247  *
2248  * Make sure referenced keys exist. If we are making a PRIMARY KEY index,
2249  * also make sure they are NOT NULL.
2250  */
2251  else
2252  {
2253  foreach(lc, constraint->keys)
2254  {
2255  char *key = strVal(lfirst(lc));
2256  bool found = false;
2257  bool forced_not_null = false;
2258  ColumnDef *column = NULL;
2259  ListCell *columns;
2260  IndexElem *iparam;
2261 
2262  /* Make sure referenced column exists. */
2263  foreach(columns, cxt->columns)
2264  {
2265  column = castNode(ColumnDef, lfirst(columns));
2266  if (strcmp(column->colname, key) == 0)
2267  {
2268  found = true;
2269  break;
2270  }
2271  }
2272  if (found)
2273  {
2274  /*
2275  * column is defined in the new table. For PRIMARY KEY, we
2276  * can apply the NOT NULL constraint cheaply here ... unless
2277  * the column is marked is_from_type, in which case marking it
2278  * here would be ineffective (see MergeAttributes).
2279  */
2280  if (constraint->contype == CONSTR_PRIMARY &&
2281  !column->is_from_type)
2282  {
2283  column->is_not_null = true;
2284  forced_not_null = true;
2285  }
2286  }
2287  else if (SystemAttributeByName(key) != NULL)
2288  {
2289  /*
2290  * column will be a system column in the new table, so accept
2291  * it. System columns can't ever be null, so no need to worry
2292  * about PRIMARY/NOT NULL constraint.
2293  */
2294  found = true;
2295  }
2296  else if (cxt->inhRelations)
2297  {
2298  /* try inherited tables */
2299  ListCell *inher;
2300 
2301  foreach(inher, cxt->inhRelations)
2302  {
2303  RangeVar *inh = castNode(RangeVar, lfirst(inher));
2304  Relation rel;
2305  int count;
2306 
2307  rel = table_openrv(inh, AccessShareLock);
2308  /* check user requested inheritance from valid relkind */
2309  if (rel->rd_rel->relkind != RELKIND_RELATION &&
2310  rel->rd_rel->relkind != RELKIND_FOREIGN_TABLE &&
2311  rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
2312  ereport(ERROR,
2313  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2314  errmsg("inherited relation \"%s\" is not a table or foreign table",
2315  inh->relname)));
2316  for (count = 0; count < rel->rd_att->natts; count++)
2317  {
2318  Form_pg_attribute inhattr = TupleDescAttr(rel->rd_att,
2319  count);
2320  char *inhname = NameStr(inhattr->attname);
2321 
2322  if (inhattr->attisdropped)
2323  continue;
2324  if (strcmp(key, inhname) == 0)
2325  {
2326  found = true;
2327 
2328  /*
2329  * It's tempting to set forced_not_null if the
2330  * parent column is already NOT NULL, but that
2331  * seems unsafe because the column's NOT NULL
2332  * marking might disappear between now and
2333  * execution. Do the runtime check to be safe.
2334  */
2335  break;
2336  }
2337  }
2338  table_close(rel, NoLock);
2339  if (found)
2340  break;
2341  }
2342  }
2343 
2344  /*
2345  * In the ALTER TABLE case, don't complain about index keys not
2346  * created in the command; they may well exist already.
2347  * DefineIndex will complain about them if not.
2348  */
2349  if (!found && !cxt->isalter)
2350  ereport(ERROR,
2351  (errcode(ERRCODE_UNDEFINED_COLUMN),
2352  errmsg("column \"%s\" named in key does not exist", key),
2353  parser_errposition(cxt->pstate, constraint->location)));
2354 
2355  /* Check for PRIMARY KEY(foo, foo) */
2356  foreach(columns, index->indexParams)
2357  {
2358  iparam = (IndexElem *) lfirst(columns);
2359  if (iparam->name && strcmp(key, iparam->name) == 0)
2360  {
2361  if (index->primary)
2362  ereport(ERROR,
2363  (errcode(ERRCODE_DUPLICATE_COLUMN),
2364  errmsg("column \"%s\" appears twice in primary key constraint",
2365  key),
2366  parser_errposition(cxt->pstate, constraint->location)));
2367  else
2368  ereport(ERROR,
2369  (errcode(ERRCODE_DUPLICATE_COLUMN),
2370  errmsg("column \"%s\" appears twice in unique constraint",
2371  key),
2372  parser_errposition(cxt->pstate, constraint->location)));
2373  }
2374  }
2375 
2376  /* OK, add it to the index definition */
2377  iparam = makeNode(IndexElem);
2378  iparam->name = pstrdup(key);
2379  iparam->expr = NULL;
2380  iparam->indexcolname = NULL;
2381  iparam->collation = NIL;
2382  iparam->opclass = NIL;
2383  iparam->opclassopts = NIL;
2384  iparam->ordering = SORTBY_DEFAULT;
2386  index->indexParams = lappend(index->indexParams, iparam);
2387 
2388  /*
2389  * For a primary-key column, also create an item for ALTER TABLE
2390  * SET NOT NULL if we couldn't ensure it via is_not_null above.
2391  */
2392  if (constraint->contype == CONSTR_PRIMARY && !forced_not_null)
2393  {
2394  AlterTableCmd *notnullcmd = makeNode(AlterTableCmd);
2395 
2396  notnullcmd->subtype = AT_SetNotNull;
2397  notnullcmd->name = pstrdup(key);
2398  notnullcmds = lappend(notnullcmds, notnullcmd);
2399  }
2400  }
2401  }
2402 
2403  /*
2404  * Add included columns to index definition. This is much like the
2405  * simple-column-name-list code above, except that we don't worry about
2406  * NOT NULL marking; included columns in a primary key should not be
2407  * forced NOT NULL. We don't complain about duplicate columns, either,
2408  * though maybe we should?
2409  */
2410  foreach(lc, constraint->including)
2411  {
2412  char *key = strVal(lfirst(lc));
2413  bool found = false;
2414  ColumnDef *column = NULL;
2415  ListCell *columns;
2416  IndexElem *iparam;
2417 
2418  foreach(columns, cxt->columns)
2419  {
2420  column = lfirst_node(ColumnDef, columns);
2421  if (strcmp(column->colname, key) == 0)
2422  {
2423  found = true;
2424  break;
2425  }
2426  }
2427 
2428  if (!found)
2429  {
2430  if (SystemAttributeByName(key) != NULL)
2431  {
2432  /*
2433  * column will be a system column in the new table, so accept
2434  * it.
2435  */
2436  found = true;
2437  }
2438  else if (cxt->inhRelations)
2439  {
2440  /* try inherited tables */
2441  ListCell *inher;
2442 
2443  foreach(inher, cxt->inhRelations)
2444  {
2445  RangeVar *inh = lfirst_node(RangeVar, inher);
2446  Relation rel;
2447  int count;
2448 
2449  rel = table_openrv(inh, AccessShareLock);
2450  /* check user requested inheritance from valid relkind */
2451  if (rel->rd_rel->relkind != RELKIND_RELATION &&
2452  rel->rd_rel->relkind != RELKIND_FOREIGN_TABLE &&
2453  rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
2454  ereport(ERROR,
2455  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2456  errmsg("inherited relation \"%s\" is not a table or foreign table",
2457  inh->relname)));
2458  for (count = 0; count < rel->rd_att->natts; count++)
2459  {
2460  Form_pg_attribute inhattr = TupleDescAttr(rel->rd_att,
2461  count);
2462  char *inhname = NameStr(inhattr->attname);
2463 
2464  if (inhattr->attisdropped)
2465  continue;
2466  if (strcmp(key, inhname) == 0)
2467  {
2468  found = true;
2469  break;
2470  }
2471  }
2472  table_close(rel, NoLock);
2473  if (found)
2474  break;
2475  }
2476  }
2477  }
2478 
2479  /*
2480  * In the ALTER TABLE case, don't complain about index keys not
2481  * created in the command; they may well exist already. DefineIndex
2482  * will complain about them if not.
2483  */
2484  if (!found && !cxt->isalter)
2485  ereport(ERROR,
2486  (errcode(ERRCODE_UNDEFINED_COLUMN),
2487  errmsg("column \"%s\" named in key does not exist", key),
2488  parser_errposition(cxt->pstate, constraint->location)));
2489 
2490  /* OK, add it to the index definition */
2491  iparam = makeNode(IndexElem);
2492  iparam->name = pstrdup(key);
2493  iparam->expr = NULL;
2494  iparam->indexcolname = NULL;
2495  iparam->collation = NIL;
2496  iparam->opclass = NIL;
2497  iparam->opclassopts = NIL;
2498  index->indexIncludingParams = lappend(index->indexIncludingParams, iparam);
2499  }
2500 
2501  /*
2502  * If we found anything that requires run-time SET NOT NULL, build a full
2503  * ALTER TABLE command for that and add it to cxt->alist.
2504  */
2505  if (notnullcmds)
2506  {
2507  AlterTableStmt *alterstmt = makeNode(AlterTableStmt);
2508 
2509  alterstmt->relation = copyObject(cxt->relation);
2510  alterstmt->cmds = notnullcmds;
2511  alterstmt->objtype = OBJECT_TABLE;
2512  alterstmt->missing_ok = false;
2513 
2514  cxt->alist = lappend(cxt->alist, alterstmt);
2515  }
2516 
2517  return index;
2518 }
bool deferrable
Definition: parsenodes.h:2794
Value * makeString(char *str)
Definition: value.c:53
signed short int16
Definition: c.h:361
#define NIL
Definition: pg_list.h:65
Definition: c.h:601
bool primary
Definition: parsenodes.h:2792
List * keys
Definition: parsenodes.h:2167
List * exclusions
Definition: parsenodes.h:2173
int16 * rd_indoption
Definition: rel.h:193
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
Oid GetDefaultOpClass(Oid type_id, Oid am_id)
Definition: indexcmds.c:2045
SortByDir ordering
Definition: parsenodes.h:706
List * options
Definition: parsenodes.h:2782
SubTransactionId oldCreateSubid
Definition: parsenodes.h:2788
#define castNode(_type_, nodeptr)
Definition: nodes.h:598
char * tableSpace
Definition: parsenodes.h:2778
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
char * pstrdup(const char *in)
Definition: mcxt.c:1186
Node * whereClause
Definition: parsenodes.h:2783
#define AccessShareLock
Definition: lockdefs.h:36
#define strVal(v)
Definition: value.h:54
int errcode(int sqlerrcode)
Definition: elog.c:610
bool initdeferred
Definition: parsenodes.h:2157
AlterTableType subtype
Definition: parsenodes.h:1863
char * conname
Definition: parsenodes.h:2155
bool is_not_null
Definition: parsenodes.h:651
Form_pg_class rd_rel
Definition: rel.h:109
unsigned int Oid
Definition: postgres_ext.h:31
#define linitial_node(type, l)
Definition: pg_list.h:198
#define OidIsValid(objectId)
Definition: c.h:651
List * opclassopts
Definition: parsenodes.h:705
List * options
Definition: parsenodes.h:2176
List * RelationGetIndexPredicate(Relation relation)
Definition: relcache.c:4854
struct HeapTupleData * rd_indextuple
Definition: rel.h:176
List * indexIncludingParams
Definition: parsenodes.h:2780
Definition: type.h:89
const FormData_pg_attribute * SystemAttributeDefinition(AttrNumber attno)
Definition: heap.c:249
ParseState * pstate
Definition: parse_utilcmd.c:78
char * relname
Definition: primnodes.h:68
Oid indexOid
Definition: parsenodes.h:2786
Node * expr
Definition: parsenodes.h:701
RangeVar * relation
Definition: parse_utilcmd.c:80
RangeVar * relation
Definition: parsenodes.h:2776
IndexStmt * pkey
Definition: parse_utilcmd.c:95
Datum get_attoptions(Oid relid, int16 attnum)
Definition: lsyscache.c:968
Form_pg_index rd_index
Definition: rel.h:174
Oid * rd_indcollation
Definition: rel.h:199
SortByNulls nulls_ordering
Definition: parsenodes.h:707
#define ERROR
Definition: elog.h:43
NameData attname
Definition: pg_attribute.h:40
bool deferrable
Definition: parsenodes.h:2156
Oid get_relname_relid(const char *relname, Oid relnamespace)
Definition: lsyscache.c:1797
#define lfirst_node(type, lc)
Definition: pg_list.h:193
const FormData_pg_attribute * SystemAttributeByName(const char *attname)
Definition: heap.c:261
Oid get_index_am_oid(const char *amname, bool missing_ok)
Definition: amcmds.c:163
#define NoLock
Definition: lockdefs.h:34
List * RelationGetIndexExpressions(Relation relation)
Definition: relcache.c:4741
Oid values[FLEXIBLE_ARRAY_MEMBER]
Definition: c.h:609
bool transformed
Definition: parsenodes.h:2796
int errdetail(const char *fmt,...)
Definition: elog.c:957
char * indexcolname
Definition: parsenodes.h:702
#define DEFAULT_INDEX_TYPE
Definition: index.h:21
#define RelationGetRelationName(relation)
Definition: rel.h:490
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:193
Oid get_index_constraint(Oid indexId)
Definition: pg_depend.c:965
SubTransactionId oldFirstRelfilenodeSubid
Definition: parsenodes.h:2789
bool reset_default_tblspc
Definition: parsenodes.h:2179
ObjectType objtype
Definition: parsenodes.h:1779
List * lappend(List *list, void *datum)
Definition: list.c:321
char * idxname
Definition: parsenodes.h:2775
FormData_pg_index * Form_pg_index
Definition: pg_index.h:68
bool reset_default_tblspc
Definition: parsenodes.h:2799
bool if_not_exists
Definition: parsenodes.h:2798
#define lsecond_node(type, l)
Definition: pg_list.h:203
uintptr_t Datum
Definition: postgres.h:367
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1377
bool unique
Definition: parsenodes.h:2791
TupleDesc rd_att
Definition: rel.h:110
char * accessMethod
Definition: parsenodes.h:2777
Relation table_openrv(const RangeVar *relation, LOCKMODE lockmode)
Definition: table.c:68
#define InvalidOid
Definition: postgres_ext.h:36
FormData_pg_attribute
Definition: pg_attribute.h:177
int16 attnum
Definition: pg_attribute.h:79
#define ereport(elevel,...)
Definition: elog.h:144
List * opclass
Definition: parsenodes.h:704
bool is_from_type
Definition: parsenodes.h:652
Node * where_clause
Definition: parsenodes.h:2183
#define makeNode(_type_)
Definition: nodes.h:577
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:206
#define Assert(condition)
Definition: c.h:745
#define lfirst(lc)
Definition: pg_list.h:190
List * indexParams
Definition: parsenodes.h:2779
List * excludeOpNames
Definition: parsenodes.h:2784
static int list_length(const List *l)
Definition: pg_list.h:169
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110
bool initdeferred
Definition: parsenodes.h:2795
char * name
Definition: parsenodes.h:700
char * idxcomment
Definition: parsenodes.h:2785
#define InvalidSubTransactionId
Definition: c.h:526
#define DatumGetPointer(X)
Definition: postgres.h:549
bool concurrent
Definition: parsenodes.h:2797
bool isconstraint
Definition: parsenodes.h:2793
char * indexname
Definition: parsenodes.h:2177
int errmsg(const char *fmt,...)
Definition: elog.c:824
RangeVar * relation
Definition: parsenodes.h:1777
int i
#define NameStr(name)
Definition: c.h:622
ConstrType contype
Definition: parsenodes.h:2152
List * collation
Definition: parsenodes.h:703
char * colname
Definition: parsenodes.h:647
List * including
Definition: parsenodes.h:2169
#define copyObject(obj)
Definition: nodes.h:645
Definition: pg_list.h:50
#define RelationGetRelid(relation)
Definition: rel.h:456
char * access_method
Definition: parsenodes.h:2182
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:132
char * indexspace
Definition: parsenodes.h:2178
#define RelationGetNamespace(relation)
Definition: rel.h:497

◆ transformIndexConstraints()

static void transformIndexConstraints ( CreateStmtContext cxt)
static

Definition at line 1874 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_concat(), list_make1, NIL, CreateStmtContext::pkey, IndexStmt::primary, CreateStmtContext::relation, RangeVar::relname, transformIndexConstraint(), IndexStmt::unique, and IndexStmt::whereClause.

Referenced by transformAlterTableStmt(), and transformCreateStmt().

1875 {
1876  IndexStmt *index;
1877  List *indexlist = NIL;
1878  List *finalindexlist = NIL;
1879  ListCell *lc;
1880 
1881  /*
1882  * Run through the constraints that need to generate an index. For PRIMARY
1883  * KEY, mark each column as NOT NULL and create an index. For UNIQUE or
1884  * EXCLUDE, create an index as for PRIMARY KEY, but do not insist on NOT
1885  * NULL.
1886  */
1887  foreach(lc, cxt->ixconstraints)
1888  {
1889  Constraint *constraint = lfirst_node(Constraint, lc);
1890 
1891  Assert(constraint->contype == CONSTR_PRIMARY ||
1892  constraint->contype == CONSTR_UNIQUE ||
1893  constraint->contype == CONSTR_EXCLUSION);
1894 
1895  index = transformIndexConstraint(constraint, cxt);
1896 
1897  indexlist = lappend(indexlist, index);
1898  }
1899 
1900  /* Add in any indexes defined by LIKE ... INCLUDING INDEXES */
1901  foreach(lc, cxt->inh_indexes)
1902  {
1903  index = (IndexStmt *) lfirst(lc);
1904 
1905  if (index->primary)
1906  {
1907  if (cxt->pkey != NULL)
1908  ereport(ERROR,
1909  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1910  errmsg("multiple primary keys for table \"%s\" are not allowed",
1911  cxt->relation->relname)));
1912  cxt->pkey = index;
1913  }
1914 
1915  indexlist = lappend(indexlist, index);
1916  }
1917 
1918  /*
1919  * Scan the index list and remove any redundant index specifications. This
1920  * can happen if, for instance, the user writes UNIQUE PRIMARY KEY. A
1921  * strict reading of SQL would suggest raising an error instead, but that
1922  * strikes me as too anal-retentive. - tgl 2001-02-14
1923  *
1924  * XXX in ALTER TABLE case, it'd be nice to look for duplicate
1925  * pre-existing indexes, too.
1926  */
1927  if (cxt->pkey != NULL)
1928  {
1929  /* Make sure we keep the PKEY index in preference to others... */
1930  finalindexlist = list_make1(cxt->pkey);
1931  }
1932 
1933  foreach(lc, indexlist)
1934  {
1935  bool keep = true;
1936  ListCell *k;
1937 
1938  index = lfirst(lc);
1939 
1940  /* if it's pkey, it's already in finalindexlist */
1941  if (index == cxt->pkey)
1942  continue;
1943 
1944  foreach(k, finalindexlist)
1945  {
1946  IndexStmt *priorindex = lfirst(k);
1947 
1948  if (equal(index->indexParams, priorindex->indexParams) &&
1949  equal(index->indexIncludingParams, priorindex->indexIncludingParams) &&
1950  equal(index->whereClause, priorindex->whereClause) &&
1951  equal(index->excludeOpNames, priorindex->excludeOpNames) &&
1952  strcmp(index->accessMethod, priorindex->accessMethod) == 0 &&
1953  index->deferrable == priorindex->deferrable &&
1954  index->initdeferred == priorindex->initdeferred)
1955  {
1956  priorindex->unique |= index->unique;
1957 
1958  /*
1959  * If the prior index is as yet unnamed, and this one is
1960  * named, then transfer the name to the prior index. This
1961  * ensures that if we have named and unnamed constraints,
1962  * we'll use (at least one of) the names for the index.
1963  */
1964  if (priorindex->idxname == NULL)
1965  priorindex->idxname = index->idxname;
1966  keep = false;
1967  break;
1968  }
1969  }
1970 
1971  if (keep)
1972  finalindexlist = lappend(finalindexlist, index);
1973  }
1974 
1975  /*
1976  * Now append all the IndexStmts to cxt->alist. If we generated an ALTER
1977  * TABLE SET NOT NULL statement to support a primary key, it's already in
1978  * cxt->alist.
1979  */
1980  cxt->alist = list_concat(cxt->alist, finalindexlist);
1981 }
bool deferrable
Definition: parsenodes.h:2794
#define NIL
Definition: pg_list.h:65
bool primary
Definition: parsenodes.h:2792
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:3033
Node * whereClause
Definition: parsenodes.h:2783
List * list_concat(List *list1, const List *list2)
Definition: list.c:515
int errcode(int sqlerrcode)
Definition: elog.c:610
List * indexIncludingParams
Definition: parsenodes.h:2780
Definition: type.h:89
#define list_make1(x1)
Definition: pg_list.h:227
char * relname
Definition: primnodes.h:68
RangeVar * relation
Definition: parse_utilcmd.c:80
IndexStmt * pkey
Definition: parse_utilcmd.c:95
#define ERROR
Definition: elog.h:43
#define lfirst_node(type, lc)
Definition: pg_list.h:193
List * lappend(List *list, void *datum)
Definition: list.c:321
char * idxname
Definition: parsenodes.h:2775
static IndexStmt * transformIndexConstraint(Constraint *constraint, CreateStmtContext *cxt)
bool unique
Definition: parsenodes.h:2791
char * accessMethod
Definition: parsenodes.h:2777
#define ereport(elevel,...)
Definition: elog.h:144
#define Assert(condition)
Definition: c.h:745
#define lfirst(lc)
Definition: pg_list.h:190
List * indexParams
Definition: parsenodes.h:2779
List * excludeOpNames
Definition: parsenodes.h:2784
bool initdeferred
Definition: parsenodes.h:2795
int errmsg(const char *fmt,...)
Definition: elog.c:824
ConstrType contype
Definition: parsenodes.h:2152
Definition: pg_list.h:50

◆ transformIndexStmt()

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

Definition at line 2643 of file parse_utilcmd.c.

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

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

2644 {
2645  ParseState *pstate;
2646  ParseNamespaceItem *nsitem;
2647  ListCell *l;
2648  Relation rel;
2649 
2650  /* Nothing to do if statement already transformed. */
2651  if (stmt->transformed)
2652  return stmt;
2653 
2654  /*
2655  * We must not scribble on the passed-in IndexStmt, so copy it. (This is
2656  * overkill, but easy.)
2657  */
2658  stmt = copyObject(stmt);
2659 
2660  /* Set up pstate */
2661  pstate = make_parsestate(NULL);
2662  pstate->p_sourcetext = queryString;
2663 
2664  /*
2665  * Put the parent table into the rtable so that the expressions can refer
2666  * to its fields without qualification. Caller is responsible for locking
2667  * relation, but we still need to open it.
2668  */
2669  rel = relation_open(relid, NoLock);
2670  nsitem = addRangeTableEntryForRelation(pstate, rel,
2672  NULL, false, true);
2673 
2674  /* no to join list, yes to namespaces */
2675  addNSItemToQuery(pstate, nsitem, false, true, true);
2676 
2677  /* take care of the where clause */
2678  if (stmt->whereClause)
2679  {
2680  stmt->whereClause = transformWhereClause(pstate,
2681  stmt->whereClause,
2683  "WHERE");
2684  /* we have to fix its collations too */
2685  assign_expr_collations(pstate, stmt->whereClause);
2686  }
2687 
2688  /* take care of any index expressions */
2689  foreach(l, stmt->indexParams)
2690  {
2691  IndexElem *ielem = (IndexElem *) lfirst(l);
2692 
2693  if (ielem->expr)
2694  {
2695  /* Extract preliminary index col name before transforming expr */
2696  if (ielem->indexcolname == NULL)
2697  ielem->indexcolname = FigureIndexColname(ielem->expr);
2698 
2699  /* Now do parse transformation of the expression */
2700  ielem->expr = transformExpr(pstate, ielem->expr,
2702 
2703  /* We have to fix its collations too */
2704  assign_expr_collations(pstate, ielem->expr);
2705 
2706  /*
2707  * transformExpr() should have already rejected subqueries,
2708  * aggregates, window functions, and SRFs, based on the EXPR_KIND_
2709  * for an index expression.
2710  *
2711  * DefineIndex() will make more checks.
2712  */
2713  }
2714  }
2715 
2716  /*
2717  * Check that only the base rel is mentioned. (This should be dead code
2718  * now that add_missing_from is history.)
2719  */
2720  if (list_length(pstate->p_rtable) != 1)
2721  ereport(ERROR,
2722  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2723  errmsg("index expressions and predicates can refer only to the table being indexed")));
2724 
2725  free_parsestate(pstate);
2726 
2727  /* Close relation */
2728  table_close(rel, NoLock);
2729 
2730  /* Mark statement as successfully transformed */
2731  stmt->transformed = true;
2732 
2733  return stmt;
2734 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:145
Node * whereClause
Definition: parsenodes.h:2783
#define AccessShareLock
Definition: lockdefs.h:36
void addNSItemToQuery(ParseState *pstate, ParseNamespaceItem *nsitem, bool addToJoinList, bool addToRelNameSpace, bool addToVarNameSpace)
int errcode(int sqlerrcode)
Definition: elog.c:610
char * FigureIndexColname(Node *node)
ParseNamespaceItem * addRangeTableEntryForRelation(ParseState *pstate, Relation rel, int lockmode, Alias *alias, bool inh, bool inFromCl)
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:43
void assign_expr_collations(ParseState *pstate, Node *expr)
Node * expr
Definition: parsenodes.h:701
#define ERROR
Definition: elog.h:43
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:48
#define NoLock
Definition: lockdefs.h:34
bool transformed
Definition: parsenodes.h:2796
char * indexcolname
Definition: parsenodes.h:702
const char * p_sourcetext
Definition: parse_node.h:179
#define ereport(elevel,...)
Definition: elog.h:144
#define lfirst(lc)
Definition: pg_list.h:190
Node * transformWhereClause(ParseState *pstate, Node *clause, ParseExprKind exprKind, const char *constructName)
List * indexParams
Definition: parsenodes.h:2779
static int list_length(const List *l)
Definition: pg_list.h:169
int errmsg(const char *fmt,...)
Definition: elog.c:824
#define copyObject(obj)
Definition: nodes.h:645
void free_parsestate(ParseState *pstate)
Definition: parse_node.c:76
List * p_rtable
Definition: parse_node.h:180

◆ transformOfType()

static void transformOfType ( CreateStmtContext cxt,
TypeName ofTypename 
)
static

Definition at line 1304 of file parse_utilcmd.c.

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

Referenced by transformCreateStmt().

1305 {
1306  HeapTuple tuple;
1307  TupleDesc tupdesc;
1308  int i;
1309  Oid ofTypeId;
1310 
1311  AssertArg(ofTypename);
1312 
1313  tuple = typenameType(NULL, ofTypename, NULL);
1314  check_of_type(tuple);
1315  ofTypeId = ((Form_pg_type) GETSTRUCT(tuple))->oid;
1316  ofTypename->typeOid = ofTypeId; /* cached for later */
1317 
1318  tupdesc = lookup_rowtype_tupdesc(ofTypeId, -1);
1319  for (i = 0; i < tupdesc->natts; i++)
1320  {
1321  Form_pg_attribute attr = TupleDescAttr(tupdesc, i);
1322  ColumnDef *n;
1323 
1324  if (attr->attisdropped)
1325  continue;
1326 
1327  n = makeNode(ColumnDef);
1328  n->colname = pstrdup(NameStr(attr->attname));
1329  n->typeName = makeTypeNameFromOid(attr->atttypid, attr->atttypmod);
1330  n->inhcount = 0;
1331  n->is_local = true;
1332  n->is_not_null = false;
1333  n->is_from_type = true;
1334  n->storage = 0;
1335  n->raw_default = NULL;
1336  n->cooked_default = NULL;
1337  n->collClause = NULL;
1338  n->collOid = attr->attcollation;
1339  n->constraints = NIL;
1340  n->location = -1;
1341  cxt->columns = lappend(cxt->columns, n);
1342  }
1343  DecrTupleDescRefCount(tupdesc);
1344 
1345  ReleaseSysCache(tuple);
1346 }
#define NIL
Definition: pg_list.h:65
Oid typeOid
Definition: parsenodes.h:211
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
Type typenameType(ParseState *pstate, const TypeName *typeName, int32 *typmod_p)
Definition: parse_type.c:264
char storage
Definition: parsenodes.h:653
TupleDesc lookup_rowtype_tupdesc(Oid type_id, int32 typmod)
Definition: typcache.c:1710
bool is_local
Definition: parsenodes.h:650
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
List * constraints
Definition: parsenodes.h:662
char * pstrdup(const char *in)
Definition: mcxt.c:1186
bool is_not_null
Definition: parsenodes.h:651
unsigned int Oid
Definition: postgres_ext.h:31
Node * cooked_default
Definition: parsenodes.h:655
void check_of_type(HeapTuple typetuple)
Definition: tablecmds.c:5885
Oid collOid
Definition: parsenodes.h:661
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:193
int location
Definition: parsenodes.h:664
#define AssertArg(condition)
Definition: c.h:747
Node * raw_default
Definition: parsenodes.h:654
List * lappend(List *list, void *datum)
Definition: list.c:321
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
TypeName * makeTypeNameFromOid(Oid typeOid, int32 typmod)
Definition: makefuncs.c:472
bool is_from_type
Definition: parsenodes.h:652
#define makeNode(_type_)
Definition: nodes.h:577
void DecrTupleDescRefCount(TupleDesc tupdesc)
Definition: tupdesc.c:393
FormData_pg_type * Form_pg_type
Definition: pg_type.h:255
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:622
char * colname
Definition: parsenodes.h:647

◆ transformPartitionBound()

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

Definition at line 3774 of file parse_utilcmd.c.

References Assert, castNode, copyObject, deparse_context_for(), deparse_expression(), elog, equal(), ereport, errcode(), errmsg(), ERROR, exprLocation(), get_attname(), get_partition_col_collation(), get_partition_col_typid(), get_partition_col_typmod(), get_partition_exprs(), get_partition_natts(), get_partition_strategy(), PartitionBoundSpec::is_default, sort-test::key, lappend(), lfirst, linitial, list_length(), PartitionBoundSpec::listdatums, PartitionBoundSpec::lowerdatums, NIL, parser_errposition(), PartitionKeyData::partattrs, PARTITION_STRATEGY_HASH, PARTITION_STRATEGY_LIST, PARTITION_STRATEGY_RANGE, RelationGetPartitionKey(), RelationGetRelationName, RelationGetRelid, PartitionBoundSpec::strategy, transformPartitionBoundValue(), transformPartitionRangeBounds(), PartitionBoundSpec::upperdatums, and value.

Referenced by DefineRelation(), and transformPartitionCmd().

3776 {
3777  PartitionBoundSpec *result_spec;
3779  char strategy = get_partition_strategy(key);
3780  int partnatts = get_partition_natts(key);
3781  List *partexprs = get_partition_exprs(key);
3782 
3783  /* Avoid scribbling on input */
3784  result_spec = copyObject(spec);
3785 
3786  if (spec->is_default)
3787  {
3788  /*
3789  * Hash partitioning does not support a default partition; there's no
3790  * use case for it (since the set of partitions to create is perfectly
3791  * defined), and if users do get into it accidentally, it's hard to
3792  * back out from it afterwards.
3793  */
3794  if (strategy == PARTITION_STRATEGY_HASH)
3795  ereport(ERROR,
3796  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3797  errmsg("a hash-partitioned table may not have a default partition")));
3798 
3799  /*
3800  * In case of the default partition, parser had no way to identify the
3801  * partition strategy. Assign the parent's strategy to the default
3802  * partition bound spec.
3803  */
3804  result_spec->strategy = strategy;
3805 
3806  return result_spec;
3807  }
3808 
3809  if (strategy == PARTITION_STRATEGY_HASH)
3810  {
3811  if (spec->strategy != PARTITION_STRATEGY_HASH)
3812  ereport(ERROR,
3813  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3814  errmsg("invalid bound specification for a hash partition"),
3815  parser_errposition(pstate, exprLocation((Node *) spec))));
3816 
3817  if (spec->modulus <= 0)
3818  ereport(ERROR,
3819  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3820  errmsg("modulus for hash partition must be a positive integer")));
3821 
3822  Assert(spec->remainder >= 0);
3823 
3824  if (spec->remainder >= spec->modulus)
3825  ereport(ERROR,
3826  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3827  errmsg("remainder for hash partition must be less than modulus")));
3828  }
3829  else if (strategy == PARTITION_STRATEGY_LIST)
3830  {
3831  ListCell *cell;
3832  char *colname;
3833  Oid coltype;
3834  int32 coltypmod;
3835  Oid partcollation;
3836 
3837  if (spec->strategy != PARTITION_STRATEGY_LIST)
3838  ereport(ERROR,
3839  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3840  errmsg("invalid bound specification for a list partition"),
3841  parser_errposition(pstate, exprLocation((Node *) spec))));
3842 
3843  /* Get the only column's name in case we need to output an error */
3844  if (key->partattrs[0] != 0)
3845  colname = get_attname(RelationGetRelid(parent),
3846  key->partattrs[0], false);
3847  else
3848  colname = deparse_expression((Node *) linitial(partexprs),
3850  RelationGetRelid(parent)),
3851  false, false);
3852  /* Need its type data too */
3853  coltype = get_partition_col_typid(key, 0);
3854  coltypmod = get_partition_col_typmod(key, 0);
3855  partcollation = get_partition_col_collation(key, 0);
3856 
3857  result_spec->listdatums = NIL;
3858  foreach(cell, spec->listdatums)
3859  {
3860  Node *expr = lfirst(cell);
3861  Const *value;
3862  ListCell *cell2;
3863  bool duplicate;
3864 
3865  value = transformPartitionBoundValue(pstate, expr,
3866  colname, coltype, coltypmod,
3867  partcollation);
3868 
3869  /* Don't add to the result if the value is a duplicate */
3870  duplicate = false;
3871  foreach(cell2, result_spec->listdatums)
3872  {
3873  Const *value2 = castNode(Const, lfirst(cell2));
3874 
3875  if (equal(value, value2))
3876  {
3877  duplicate = true;
3878  break;
3879  }
3880  }
3881  if (duplicate)
3882  continue;
3883 
3884  result_spec->listdatums = lappend(result_spec->listdatums,
3885  value);
3886  }
3887  }
3888  else if (strategy == PARTITION_STRATEGY_RANGE)
3889  {
3890  if (spec->strategy != PARTITION_STRATEGY_RANGE)
3891  ereport(ERROR,
3892  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3893  errmsg("invalid bound specification for a range partition"),
3894  parser_errposition(pstate, exprLocation((Node *) spec))));
3895 
3896  if (list_length(spec->lowerdatums) != partnatts)
3897  ereport(ERROR,
3898  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3899  errmsg("FROM must specify exactly one value per partitioning column")));
3900  if (list_length(spec->upperdatums) != partnatts)
3901  ereport(ERROR,
3902  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3903  errmsg("TO must specify exactly one value per partitioning column")));
3904 
3905  /*
3906  * Convert raw parse nodes into PartitionRangeDatum nodes and perform
3907  * any necessary validation.
3908  */
3909  result_spec->lowerdatums =
3911  parent);
3912  result_spec->upperdatums =
3914  parent);
3915  }
3916  else
3917  elog(ERROR, "unexpected partition strategy: %d", (int) strategy);
3918 
3919  return result_spec;
3920 }
#define NIL
Definition: pg_list.h:65
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1191
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:3033
#define castNode(_type_, nodeptr)
Definition: nodes.h:598
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:529
static int get_partition_natts(PartitionKey key)
Definition: partcache.h:64
int errcode(int sqlerrcode)
Definition: elog.c:610
PartitionKey RelationGetPartitionKey(Relation rel)
Definition: partcache.c:54
unsigned int Oid
Definition: postgres_ext.h:31
signed int int32
Definition: c.h:362
static List * get_partition_exprs(PartitionKey key)
Definition: partcache.h:70
#define linitial(l)
Definition: pg_list.h:195
#define ERROR
Definition: elog.h:43
static Const * transformPartitionBoundValue(ParseState *pstate, Node *con, const char *colName, Oid colType, int32 colTypmod, Oid partCollation)
static List * transformPartitionRangeBounds(ParseState *pstate, List *blist, Relation parent)
List * deparse_context_for(const char *aliasname, Oid relid)
Definition: ruleutils.c:3283
#define RelationGetRelationName(relation)
Definition: rel.h:490
List * lappend(List *list, void *datum)
Definition: list.c:321
AttrNumber * partattrs
Definition: partcache.h:28
#define PARTITION_STRATEGY_HASH
Definition: parsenodes.h:800
static struct @143 value
#define ereport(elevel,...)
Definition: elog.h:144
#define Assert(condition)
Definition: c.h:745
#define lfirst(lc)
Definition: pg_list.h:190
char * deparse_expression(Node *expr, List *dpcontext, bool forceprefix, bool showimplicit)
Definition: ruleutils.c:3223
static int list_length(const List *l)
Definition: pg_list.h:169
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110
#define PARTITION_STRATEGY_LIST
Definition: parsenodes.h:801
static Oid get_partition_col_collation(PartitionKey key, int col)
Definition: partcache.h:97
#define PARTITION_STRATEGY_RANGE
Definition: parsenodes.h:802
int errmsg(const char *fmt,...)
Definition: elog.c:824
#define elog(elevel,...)
Definition: elog.h:214
char * get_attname(Oid relid, AttrNumber attnum, bool missing_ok)
Definition: lsyscache.c:825
#define copyObject(obj)
Definition: nodes.h:645
static int get_partition_strategy(PartitionKey key)
Definition: partcache.h:58
Definition: pg_list.h:50
#define RelationGetRelid(relation)
Definition: rel.h:456

◆ transformPartitionBoundValue()

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

Definition at line 4084 of file parse_utilcmd.c.

References Assert, COERCE_IMPLICIT_CAST, coerce_to_target_type(), COERCION_ASSIGNMENT, contain_var_clause(), elog, ereport, errcode(), errhint(), errmsg(), ERROR, evaluate_expr(), EXPR_KIND_PARTITION_BOUND, exprCollation(), expression_planner(), exprLocation(), exprType(), format_type_be(), get_collation_name(), IsA, OidIsValid, parser_errposition(), transformExpr(), type_is_collatable(), and value.

Referenced by transformPartitionBound(), and transformPartitionRangeBounds().

4087 {
4088  Node *value;
4089 
4090  /* Transform raw parsetree */
4091  value = transformExpr(pstate, val, EXPR_KIND_PARTITION_BOUND);
4092 
4093  /*
4094  * Check that the input expression's collation is compatible with one
4095  * specified for the parent's partition key (partcollation). Don't throw
4096  * an error if it's the default collation which we'll replace with the
4097  * parent's collation anyway.
4098  */
4099  if (IsA(value, CollateExpr))
4100  {
4101  Oid exprCollOid = exprCollation(value);
4102 
4103  /*
4104  * Check we have a collation iff it is a collatable type. The only
4105  * expected failures here are (1) COLLATE applied to a noncollatable
4106  * type, or (2) partition bound expression had an unresolved
4107  * collation. But we might as well code this to be a complete
4108  * consistency check.
4109  */
4110  if (type_is_collatable(colType))
4111  {
4112  if (!OidIsValid(exprCollOid))
4113  ereport(ERROR,
4114  (errcode(ERRCODE_INDETERMINATE_COLLATION),
4115  errmsg("could not determine which collation to use for partition bound expression"),
4116  errhint("Use the COLLATE clause to set the collation explicitly.")));
4117  }
4118  else
4119  {
4120  if (OidIsValid(exprCollOid))
4121  ereport(ERROR,
4122  (errcode(ERRCODE_DATATYPE_MISMATCH),
4123  errmsg("collations are not supported by type %s",
4124  format_type_be(colType))));
4125  }
4126 
4127  if (OidIsValid(exprCollOid) &&
4128  exprCollOid != DEFAULT_COLLATION_OID &&
4129  exprCollOid != partCollation)
4130  ereport(ERROR,
4131  (errcode(ERRCODE_DATATYPE_MISMATCH),
4132  errmsg("collation of partition bound value for column \"%s\" does not match partition key collation \"%s\"",
4133  colName, get_collation_name(partCollation)),
4134  parser_errposition(pstate, exprLocation(value))));
4135  }
4136 
4137  /* Coerce to correct type */
4138  value = coerce_to_target_type(pstate,
4139  value, exprType(value),
4140  colType,
4141  colTypmod,
4144  -1);
4145 
4146  if (value == NULL)
4147  ereport(ERROR,
4148  (errcode(ERRCODE_DATATYPE_MISMATCH),
4149  errmsg("specified value cannot be cast to type %s for column \"%s\"",
4150  format_type_be(colType), colName),
4151  parser_errposition(pstate, exprLocation(val))));
4152 
4153  /* Simplify the expression, in case we had a coercion */
4154  if (!IsA(value, Const))
4155  value = (Node *) expression_planner((Expr *) value);
4156 
4157  /*
4158  * transformExpr() should have already rejected column references,
4159  * subqueries, aggregates, window functions, and SRFs, based on the
4160  * EXPR_KIND_ for a default expression.
4161  */
4162  Assert(!contain_var_clause(value));
4163 
4164  /*
4165  * Evaluate the expression, assigning the partition key's collation to the
4166  * resulting Const expression.
4167  */
4168  value = (Node *) evaluate_expr((Expr *) value, colType, colTypmod,
4169  partCollation);
4170  if (!IsA(value, Const))
4171  elog(ERROR, "could not evaluate partition bound expression");
4172 
4173  return (Const *) value;
4174 }
Expr * evaluate_expr(Expr *expr, Oid result_type, int32 result_typmod, Oid result_collation)
Definition: clauses.c:4773
#define IsA(nodeptr, _type_)
Definition: nodes.h:580
int errhint(const char *fmt,...)
Definition: elog.c:1071
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1191
char * get_collation_name(Oid colloid)
Definition: lsyscache.c:1033
Expr * expression_planner(Expr *expr)
Definition: planner.c:6151
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:145
Definition: nodes.h:529
int errcode(int sqlerrcode)
Definition: elog.c:610
char * format_type_be(Oid type_oid)
Definition: format_type.c:339
bool contain_var_clause(Node *node)
Definition: var.c:331
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:651
#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:77
static struct @143 value
#define ereport(elevel,...)
Definition: elog.h:144
#define Assert(condition)
Definition: c.h:745
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:719
int errmsg(const char *fmt,...)
Definition: elog.c:824
#define elog(elevel,...)
Definition: elog.h:214
bool type_is_collatable(Oid typid)
Definition: lsyscache.c:2958
long val
Definition: informix.c:664

◆ transformPartitionCmd()

static void transformPartitionCmd ( CreateStmtContext cxt,
PartitionCmd cmd 
)
static

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

3722 {
3723  Relation parentRel = cxt->rel;
3724 
3725  switch (parentRel->rd_rel->relkind)
3726  {
3727  case RELKIND_PARTITIONED_TABLE:
3728  /* transform the partition bound, if any */
3729  Assert(RelationGetPartitionKey(parentRel) != NULL);
3730  if (cmd->bound != NULL)
3731  cxt->partbound = transformPartitionBound(cxt->pstate, parentRel,
3732  cmd->bound);
3733  break;
3734  case RELKIND_PARTITIONED_INDEX:
3735 
3736  /*
3737  * A partitioned index cannot have a partition bound set. ALTER
3738  * INDEX prevents that with its grammar, but not ALTER TABLE.
3739  */
3740  if (cmd->bound != NULL)
3741  ereport(ERROR,
3742  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3743  errmsg("\"%s\" is not a partitioned table",
3744  RelationGetRelationName(parentRel))));
3745  break;
3746  case RELKIND_RELATION:
3747  /* the table must be partitioned */
3748  ereport(ERROR,
3749  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3750  errmsg("table \"%s\" is not partitioned",
3751  RelationGetRelationName(parentRel))));
3752  break;
3753  case RELKIND_INDEX:
3754  /* the index must be partitioned */
3755  ereport(ERROR,
3756  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3757  errmsg("index \"%s\" is not partitioned",
3758  RelationGetRelationName(parentRel))));
3759  break;
3760  default:
3761  /* parser shouldn't let this case through */
3762  elog(ERROR, "\"%s\" is not a partitioned table or index",
3763  RelationGetRelationName(parentRel));
3764  break;
3765  }
3766 }
int errcode(int sqlerrcode)
Definition: elog.c:610
PartitionKey RelationGetPartitionKey(Relation rel)
Definition: partcache.c:54
Form_pg_class rd_rel
Definition: rel.h:109
PartitionBoundSpec * transformPartitionBound(ParseState *pstate, Relation parent, PartitionBoundSpec *spec)
ParseState * pstate
Definition: parse_utilcmd.c:78
#define ERROR
Definition: elog.h:43
#define RelationGetRelationName(relation)
Definition: rel.h:490
PartitionBoundSpec * partbound
Definition: parse_utilcmd.c:97
#define ereport(elevel,...)
Definition: elog.h:144
#define Assert(condition)
Definition: c.h:745
PartitionBoundSpec * bound
Definition: parsenodes.h:861
int errmsg(const char *fmt,...)
Definition: elog.c:824
#define elog(elevel,...)
Definition: elog.h:214

◆ transformPartitionRangeBounds()